1 /* $OpenBSD: ssh-agent.c,v 1.159 2008/06/28 14:05:15 djm 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.
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
51 #include "openbsd-compat/sys-queue.h"
53 #include <openssl/evp.h>
54 #include <openssl/md5.h>
55 #include "openbsd-compat/openssl-compat.h"
84 #if defined(HAVE_SYS_PRCTL_H)
85 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
102 u_int sockets_alloc = 0;
103 SocketEntry *sockets = NULL;
105 typedef struct identity {
106 TAILQ_ENTRY(identity) next;
115 TAILQ_HEAD(idqueue, identity) idlist;
118 /* private key table, one per protocol version */
123 /* pid of shell == parent of agent */
124 pid_t parent_pid = -1;
125 u_int parent_alive_interval = 0;
127 /* pathname and directory for AUTH_SOCKET */
128 char socket_name[MAXPATHLEN];
129 char socket_dir[MAXPATHLEN];
133 char *lock_passwd = NULL;
135 extern char *__progname;
137 /* Default lifetime (0 == forever) */
138 static int lifetime = 0;
141 close_socket(SocketEntry *e)
145 e->type = AUTH_UNUSED;
146 buffer_free(&e->input);
147 buffer_free(&e->output);
148 buffer_free(&e->request);
156 for (i = 0; i <=2; i++) {
157 TAILQ_INIT(&idtable[i].idlist);
158 idtable[i].nentries = 0;
162 /* return private key table for requested protocol version */
164 idtab_lookup(int version)
166 if (version < 1 || version > 2)
167 fatal("internal error, bad protocol version %d", version);
168 return &idtable[version];
172 free_identity(Identity *id)
179 /* return matching private key for given public key */
181 lookup_identity(Key *key, int version)
185 Idtab *tab = idtab_lookup(version);
186 TAILQ_FOREACH(id, &tab->idlist, next) {
187 if (key_equal(key, id->key))
193 /* Check confirmation of keysign request */
195 confirm_key(Identity *id)
200 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
201 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
209 /* send list of supported public keys to 'client' */
211 process_request_identities(SocketEntry *e, int version)
213 Idtab *tab = idtab_lookup(version);
218 buffer_put_char(&msg, (version == 1) ?
219 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
220 buffer_put_int(&msg, tab->nentries);
221 TAILQ_FOREACH(id, &tab->idlist, next) {
222 if (id->key->type == KEY_RSA1) {
223 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
224 buffer_put_bignum(&msg, id->key->rsa->e);
225 buffer_put_bignum(&msg, id->key->rsa->n);
229 key_to_blob(id->key, &blob, &blen);
230 buffer_put_string(&msg, blob, blen);
233 buffer_put_cstring(&msg, id->comment);
235 buffer_put_int(&e->output, buffer_len(&msg));
236 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
242 process_authentication_challenge1(SocketEntry *e)
244 u_char buf[32], mdbuf[16], session_id[16];
254 key = key_new(KEY_RSA1);
255 if ((challenge = BN_new()) == NULL)
256 fatal("process_authentication_challenge1: BN_new failed");
258 (void) buffer_get_int(&e->request); /* ignored */
259 buffer_get_bignum(&e->request, key->rsa->e);
260 buffer_get_bignum(&e->request, key->rsa->n);
261 buffer_get_bignum(&e->request, challenge);
263 /* Only protocol 1.1 is supported */
264 if (buffer_len(&e->request) == 0)
266 buffer_get(&e->request, session_id, 16);
267 response_type = buffer_get_int(&e->request);
268 if (response_type != 1)
271 id = lookup_identity(key, 1);
272 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
273 Key *private = id->key;
274 /* Decrypt the challenge using the private key. */
275 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
278 /* The response is MD5 of decrypted challenge plus session id. */
279 len = BN_num_bytes(challenge);
280 if (len <= 0 || len > 32) {
281 logit("process_authentication_challenge: bad challenge length %d", len);
285 BN_bn2bin(challenge, buf + 32 - len);
287 MD5_Update(&md, buf, 32);
288 MD5_Update(&md, session_id, 16);
289 MD5_Final(mdbuf, &md);
291 /* Send the response. */
292 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
293 for (i = 0; i < 16; i++)
294 buffer_put_char(&msg, mdbuf[i]);
299 /* Unknown identity or protocol error. Send failure. */
300 buffer_put_char(&msg, SSH_AGENT_FAILURE);
302 buffer_put_int(&e->output, buffer_len(&msg));
303 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
305 BN_clear_free(challenge);
311 process_sign_request2(SocketEntry *e)
313 u_char *blob, *data, *signature = NULL;
314 u_int blen, dlen, slen = 0;
315 extern int datafellows;
323 blob = buffer_get_string(&e->request, &blen);
324 data = buffer_get_string(&e->request, &dlen);
326 flags = buffer_get_int(&e->request);
327 odatafellows = datafellows;
328 if (flags & SSH_AGENT_OLD_SIGNATURE)
329 datafellows = SSH_BUG_SIGBLOB;
331 key = key_from_blob(blob, blen);
333 Identity *id = lookup_identity(key, 2);
334 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
335 ok = key_sign(id->key, &signature, &slen, data, dlen);
340 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
341 buffer_put_string(&msg, signature, slen);
343 buffer_put_char(&msg, SSH_AGENT_FAILURE);
345 buffer_put_int(&e->output, buffer_len(&msg));
346 buffer_append(&e->output, buffer_ptr(&msg),
351 if (signature != NULL)
353 datafellows = odatafellows;
358 process_remove_identity(SocketEntry *e, int version)
367 key = key_new(KEY_RSA1);
368 bits = buffer_get_int(&e->request);
369 buffer_get_bignum(&e->request, key->rsa->e);
370 buffer_get_bignum(&e->request, key->rsa->n);
372 if (bits != key_size(key))
373 logit("Warning: identity keysize mismatch: actual %u, announced %u",
374 key_size(key), bits);
377 blob = buffer_get_string(&e->request, &blen);
378 key = key_from_blob(blob, blen);
383 Identity *id = lookup_identity(key, version);
386 * We have this key. Free the old key. Since we
387 * don't want to leave empty slots in the middle of
388 * the array, we actually free the key there and move
389 * all the entries between the empty slot and the end
392 Idtab *tab = idtab_lookup(version);
393 if (tab->nentries < 1)
394 fatal("process_remove_identity: "
395 "internal error: tab->nentries %d",
397 TAILQ_REMOVE(&tab->idlist, id, next);
404 buffer_put_int(&e->output, 1);
405 buffer_put_char(&e->output,
406 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
410 process_remove_all_identities(SocketEntry *e, int version)
412 Idtab *tab = idtab_lookup(version);
415 /* Loop over all identities and clear the keys. */
416 for (id = TAILQ_FIRST(&tab->idlist); id;
417 id = TAILQ_FIRST(&tab->idlist)) {
418 TAILQ_REMOVE(&tab->idlist, id, next);
422 /* Mark that there are no identities. */
426 buffer_put_int(&e->output, 1);
427 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
430 /* removes expired keys and returns number of seconds until the next expiry */
434 u_int deadline = 0, now = time(NULL);
439 for (version = 1; version < 3; version++) {
440 tab = idtab_lookup(version);
441 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
442 nxt = TAILQ_NEXT(id, next);
445 if (now >= id->death) {
446 debug("expiring key '%s'", id->comment);
447 TAILQ_REMOVE(&tab->idlist, id, next);
451 deadline = (deadline == 0) ? id->death :
452 MIN(deadline, id->death);
455 if (deadline == 0 || deadline <= now)
458 return (deadline - now);
462 process_add_identity(SocketEntry *e, int version)
464 Idtab *tab = idtab_lookup(version);
466 int type, success = 0, death = 0, confirm = 0;
467 char *type_name, *comment;
472 k = key_new_private(KEY_RSA1);
473 (void) buffer_get_int(&e->request); /* ignored */
474 buffer_get_bignum(&e->request, k->rsa->n);
475 buffer_get_bignum(&e->request, k->rsa->e);
476 buffer_get_bignum(&e->request, k->rsa->d);
477 buffer_get_bignum(&e->request, k->rsa->iqmp);
479 /* SSH and SSL have p and q swapped */
480 buffer_get_bignum(&e->request, k->rsa->q); /* p */
481 buffer_get_bignum(&e->request, k->rsa->p); /* q */
483 /* Generate additional parameters */
484 rsa_generate_additional_parameters(k->rsa);
487 type_name = buffer_get_string(&e->request, NULL);
488 type = key_type_from_name(type_name);
492 k = key_new_private(type);
493 buffer_get_bignum2(&e->request, k->dsa->p);
494 buffer_get_bignum2(&e->request, k->dsa->q);
495 buffer_get_bignum2(&e->request, k->dsa->g);
496 buffer_get_bignum2(&e->request, k->dsa->pub_key);
497 buffer_get_bignum2(&e->request, k->dsa->priv_key);
500 k = key_new_private(type);
501 buffer_get_bignum2(&e->request, k->rsa->n);
502 buffer_get_bignum2(&e->request, k->rsa->e);
503 buffer_get_bignum2(&e->request, k->rsa->d);
504 buffer_get_bignum2(&e->request, k->rsa->iqmp);
505 buffer_get_bignum2(&e->request, k->rsa->p);
506 buffer_get_bignum2(&e->request, k->rsa->q);
508 /* Generate additional parameters */
509 rsa_generate_additional_parameters(k->rsa);
512 buffer_clear(&e->request);
517 /* enable blinding */
521 if (RSA_blinding_on(k->rsa, NULL) != 1) {
522 error("process_add_identity: RSA_blinding_on failed");
528 comment = buffer_get_string(&e->request, NULL);
533 while (buffer_len(&e->request)) {
534 switch ((type = buffer_get_char(&e->request))) {
535 case SSH_AGENT_CONSTRAIN_LIFETIME:
536 death = time(NULL) + buffer_get_int(&e->request);
538 case SSH_AGENT_CONSTRAIN_CONFIRM:
542 error("process_add_identity: "
543 "Unknown constraint type %d", type);
550 if (lifetime && !death)
551 death = time(NULL) + lifetime;
552 if ((id = lookup_identity(k, version)) == NULL) {
553 id = xmalloc(sizeof(Identity));
555 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
556 /* Increment the number of identities. */
562 id->comment = comment;
564 id->confirm = confirm;
566 buffer_put_int(&e->output, 1);
567 buffer_put_char(&e->output,
568 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
571 /* XXX todo: encrypt sensitive data with passphrase */
573 process_lock_agent(SocketEntry *e, int lock)
578 passwd = buffer_get_string(&e->request, NULL);
579 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
581 memset(lock_passwd, 0, strlen(lock_passwd));
585 } else if (!locked && lock) {
587 lock_passwd = xstrdup(passwd);
590 memset(passwd, 0, strlen(passwd));
593 buffer_put_int(&e->output, 1);
594 buffer_put_char(&e->output,
595 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
599 no_identities(SocketEntry *e, u_int type)
604 buffer_put_char(&msg,
605 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
606 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
607 buffer_put_int(&msg, 0);
608 buffer_put_int(&e->output, buffer_len(&msg));
609 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
615 process_add_smartcard_key(SocketEntry *e)
617 char *sc_reader_id = NULL, *pin;
618 int i, type, version, success = 0, death = 0, confirm = 0;
623 sc_reader_id = buffer_get_string(&e->request, NULL);
624 pin = buffer_get_string(&e->request, NULL);
626 while (buffer_len(&e->request)) {
627 switch ((type = buffer_get_char(&e->request))) {
628 case SSH_AGENT_CONSTRAIN_LIFETIME:
629 death = time(NULL) + buffer_get_int(&e->request);
631 case SSH_AGENT_CONSTRAIN_CONFIRM:
635 error("process_add_smartcard_key: "
636 "Unknown constraint type %d", type);
642 if (lifetime && !death)
643 death = time(NULL) + lifetime;
645 keys = sc_get_keys(sc_reader_id, pin);
649 if (keys == NULL || keys[0] == NULL) {
650 error("sc_get_keys failed");
653 for (i = 0; keys[i] != NULL; i++) {
655 version = k->type == KEY_RSA1 ? 1 : 2;
656 tab = idtab_lookup(version);
657 if (lookup_identity(k, version) == NULL) {
658 id = xmalloc(sizeof(Identity));
660 id->comment = sc_get_key_label(k);
662 id->confirm = confirm;
663 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
673 buffer_put_int(&e->output, 1);
674 buffer_put_char(&e->output,
675 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
679 process_remove_smartcard_key(SocketEntry *e)
681 char *sc_reader_id = NULL, *pin;
682 int i, version, success = 0;
683 Key **keys, *k = NULL;
687 sc_reader_id = buffer_get_string(&e->request, NULL);
688 pin = buffer_get_string(&e->request, NULL);
689 keys = sc_get_keys(sc_reader_id, pin);
693 if (keys == NULL || keys[0] == NULL) {
694 error("sc_get_keys failed");
697 for (i = 0; keys[i] != NULL; i++) {
699 version = k->type == KEY_RSA1 ? 1 : 2;
700 if ((id = lookup_identity(k, version)) != NULL) {
701 tab = idtab_lookup(version);
702 TAILQ_REMOVE(&tab->idlist, id, next);
712 buffer_put_int(&e->output, 1);
713 buffer_put_char(&e->output,
714 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
716 #endif /* SMARTCARD */
718 /* dispatch incoming messages */
721 process_message(SocketEntry *e)
726 if (buffer_len(&e->input) < 5)
727 return; /* Incomplete message. */
728 cp = buffer_ptr(&e->input);
729 msg_len = get_u32(cp);
730 if (msg_len > 256 * 1024) {
734 if (buffer_len(&e->input) < msg_len + 4)
737 /* move the current input to e->request */
738 buffer_consume(&e->input, 4);
739 buffer_clear(&e->request);
740 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
741 buffer_consume(&e->input, msg_len);
742 type = buffer_get_char(&e->request);
744 /* check wheter agent is locked */
745 if (locked && type != SSH_AGENTC_UNLOCK) {
746 buffer_clear(&e->request);
748 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
749 case SSH2_AGENTC_REQUEST_IDENTITIES:
750 /* send empty lists */
751 no_identities(e, type);
754 /* send a fail message for all other request types */
755 buffer_put_int(&e->output, 1);
756 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
761 debug("type %d", type);
763 case SSH_AGENTC_LOCK:
764 case SSH_AGENTC_UNLOCK:
765 process_lock_agent(e, type == SSH_AGENTC_LOCK);
768 case SSH_AGENTC_RSA_CHALLENGE:
769 process_authentication_challenge1(e);
771 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
772 process_request_identities(e, 1);
774 case SSH_AGENTC_ADD_RSA_IDENTITY:
775 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
776 process_add_identity(e, 1);
778 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
779 process_remove_identity(e, 1);
781 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
782 process_remove_all_identities(e, 1);
785 case SSH2_AGENTC_SIGN_REQUEST:
786 process_sign_request2(e);
788 case SSH2_AGENTC_REQUEST_IDENTITIES:
789 process_request_identities(e, 2);
791 case SSH2_AGENTC_ADD_IDENTITY:
792 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
793 process_add_identity(e, 2);
795 case SSH2_AGENTC_REMOVE_IDENTITY:
796 process_remove_identity(e, 2);
798 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
799 process_remove_all_identities(e, 2);
802 case SSH_AGENTC_ADD_SMARTCARD_KEY:
803 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
804 process_add_smartcard_key(e);
806 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
807 process_remove_smartcard_key(e);
809 #endif /* SMARTCARD */
811 /* Unknown message. Respond with failure. */
812 error("Unknown message %d", type);
813 buffer_clear(&e->request);
814 buffer_put_int(&e->output, 1);
815 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
821 new_socket(sock_type type, int fd)
823 u_int i, old_alloc, new_alloc;
830 for (i = 0; i < sockets_alloc; i++)
831 if (sockets[i].type == AUTH_UNUSED) {
833 buffer_init(&sockets[i].input);
834 buffer_init(&sockets[i].output);
835 buffer_init(&sockets[i].request);
836 sockets[i].type = type;
839 old_alloc = sockets_alloc;
840 new_alloc = sockets_alloc + 10;
841 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
842 for (i = old_alloc; i < new_alloc; i++)
843 sockets[i].type = AUTH_UNUSED;
844 sockets_alloc = new_alloc;
845 sockets[old_alloc].fd = fd;
846 buffer_init(&sockets[old_alloc].input);
847 buffer_init(&sockets[old_alloc].output);
848 buffer_init(&sockets[old_alloc].request);
849 sockets[old_alloc].type = type;
853 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
854 struct timeval **tvpp)
856 u_int i, sz, deadline;
858 static struct timeval tv;
860 for (i = 0; i < sockets_alloc; i++) {
861 switch (sockets[i].type) {
863 case AUTH_CONNECTION:
864 n = MAX(n, sockets[i].fd);
869 fatal("Unknown socket type %d", sockets[i].type);
874 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
875 if (*fdrp == NULL || sz > *nallocp) {
885 debug("XXX shrink: %d < %d", n, *fdl);
887 memset(*fdrp, 0, sz);
888 memset(*fdwp, 0, sz);
890 for (i = 0; i < sockets_alloc; i++) {
891 switch (sockets[i].type) {
893 case AUTH_CONNECTION:
894 FD_SET(sockets[i].fd, *fdrp);
895 if (buffer_len(&sockets[i].output) > 0)
896 FD_SET(sockets[i].fd, *fdwp);
903 if (parent_alive_interval != 0)
904 deadline = (deadline == 0) ? parent_alive_interval :
905 MIN(deadline, parent_alive_interval);
909 tv.tv_sec = deadline;
917 after_select(fd_set *readset, fd_set *writeset)
919 struct sockaddr_un sunaddr;
927 for (i = 0; i < sockets_alloc; i++)
928 switch (sockets[i].type) {
932 if (FD_ISSET(sockets[i].fd, readset)) {
933 slen = sizeof(sunaddr);
934 sock = accept(sockets[i].fd,
935 (struct sockaddr *)&sunaddr, &slen);
937 error("accept from AUTH_SOCKET: %s",
941 if (getpeereid(sock, &euid, &egid) < 0) {
942 error("getpeereid %d failed: %s",
943 sock, strerror(errno));
947 if ((euid != 0) && (getuid() != euid)) {
948 error("uid mismatch: "
949 "peer euid %u != uid %u",
950 (u_int) euid, (u_int) getuid());
954 new_socket(AUTH_CONNECTION, sock);
957 case AUTH_CONNECTION:
958 if (buffer_len(&sockets[i].output) > 0 &&
959 FD_ISSET(sockets[i].fd, writeset)) {
961 len = write(sockets[i].fd,
962 buffer_ptr(&sockets[i].output),
963 buffer_len(&sockets[i].output));
964 if (len == -1 && (errno == EAGAIN ||
966 errno == EWOULDBLOCK))
971 close_socket(&sockets[i]);
974 buffer_consume(&sockets[i].output, len);
976 if (FD_ISSET(sockets[i].fd, readset)) {
978 len = read(sockets[i].fd, buf, sizeof(buf));
979 if (len == -1 && (errno == EAGAIN ||
981 errno == EWOULDBLOCK))
986 close_socket(&sockets[i]);
989 buffer_append(&sockets[i].input, buf, len);
990 process_message(&sockets[i]);
994 fatal("Unknown type %d", sockets[i].type);
1002 unlink(socket_name);
1016 cleanup_handler(int sig)
1023 check_parent_exists(void)
1025 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1026 /* printf("Parent has died - Authentication agent exiting.\n"); */
1035 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1037 fprintf(stderr, "Options:\n");
1038 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1039 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1040 fprintf(stderr, " -k Kill the current agent.\n");
1041 fprintf(stderr, " -d Debug mode.\n");
1042 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1043 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1048 main(int ac, char **av)
1050 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1051 int sock, fd, ch, result, saved_errno;
1053 char *shell, *format, *pidstr, *agentsocket = NULL;
1054 fd_set *readsetp = NULL, *writesetp = NULL;
1055 struct sockaddr_un sunaddr;
1056 #ifdef HAVE_SETRLIMIT
1061 extern char *optarg;
1063 char pidstrbuf[1 + 3 * sizeof pid];
1064 struct timeval *tvp = NULL;
1066 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1074 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1075 /* Disable ptrace on Linux without sgid bit */
1076 prctl(PR_SET_DUMPABLE, 0);
1079 SSLeay_add_all_algorithms();
1081 __progname = ssh_get_progname(av[0]);
1085 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1106 agentsocket = optarg;
1109 if ((lifetime = convtime(optarg)) == -1) {
1110 fprintf(stderr, "Invalid lifetime\n");
1121 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1124 if (ac == 0 && !c_flag && !s_flag) {
1125 shell = getenv("SHELL");
1126 if (shell != NULL &&
1127 strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1131 const char *errstr = NULL;
1133 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1134 if (pidstr == NULL) {
1135 fprintf(stderr, "%s not set, cannot kill agent\n",
1136 SSH_AGENTPID_ENV_NAME);
1139 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1142 "%s=\"%s\", which is not a good PID: %s\n",
1143 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1146 if (kill(pid, SIGTERM) == -1) {
1150 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1151 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1152 printf(format, SSH_AGENTPID_ENV_NAME);
1153 printf("echo Agent pid %ld killed;\n", (long)pid);
1156 parent_pid = getpid();
1158 if (agentsocket == NULL) {
1159 /* Create private directory for agent socket */
1160 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1161 if (mkdtemp(socket_dir) == NULL) {
1162 perror("mkdtemp: private socket dir");
1165 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1168 /* Try to use specified agent socket */
1169 socket_dir[0] = '\0';
1170 strlcpy(socket_name, agentsocket, sizeof socket_name);
1174 * Create socket early so it will exist before command gets run from
1177 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1180 *socket_name = '\0'; /* Don't unlink any existing file */
1183 memset(&sunaddr, 0, sizeof(sunaddr));
1184 sunaddr.sun_family = AF_UNIX;
1185 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1186 prev_mask = umask(0177);
1187 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1189 *socket_name = '\0'; /* Don't unlink any existing file */
1194 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1200 * Fork, and have the parent execute the command, if any, or present
1201 * the socket data. The child continues as the authentication agent.
1204 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1205 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1206 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1207 SSH_AUTHSOCKET_ENV_NAME);
1208 printf("echo Agent pid %ld;\n", (long)parent_pid);
1216 if (pid != 0) { /* Parent - execute the given command. */
1218 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1220 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1221 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1222 SSH_AUTHSOCKET_ENV_NAME);
1223 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1224 SSH_AGENTPID_ENV_NAME);
1225 printf("echo Agent pid %ld;\n", (long)pid);
1228 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1229 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1238 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1240 if (setsid() == -1) {
1241 error("setsid: %s", strerror(errno));
1246 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1247 /* XXX might close listen socket */
1248 (void)dup2(fd, STDIN_FILENO);
1249 (void)dup2(fd, STDOUT_FILENO);
1250 (void)dup2(fd, STDERR_FILENO);
1255 #ifdef HAVE_SETRLIMIT
1256 /* deny core dumps, since memory contains unencrypted private keys */
1257 rlim.rlim_cur = rlim.rlim_max = 0;
1258 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1259 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1265 new_socket(AUTH_SOCKET, sock);
1267 parent_alive_interval = 10;
1270 signal(SIGINT, SIG_IGN);
1271 signal(SIGPIPE, SIG_IGN);
1272 signal(SIGHUP, cleanup_handler);
1273 signal(SIGTERM, cleanup_handler);
1277 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1278 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1279 saved_errno = errno;
1280 if (parent_alive_interval != 0)
1281 check_parent_exists();
1282 (void) reaper(); /* remove expired keys */
1284 if (saved_errno == EINTR)
1286 fatal("select: %s", strerror(saved_errno));
1287 } else if (result > 0)
1288 after_select(readsetp, writesetp);