1 /* $OpenBSD: ssh-agent.c,v 1.181 2013/12/19 01:19:41 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"
81 #include "ssh-pkcs11.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;
116 TAILQ_HEAD(idqueue, identity) idlist;
119 /* private key table, one per protocol version */
124 /* pid of shell == parent of agent */
125 pid_t parent_pid = -1;
126 time_t parent_alive_interval = 0;
128 /* pathname and directory for AUTH_SOCKET */
129 char socket_name[MAXPATHLEN];
130 char socket_dir[MAXPATHLEN];
134 char *lock_passwd = NULL;
136 extern char *__progname;
138 /* Default lifetime in seconds (0 == forever) */
139 static long lifetime = 0;
142 * Client connection count; incremented in new_socket() and decremented in
143 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
144 * normally initialized to 1, it will never reach 0. However, if the -x
145 * option is specified, it is initialized to 0 in main(); in that case,
146 * ssh-agent will exit as soon as it has had at least one client but no
149 static int xcount = 1;
152 close_socket(SocketEntry *e)
156 if (e->type == AUTH_CONNECTION) {
157 debug("xcount %d -> %d", xcount, xcount - 1);
163 e->type = AUTH_UNUSED;
164 buffer_free(&e->input);
165 buffer_free(&e->output);
166 buffer_free(&e->request);
176 for (i = 0; i <=2; i++) {
177 TAILQ_INIT(&idtable[i].idlist);
178 idtable[i].nentries = 0;
182 /* return private key table for requested protocol version */
184 idtab_lookup(int version)
186 if (version < 1 || version > 2)
187 fatal("internal error, bad protocol version %d", version);
188 return &idtable[version];
192 free_identity(Identity *id)
200 /* return matching private key for given public key */
202 lookup_identity(Key *key, int version)
206 Idtab *tab = idtab_lookup(version);
207 TAILQ_FOREACH(id, &tab->idlist, next) {
208 if (key_equal(key, id->key))
214 /* Check confirmation of keysign request */
216 confirm_key(Identity *id)
221 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
222 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
230 /* send list of supported public keys to 'client' */
232 process_request_identities(SocketEntry *e, int version)
234 Idtab *tab = idtab_lookup(version);
239 buffer_put_char(&msg, (version == 1) ?
240 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
241 buffer_put_int(&msg, tab->nentries);
242 TAILQ_FOREACH(id, &tab->idlist, next) {
243 if (id->key->type == KEY_RSA1) {
244 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
245 buffer_put_bignum(&msg, id->key->rsa->e);
246 buffer_put_bignum(&msg, id->key->rsa->n);
250 key_to_blob(id->key, &blob, &blen);
251 buffer_put_string(&msg, blob, blen);
254 buffer_put_cstring(&msg, id->comment);
256 buffer_put_int(&e->output, buffer_len(&msg));
257 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
263 process_authentication_challenge1(SocketEntry *e)
265 u_char buf[32], mdbuf[16], session_id[16];
275 key = key_new(KEY_RSA1);
276 if ((challenge = BN_new()) == NULL)
277 fatal("process_authentication_challenge1: BN_new failed");
279 (void) buffer_get_int(&e->request); /* ignored */
280 buffer_get_bignum(&e->request, key->rsa->e);
281 buffer_get_bignum(&e->request, key->rsa->n);
282 buffer_get_bignum(&e->request, challenge);
284 /* Only protocol 1.1 is supported */
285 if (buffer_len(&e->request) == 0)
287 buffer_get(&e->request, session_id, 16);
288 response_type = buffer_get_int(&e->request);
289 if (response_type != 1)
292 id = lookup_identity(key, 1);
293 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
294 Key *private = id->key;
295 /* Decrypt the challenge using the private key. */
296 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
299 /* The response is MD5 of decrypted challenge plus session id. */
300 len = BN_num_bytes(challenge);
301 if (len <= 0 || len > 32) {
302 logit("process_authentication_challenge: bad challenge length %d", len);
306 BN_bn2bin(challenge, buf + 32 - len);
308 MD5_Update(&md, buf, 32);
309 MD5_Update(&md, session_id, 16);
310 MD5_Final(mdbuf, &md);
312 /* Send the response. */
313 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
314 for (i = 0; i < 16; i++)
315 buffer_put_char(&msg, mdbuf[i]);
320 /* Unknown identity or protocol error. Send failure. */
321 buffer_put_char(&msg, SSH_AGENT_FAILURE);
323 buffer_put_int(&e->output, buffer_len(&msg));
324 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
326 BN_clear_free(challenge);
332 process_sign_request2(SocketEntry *e)
334 u_char *blob, *data, *signature = NULL;
335 u_int blen, dlen, slen = 0;
336 extern int datafellows;
344 blob = buffer_get_string(&e->request, &blen);
345 data = buffer_get_string(&e->request, &dlen);
347 flags = buffer_get_int(&e->request);
348 odatafellows = datafellows;
349 if (flags & SSH_AGENT_OLD_SIGNATURE)
350 datafellows = SSH_BUG_SIGBLOB;
352 key = key_from_blob(blob, blen);
354 Identity *id = lookup_identity(key, 2);
355 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
356 ok = key_sign(id->key, &signature, &slen, data, dlen);
361 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
362 buffer_put_string(&msg, signature, slen);
364 buffer_put_char(&msg, SSH_AGENT_FAILURE);
366 buffer_put_int(&e->output, buffer_len(&msg));
367 buffer_append(&e->output, buffer_ptr(&msg),
373 datafellows = odatafellows;
378 process_remove_identity(SocketEntry *e, int version)
387 key = key_new(KEY_RSA1);
388 bits = buffer_get_int(&e->request);
389 buffer_get_bignum(&e->request, key->rsa->e);
390 buffer_get_bignum(&e->request, key->rsa->n);
392 if (bits != key_size(key))
393 logit("Warning: identity keysize mismatch: actual %u, announced %u",
394 key_size(key), bits);
397 blob = buffer_get_string(&e->request, &blen);
398 key = key_from_blob(blob, blen);
403 Identity *id = lookup_identity(key, version);
406 * We have this key. Free the old key. Since we
407 * don't want to leave empty slots in the middle of
408 * the array, we actually free the key there and move
409 * all the entries between the empty slot and the end
412 Idtab *tab = idtab_lookup(version);
413 if (tab->nentries < 1)
414 fatal("process_remove_identity: "
415 "internal error: tab->nentries %d",
417 TAILQ_REMOVE(&tab->idlist, id, next);
424 buffer_put_int(&e->output, 1);
425 buffer_put_char(&e->output,
426 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
430 process_remove_all_identities(SocketEntry *e, int version)
432 Idtab *tab = idtab_lookup(version);
435 /* Loop over all identities and clear the keys. */
436 for (id = TAILQ_FIRST(&tab->idlist); id;
437 id = TAILQ_FIRST(&tab->idlist)) {
438 TAILQ_REMOVE(&tab->idlist, id, next);
442 /* Mark that there are no identities. */
446 buffer_put_int(&e->output, 1);
447 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
450 /* removes expired keys and returns number of seconds until the next expiry */
454 time_t deadline = 0, now = monotime();
459 for (version = 1; version < 3; version++) {
460 tab = idtab_lookup(version);
461 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
462 nxt = TAILQ_NEXT(id, next);
465 if (now >= id->death) {
466 debug("expiring key '%s'", id->comment);
467 TAILQ_REMOVE(&tab->idlist, id, next);
471 deadline = (deadline == 0) ? id->death :
472 MIN(deadline, id->death);
475 if (deadline == 0 || deadline <= now)
478 return (deadline - now);
482 process_add_identity(SocketEntry *e, int version)
484 Idtab *tab = idtab_lookup(version);
486 int type, success = 0, confirm = 0;
493 k = key_new_private(KEY_RSA1);
494 (void) buffer_get_int(&e->request); /* ignored */
495 buffer_get_bignum(&e->request, k->rsa->n);
496 buffer_get_bignum(&e->request, k->rsa->e);
497 buffer_get_bignum(&e->request, k->rsa->d);
498 buffer_get_bignum(&e->request, k->rsa->iqmp);
500 /* SSH and SSL have p and q swapped */
501 buffer_get_bignum(&e->request, k->rsa->q); /* p */
502 buffer_get_bignum(&e->request, k->rsa->p); /* q */
504 /* Generate additional parameters */
505 rsa_generate_additional_parameters(k->rsa);
507 /* enable blinding */
508 if (RSA_blinding_on(k->rsa, NULL) != 1) {
509 error("process_add_identity: RSA_blinding_on failed");
515 k = key_private_deserialize(&e->request);
517 buffer_clear(&e->request);
522 comment = buffer_get_string(&e->request, NULL);
527 while (buffer_len(&e->request)) {
528 switch ((type = buffer_get_char(&e->request))) {
529 case SSH_AGENT_CONSTRAIN_LIFETIME:
530 death = monotime() + buffer_get_int(&e->request);
532 case SSH_AGENT_CONSTRAIN_CONFIRM:
536 error("process_add_identity: "
537 "Unknown constraint type %d", type);
544 if (lifetime && !death)
545 death = monotime() + lifetime;
546 if ((id = lookup_identity(k, version)) == NULL) {
547 id = xcalloc(1, sizeof(Identity));
549 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
550 /* Increment the number of identities. */
556 id->comment = comment;
558 id->confirm = confirm;
560 buffer_put_int(&e->output, 1);
561 buffer_put_char(&e->output,
562 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
565 /* XXX todo: encrypt sensitive data with passphrase */
567 process_lock_agent(SocketEntry *e, int lock)
572 passwd = buffer_get_string(&e->request, NULL);
573 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
575 memset(lock_passwd, 0, strlen(lock_passwd));
579 } else if (!locked && lock) {
581 lock_passwd = xstrdup(passwd);
584 memset(passwd, 0, strlen(passwd));
587 buffer_put_int(&e->output, 1);
588 buffer_put_char(&e->output,
589 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
593 no_identities(SocketEntry *e, u_int type)
598 buffer_put_char(&msg,
599 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
600 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
601 buffer_put_int(&msg, 0);
602 buffer_put_int(&e->output, buffer_len(&msg));
603 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
609 process_add_smartcard_key(SocketEntry *e)
611 char *provider = NULL, *pin;
612 int i, type, version, count = 0, success = 0, confirm = 0;
614 Key **keys = NULL, *k;
618 provider = buffer_get_string(&e->request, NULL);
619 pin = buffer_get_string(&e->request, NULL);
621 while (buffer_len(&e->request)) {
622 switch ((type = buffer_get_char(&e->request))) {
623 case SSH_AGENT_CONSTRAIN_LIFETIME:
624 death = monotime() + buffer_get_int(&e->request);
626 case SSH_AGENT_CONSTRAIN_CONFIRM:
630 error("process_add_smartcard_key: "
631 "Unknown constraint type %d", type);
635 if (lifetime && !death)
636 death = monotime() + lifetime;
638 count = pkcs11_add_provider(provider, pin, &keys);
639 for (i = 0; i < count; i++) {
641 version = k->type == KEY_RSA1 ? 1 : 2;
642 tab = idtab_lookup(version);
643 if (lookup_identity(k, version) == NULL) {
644 id = xcalloc(1, sizeof(Identity));
646 id->provider = xstrdup(provider);
647 id->comment = xstrdup(provider); /* XXX */
649 id->confirm = confirm;
650 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
662 buffer_put_int(&e->output, 1);
663 buffer_put_char(&e->output,
664 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
668 process_remove_smartcard_key(SocketEntry *e)
670 char *provider = NULL, *pin = NULL;
671 int version, success = 0;
675 provider = buffer_get_string(&e->request, NULL);
676 pin = buffer_get_string(&e->request, NULL);
679 for (version = 1; version < 3; version++) {
680 tab = idtab_lookup(version);
681 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
682 nxt = TAILQ_NEXT(id, next);
683 /* Skip file--based keys */
684 if (id->provider == NULL)
686 if (!strcmp(provider, id->provider)) {
687 TAILQ_REMOVE(&tab->idlist, id, next);
693 if (pkcs11_del_provider(provider) == 0)
696 error("process_remove_smartcard_key:"
697 " pkcs11_del_provider failed");
699 buffer_put_int(&e->output, 1);
700 buffer_put_char(&e->output,
701 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
703 #endif /* ENABLE_PKCS11 */
705 /* dispatch incoming messages */
708 process_message(SocketEntry *e)
713 if (buffer_len(&e->input) < 5)
714 return; /* Incomplete message. */
715 cp = buffer_ptr(&e->input);
716 msg_len = get_u32(cp);
717 if (msg_len > 256 * 1024) {
721 if (buffer_len(&e->input) < msg_len + 4)
724 /* move the current input to e->request */
725 buffer_consume(&e->input, 4);
726 buffer_clear(&e->request);
727 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
728 buffer_consume(&e->input, msg_len);
729 type = buffer_get_char(&e->request);
731 /* check wheter agent is locked */
732 if (locked && type != SSH_AGENTC_UNLOCK) {
733 buffer_clear(&e->request);
735 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
736 case SSH2_AGENTC_REQUEST_IDENTITIES:
737 /* send empty lists */
738 no_identities(e, type);
741 /* send a fail message for all other request types */
742 buffer_put_int(&e->output, 1);
743 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
748 debug("type %d", type);
750 case SSH_AGENTC_LOCK:
751 case SSH_AGENTC_UNLOCK:
752 process_lock_agent(e, type == SSH_AGENTC_LOCK);
755 case SSH_AGENTC_RSA_CHALLENGE:
756 process_authentication_challenge1(e);
758 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
759 process_request_identities(e, 1);
761 case SSH_AGENTC_ADD_RSA_IDENTITY:
762 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
763 process_add_identity(e, 1);
765 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
766 process_remove_identity(e, 1);
768 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
769 process_remove_all_identities(e, 1);
772 case SSH2_AGENTC_SIGN_REQUEST:
773 process_sign_request2(e);
775 case SSH2_AGENTC_REQUEST_IDENTITIES:
776 process_request_identities(e, 2);
778 case SSH2_AGENTC_ADD_IDENTITY:
779 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
780 process_add_identity(e, 2);
782 case SSH2_AGENTC_REMOVE_IDENTITY:
783 process_remove_identity(e, 2);
785 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
786 process_remove_all_identities(e, 2);
789 case SSH_AGENTC_ADD_SMARTCARD_KEY:
790 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
791 process_add_smartcard_key(e);
793 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
794 process_remove_smartcard_key(e);
796 #endif /* ENABLE_PKCS11 */
798 /* Unknown message. Respond with failure. */
799 error("Unknown message %d", type);
800 buffer_clear(&e->request);
801 buffer_put_int(&e->output, 1);
802 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
808 new_socket(sock_type type, int fd)
810 u_int i, old_alloc, new_alloc;
812 if (type == AUTH_CONNECTION) {
813 debug("xcount %d -> %d", xcount, xcount + 1);
821 for (i = 0; i < sockets_alloc; i++)
822 if (sockets[i].type == AUTH_UNUSED) {
824 buffer_init(&sockets[i].input);
825 buffer_init(&sockets[i].output);
826 buffer_init(&sockets[i].request);
827 sockets[i].type = type;
830 old_alloc = sockets_alloc;
831 new_alloc = sockets_alloc + 10;
832 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
833 for (i = old_alloc; i < new_alloc; i++)
834 sockets[i].type = AUTH_UNUSED;
835 sockets_alloc = new_alloc;
836 sockets[old_alloc].fd = fd;
837 buffer_init(&sockets[old_alloc].input);
838 buffer_init(&sockets[old_alloc].output);
839 buffer_init(&sockets[old_alloc].request);
840 sockets[old_alloc].type = type;
844 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
845 struct timeval **tvpp)
849 static struct timeval tv;
852 for (i = 0; i < sockets_alloc; i++) {
853 switch (sockets[i].type) {
855 case AUTH_CONNECTION:
856 n = MAX(n, sockets[i].fd);
861 fatal("Unknown socket type %d", sockets[i].type);
866 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
867 if (*fdrp == NULL || sz > *nallocp) {
875 debug("XXX shrink: %d < %d", n, *fdl);
877 memset(*fdrp, 0, sz);
878 memset(*fdwp, 0, sz);
880 for (i = 0; i < sockets_alloc; i++) {
881 switch (sockets[i].type) {
883 case AUTH_CONNECTION:
884 FD_SET(sockets[i].fd, *fdrp);
885 if (buffer_len(&sockets[i].output) > 0)
886 FD_SET(sockets[i].fd, *fdwp);
893 if (parent_alive_interval != 0)
894 deadline = (deadline == 0) ? parent_alive_interval :
895 MIN(deadline, parent_alive_interval);
899 tv.tv_sec = deadline;
907 after_select(fd_set *readset, fd_set *writeset)
909 struct sockaddr_un sunaddr;
917 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
918 switch (sockets[i].type) {
922 if (FD_ISSET(sockets[i].fd, readset)) {
923 slen = sizeof(sunaddr);
924 sock = accept(sockets[i].fd,
925 (struct sockaddr *)&sunaddr, &slen);
927 error("accept from AUTH_SOCKET: %s",
931 if (getpeereid(sock, &euid, &egid) < 0) {
932 error("getpeereid %d failed: %s",
933 sock, strerror(errno));
937 if ((euid != 0) && (getuid() != euid)) {
938 error("uid mismatch: "
939 "peer euid %u != uid %u",
940 (u_int) euid, (u_int) getuid());
944 new_socket(AUTH_CONNECTION, sock);
947 case AUTH_CONNECTION:
948 if (buffer_len(&sockets[i].output) > 0 &&
949 FD_ISSET(sockets[i].fd, writeset)) {
950 len = write(sockets[i].fd,
951 buffer_ptr(&sockets[i].output),
952 buffer_len(&sockets[i].output));
953 if (len == -1 && (errno == EAGAIN ||
954 errno == EWOULDBLOCK ||
958 close_socket(&sockets[i]);
961 buffer_consume(&sockets[i].output, len);
963 if (FD_ISSET(sockets[i].fd, readset)) {
964 len = read(sockets[i].fd, buf, sizeof(buf));
965 if (len == -1 && (errno == EAGAIN ||
966 errno == EWOULDBLOCK ||
970 close_socket(&sockets[i]);
973 buffer_append(&sockets[i].input, buf, len);
974 process_message(&sockets[i]);
978 fatal("Unknown type %d", sockets[i].type);
1000 cleanup_handler(int sig)
1003 #ifdef ENABLE_PKCS11
1010 check_parent_exists(void)
1013 * If our parent has exited then getppid() will return (pid_t)1,
1014 * so testing for that should be safe.
1016 if (parent_pid != -1 && getppid() != parent_pid) {
1017 /* printf("Parent has died - Authentication agent exiting.\n"); */
1026 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1028 fprintf(stderr, "Options:\n");
1029 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1030 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1031 fprintf(stderr, " -k Kill the current agent.\n");
1032 fprintf(stderr, " -d Debug mode.\n");
1033 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1034 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1035 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1040 main(int ac, char **av)
1042 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1043 int sock, fd, ch, result, saved_errno;
1045 char *shell, *format, *pidstr, *agentsocket = NULL;
1046 fd_set *readsetp = NULL, *writesetp = NULL;
1047 struct sockaddr_un sunaddr;
1048 #ifdef HAVE_SETRLIMIT
1053 extern char *optarg;
1055 char pidstrbuf[1 + 3 * sizeof pid];
1056 struct timeval *tvp = NULL;
1059 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1067 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1068 /* Disable ptrace on Linux without sgid bit */
1069 prctl(PR_SET_DUMPABLE, 0);
1072 OpenSSL_add_all_algorithms();
1074 __progname = ssh_get_progname(av[0]);
1077 while ((ch = getopt(ac, av, "cdksa:t:x")) != -1) {
1098 agentsocket = optarg;
1101 if ((lifetime = convtime(optarg)) == -1) {
1102 fprintf(stderr, "Invalid lifetime\n");
1116 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1119 if (ac == 0 && !c_flag && !s_flag) {
1120 shell = getenv("SHELL");
1121 if (shell != NULL && (len = strlen(shell)) > 2 &&
1122 strncmp(shell + len - 3, "csh", 3) == 0)
1126 const char *errstr = NULL;
1128 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1129 if (pidstr == NULL) {
1130 fprintf(stderr, "%s not set, cannot kill agent\n",
1131 SSH_AGENTPID_ENV_NAME);
1134 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1137 "%s=\"%s\", which is not a good PID: %s\n",
1138 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1141 if (kill(pid, SIGTERM) == -1) {
1145 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1146 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1147 printf(format, SSH_AGENTPID_ENV_NAME);
1148 printf("echo Agent pid %ld killed;\n", (long)pid);
1151 parent_pid = getpid();
1153 if (agentsocket == NULL) {
1154 /* Create private directory for agent socket */
1155 mktemp_proto(socket_dir, sizeof(socket_dir));
1156 if (mkdtemp(socket_dir) == NULL) {
1157 perror("mkdtemp: private socket dir");
1160 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1163 /* Try to use specified agent socket */
1164 socket_dir[0] = '\0';
1165 strlcpy(socket_name, agentsocket, sizeof socket_name);
1169 * Create socket early so it will exist before command gets run from
1172 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1175 *socket_name = '\0'; /* Don't unlink any existing file */
1178 memset(&sunaddr, 0, sizeof(sunaddr));
1179 sunaddr.sun_family = AF_UNIX;
1180 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1181 prev_mask = umask(0177);
1182 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1184 *socket_name = '\0'; /* Don't unlink any existing file */
1189 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1195 * Fork, and have the parent execute the command, if any, or present
1196 * the socket data. The child continues as the authentication agent.
1199 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1200 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1201 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1202 SSH_AUTHSOCKET_ENV_NAME);
1203 printf("echo Agent pid %ld;\n", (long)parent_pid);
1211 if (pid != 0) { /* Parent - execute the given command. */
1213 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1215 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1216 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1217 SSH_AUTHSOCKET_ENV_NAME);
1218 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1219 SSH_AGENTPID_ENV_NAME);
1220 printf("echo Agent pid %ld;\n", (long)pid);
1223 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1224 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1233 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1235 if (setsid() == -1) {
1236 error("setsid: %s", strerror(errno));
1241 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1242 /* XXX might close listen socket */
1243 (void)dup2(fd, STDIN_FILENO);
1244 (void)dup2(fd, STDOUT_FILENO);
1245 (void)dup2(fd, STDERR_FILENO);
1250 #ifdef HAVE_SETRLIMIT
1251 /* deny core dumps, since memory contains unencrypted private keys */
1252 rlim.rlim_cur = rlim.rlim_max = 0;
1253 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1254 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1261 #ifdef ENABLE_PKCS11
1264 new_socket(AUTH_SOCKET, sock);
1266 parent_alive_interval = 10;
1268 signal(SIGPIPE, SIG_IGN);
1269 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1270 signal(SIGHUP, cleanup_handler);
1271 signal(SIGTERM, cleanup_handler);
1275 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1276 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1277 saved_errno = errno;
1278 if (parent_alive_interval != 0)
1279 check_parent_exists();
1280 (void) reaper(); /* remove expired keys */
1282 if (saved_errno == EINTR)
1284 fatal("select: %s", strerror(saved_errno));
1285 } else if (result > 0)
1286 after_select(readsetp, writesetp);