1 /* $OpenBSD: ssh-agent.c,v 1.190 2014/07/25 21:22:03 dtucker 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"
53 #include <openssl/evp.h>
54 #include "openbsd-compat/openssl-compat.h"
82 #include "ssh-pkcs11.h"
85 #if defined(HAVE_SYS_PRCTL_H)
86 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
103 u_int sockets_alloc = 0;
104 SocketEntry *sockets = NULL;
106 typedef struct identity {
107 TAILQ_ENTRY(identity) next;
117 TAILQ_HEAD(idqueue, identity) idlist;
120 /* private key table, one per protocol version */
125 /* pid of shell == parent of agent */
126 pid_t parent_pid = -1;
127 time_t parent_alive_interval = 0;
129 /* pid of process for which cleanup_socket is applicable */
130 pid_t cleanup_pid = 0;
132 /* pathname and directory for AUTH_SOCKET */
133 char socket_name[MAXPATHLEN];
134 char socket_dir[MAXPATHLEN];
138 char *lock_passwd = NULL;
140 extern char *__progname;
142 /* Default lifetime in seconds (0 == forever) */
143 static long lifetime = 0;
146 close_socket(SocketEntry *e)
150 e->type = AUTH_UNUSED;
151 buffer_free(&e->input);
152 buffer_free(&e->output);
153 buffer_free(&e->request);
161 for (i = 0; i <=2; i++) {
162 TAILQ_INIT(&idtable[i].idlist);
163 idtable[i].nentries = 0;
167 /* return private key table for requested protocol version */
169 idtab_lookup(int version)
171 if (version < 1 || version > 2)
172 fatal("internal error, bad protocol version %d", version);
173 return &idtable[version];
177 free_identity(Identity *id)
185 /* return matching private key for given public key */
187 lookup_identity(Key *key, int version)
191 Idtab *tab = idtab_lookup(version);
192 TAILQ_FOREACH(id, &tab->idlist, next) {
193 if (key_equal(key, id->key))
199 /* Check confirmation of keysign request */
201 confirm_key(Identity *id)
206 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
207 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
215 /* send list of supported public keys to 'client' */
217 process_request_identities(SocketEntry *e, int version)
219 Idtab *tab = idtab_lookup(version);
224 buffer_put_char(&msg, (version == 1) ?
225 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
226 buffer_put_int(&msg, tab->nentries);
227 TAILQ_FOREACH(id, &tab->idlist, next) {
228 if (id->key->type == KEY_RSA1) {
230 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
231 buffer_put_bignum(&msg, id->key->rsa->e);
232 buffer_put_bignum(&msg, id->key->rsa->n);
237 key_to_blob(id->key, &blob, &blen);
238 buffer_put_string(&msg, blob, blen);
241 buffer_put_cstring(&msg, id->comment);
243 buffer_put_int(&e->output, buffer_len(&msg));
244 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
251 process_authentication_challenge1(SocketEntry *e)
253 u_char buf[32], mdbuf[16], session_id[16];
259 struct ssh_digest_ctx *md;
263 key = key_new(KEY_RSA1);
264 if ((challenge = BN_new()) == NULL)
265 fatal("process_authentication_challenge1: BN_new failed");
267 (void) buffer_get_int(&e->request); /* ignored */
268 buffer_get_bignum(&e->request, key->rsa->e);
269 buffer_get_bignum(&e->request, key->rsa->n);
270 buffer_get_bignum(&e->request, challenge);
272 /* Only protocol 1.1 is supported */
273 if (buffer_len(&e->request) == 0)
275 buffer_get(&e->request, session_id, 16);
276 response_type = buffer_get_int(&e->request);
277 if (response_type != 1)
280 id = lookup_identity(key, 1);
281 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
282 Key *private = id->key;
283 /* Decrypt the challenge using the private key. */
284 if (rsa_private_decrypt(challenge, challenge, private->rsa) != 0)
287 /* The response is MD5 of decrypted challenge plus session id. */
288 len = BN_num_bytes(challenge);
289 if (len <= 0 || len > 32) {
290 logit("process_authentication_challenge: bad challenge length %d", len);
294 BN_bn2bin(challenge, buf + 32 - len);
295 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
296 ssh_digest_update(md, buf, 32) < 0 ||
297 ssh_digest_update(md, session_id, 16) < 0 ||
298 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
299 fatal("%s: md5 failed", __func__);
302 /* Send the response. */
303 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
304 for (i = 0; i < 16; i++)
305 buffer_put_char(&msg, mdbuf[i]);
310 /* Unknown identity or protocol error. Send failure. */
311 buffer_put_char(&msg, SSH_AGENT_FAILURE);
313 buffer_put_int(&e->output, buffer_len(&msg));
314 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
316 BN_clear_free(challenge);
323 process_sign_request2(SocketEntry *e)
325 u_char *blob, *data, *signature = NULL;
326 u_int blen, dlen, slen = 0;
327 extern int datafellows;
335 blob = buffer_get_string(&e->request, &blen);
336 data = buffer_get_string(&e->request, &dlen);
338 flags = buffer_get_int(&e->request);
339 odatafellows = datafellows;
340 if (flags & SSH_AGENT_OLD_SIGNATURE)
341 datafellows = SSH_BUG_SIGBLOB;
343 key = key_from_blob(blob, blen);
345 Identity *id = lookup_identity(key, 2);
346 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
347 ok = key_sign(id->key, &signature, &slen, data, dlen);
352 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
353 buffer_put_string(&msg, signature, slen);
355 buffer_put_char(&msg, SSH_AGENT_FAILURE);
357 buffer_put_int(&e->output, buffer_len(&msg));
358 buffer_append(&e->output, buffer_ptr(&msg),
364 datafellows = odatafellows;
369 process_remove_identity(SocketEntry *e, int version)
377 #endif /* WITH_SSH1 */
382 key = key_new(KEY_RSA1);
383 bits = buffer_get_int(&e->request);
384 buffer_get_bignum(&e->request, key->rsa->e);
385 buffer_get_bignum(&e->request, key->rsa->n);
387 if (bits != key_size(key))
388 logit("Warning: identity keysize mismatch: actual %u, announced %u",
389 key_size(key), bits);
391 #endif /* WITH_SSH1 */
393 blob = buffer_get_string(&e->request, &blen);
394 key = key_from_blob(blob, blen);
399 Identity *id = lookup_identity(key, version);
402 * We have this key. Free the old key. Since we
403 * don't want to leave empty slots in the middle of
404 * the array, we actually free the key there and move
405 * all the entries between the empty slot and the end
408 Idtab *tab = idtab_lookup(version);
409 if (tab->nentries < 1)
410 fatal("process_remove_identity: "
411 "internal error: tab->nentries %d",
413 TAILQ_REMOVE(&tab->idlist, id, next);
420 buffer_put_int(&e->output, 1);
421 buffer_put_char(&e->output,
422 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
426 process_remove_all_identities(SocketEntry *e, int version)
428 Idtab *tab = idtab_lookup(version);
431 /* Loop over all identities and clear the keys. */
432 for (id = TAILQ_FIRST(&tab->idlist); id;
433 id = TAILQ_FIRST(&tab->idlist)) {
434 TAILQ_REMOVE(&tab->idlist, id, next);
438 /* Mark that there are no identities. */
442 buffer_put_int(&e->output, 1);
443 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
446 /* removes expired keys and returns number of seconds until the next expiry */
450 time_t deadline = 0, now = monotime();
455 for (version = 1; version < 3; version++) {
456 tab = idtab_lookup(version);
457 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
458 nxt = TAILQ_NEXT(id, next);
461 if (now >= id->death) {
462 debug("expiring key '%s'", id->comment);
463 TAILQ_REMOVE(&tab->idlist, id, next);
467 deadline = (deadline == 0) ? id->death :
468 MIN(deadline, id->death);
471 if (deadline == 0 || deadline <= now)
474 return (deadline - now);
478 process_add_identity(SocketEntry *e, int version)
480 Idtab *tab = idtab_lookup(version);
482 int type, success = 0, confirm = 0;
490 k = key_new_private(KEY_RSA1);
491 (void) buffer_get_int(&e->request); /* ignored */
492 buffer_get_bignum(&e->request, k->rsa->n);
493 buffer_get_bignum(&e->request, k->rsa->e);
494 buffer_get_bignum(&e->request, k->rsa->d);
495 buffer_get_bignum(&e->request, k->rsa->iqmp);
497 /* SSH and SSL have p and q swapped */
498 buffer_get_bignum(&e->request, k->rsa->q); /* p */
499 buffer_get_bignum(&e->request, k->rsa->p); /* q */
501 /* Generate additional parameters */
502 if (rsa_generate_additional_parameters(k->rsa) != 0)
503 fatal("%s: rsa_generate_additional_parameters "
506 /* enable blinding */
507 if (RSA_blinding_on(k->rsa, NULL) != 1) {
508 error("process_add_identity: RSA_blinding_on failed");
513 #endif /* WITH_SSH1 */
515 k = key_private_deserialize(&e->request);
517 buffer_clear(&e->request);
524 comment = buffer_get_string(&e->request, NULL);
526 while (buffer_len(&e->request)) {
527 switch ((type = buffer_get_char(&e->request))) {
528 case SSH_AGENT_CONSTRAIN_LIFETIME:
529 death = monotime() + buffer_get_int(&e->request);
531 case SSH_AGENT_CONSTRAIN_CONFIRM:
535 error("process_add_identity: "
536 "Unknown constraint type %d", type);
543 if (lifetime && !death)
544 death = monotime() + lifetime;
545 if ((id = lookup_identity(k, version)) == NULL) {
546 id = xcalloc(1, sizeof(Identity));
548 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
549 /* Increment the number of identities. */
555 id->comment = comment;
557 id->confirm = confirm;
559 buffer_put_int(&e->output, 1);
560 buffer_put_char(&e->output,
561 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
564 /* XXX todo: encrypt sensitive data with passphrase */
566 process_lock_agent(SocketEntry *e, int lock)
571 passwd = buffer_get_string(&e->request, NULL);
572 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
574 explicit_bzero(lock_passwd, strlen(lock_passwd));
578 } else if (!locked && lock) {
580 lock_passwd = xstrdup(passwd);
583 explicit_bzero(passwd, strlen(passwd));
586 buffer_put_int(&e->output, 1);
587 buffer_put_char(&e->output,
588 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
592 no_identities(SocketEntry *e, u_int type)
597 buffer_put_char(&msg,
598 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
599 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
600 buffer_put_int(&msg, 0);
601 buffer_put_int(&e->output, buffer_len(&msg));
602 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
608 process_add_smartcard_key(SocketEntry *e)
610 char *provider = NULL, *pin;
611 int i, type, version, count = 0, success = 0, confirm = 0;
613 Key **keys = NULL, *k;
617 provider = buffer_get_string(&e->request, NULL);
618 pin = buffer_get_string(&e->request, NULL);
620 while (buffer_len(&e->request)) {
621 switch ((type = buffer_get_char(&e->request))) {
622 case SSH_AGENT_CONSTRAIN_LIFETIME:
623 death = monotime() + buffer_get_int(&e->request);
625 case SSH_AGENT_CONSTRAIN_CONFIRM:
629 error("process_add_smartcard_key: "
630 "Unknown constraint type %d", type);
634 if (lifetime && !death)
635 death = monotime() + lifetime;
637 count = pkcs11_add_provider(provider, pin, &keys);
638 for (i = 0; i < count; i++) {
640 version = k->type == KEY_RSA1 ? 1 : 2;
641 tab = idtab_lookup(version);
642 if (lookup_identity(k, version) == NULL) {
643 id = xcalloc(1, sizeof(Identity));
645 id->provider = xstrdup(provider);
646 id->comment = xstrdup(provider); /* XXX */
648 id->confirm = confirm;
649 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
661 buffer_put_int(&e->output, 1);
662 buffer_put_char(&e->output,
663 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
667 process_remove_smartcard_key(SocketEntry *e)
669 char *provider = NULL, *pin = NULL;
670 int version, success = 0;
674 provider = buffer_get_string(&e->request, NULL);
675 pin = buffer_get_string(&e->request, NULL);
678 for (version = 1; version < 3; version++) {
679 tab = idtab_lookup(version);
680 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
681 nxt = TAILQ_NEXT(id, next);
682 /* Skip file--based keys */
683 if (id->provider == NULL)
685 if (!strcmp(provider, id->provider)) {
686 TAILQ_REMOVE(&tab->idlist, id, next);
692 if (pkcs11_del_provider(provider) == 0)
695 error("process_remove_smartcard_key:"
696 " pkcs11_del_provider failed");
698 buffer_put_int(&e->output, 1);
699 buffer_put_char(&e->output,
700 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
702 #endif /* ENABLE_PKCS11 */
704 /* dispatch incoming messages */
707 process_message(SocketEntry *e)
712 if (buffer_len(&e->input) < 5)
713 return; /* Incomplete message. */
714 cp = buffer_ptr(&e->input);
715 msg_len = get_u32(cp);
716 if (msg_len > 256 * 1024) {
720 if (buffer_len(&e->input) < msg_len + 4)
723 /* move the current input to e->request */
724 buffer_consume(&e->input, 4);
725 buffer_clear(&e->request);
726 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
727 buffer_consume(&e->input, msg_len);
728 type = buffer_get_char(&e->request);
730 /* check wheter agent is locked */
731 if (locked && type != SSH_AGENTC_UNLOCK) {
732 buffer_clear(&e->request);
734 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
735 case SSH2_AGENTC_REQUEST_IDENTITIES:
736 /* send empty lists */
737 no_identities(e, type);
740 /* send a fail message for all other request types */
741 buffer_put_int(&e->output, 1);
742 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
747 debug("type %d", type);
749 case SSH_AGENTC_LOCK:
750 case SSH_AGENTC_UNLOCK:
751 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);
773 case SSH2_AGENTC_SIGN_REQUEST:
774 process_sign_request2(e);
776 case SSH2_AGENTC_REQUEST_IDENTITIES:
777 process_request_identities(e, 2);
779 case SSH2_AGENTC_ADD_IDENTITY:
780 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
781 process_add_identity(e, 2);
783 case SSH2_AGENTC_REMOVE_IDENTITY:
784 process_remove_identity(e, 2);
786 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
787 process_remove_all_identities(e, 2);
790 case SSH_AGENTC_ADD_SMARTCARD_KEY:
791 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
792 process_add_smartcard_key(e);
794 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
795 process_remove_smartcard_key(e);
797 #endif /* ENABLE_PKCS11 */
799 /* Unknown message. Respond with failure. */
800 error("Unknown message %d", type);
801 buffer_clear(&e->request);
802 buffer_put_int(&e->output, 1);
803 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
809 new_socket(sock_type type, int fd)
811 u_int i, old_alloc, new_alloc;
818 for (i = 0; i < sockets_alloc; i++)
819 if (sockets[i].type == AUTH_UNUSED) {
821 buffer_init(&sockets[i].input);
822 buffer_init(&sockets[i].output);
823 buffer_init(&sockets[i].request);
824 sockets[i].type = type;
827 old_alloc = sockets_alloc;
828 new_alloc = sockets_alloc + 10;
829 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
830 for (i = old_alloc; i < new_alloc; i++)
831 sockets[i].type = AUTH_UNUSED;
832 sockets_alloc = new_alloc;
833 sockets[old_alloc].fd = fd;
834 buffer_init(&sockets[old_alloc].input);
835 buffer_init(&sockets[old_alloc].output);
836 buffer_init(&sockets[old_alloc].request);
837 sockets[old_alloc].type = type;
841 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
842 struct timeval **tvpp)
846 static struct timeval tv;
849 for (i = 0; i < sockets_alloc; i++) {
850 switch (sockets[i].type) {
852 case AUTH_CONNECTION:
853 n = MAX(n, sockets[i].fd);
858 fatal("Unknown socket type %d", sockets[i].type);
863 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
864 if (*fdrp == NULL || sz > *nallocp) {
872 debug("XXX shrink: %d < %d", n, *fdl);
874 memset(*fdrp, 0, sz);
875 memset(*fdwp, 0, sz);
877 for (i = 0; i < sockets_alloc; i++) {
878 switch (sockets[i].type) {
880 case AUTH_CONNECTION:
881 FD_SET(sockets[i].fd, *fdrp);
882 if (buffer_len(&sockets[i].output) > 0)
883 FD_SET(sockets[i].fd, *fdwp);
890 if (parent_alive_interval != 0)
891 deadline = (deadline == 0) ? parent_alive_interval :
892 MIN(deadline, parent_alive_interval);
896 tv.tv_sec = deadline;
904 after_select(fd_set *readset, fd_set *writeset)
906 struct sockaddr_un sunaddr;
914 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
915 switch (sockets[i].type) {
919 if (FD_ISSET(sockets[i].fd, readset)) {
920 slen = sizeof(sunaddr);
921 sock = accept(sockets[i].fd,
922 (struct sockaddr *)&sunaddr, &slen);
924 error("accept from AUTH_SOCKET: %s",
928 if (getpeereid(sock, &euid, &egid) < 0) {
929 error("getpeereid %d failed: %s",
930 sock, strerror(errno));
934 if ((euid != 0) && (getuid() != euid)) {
935 error("uid mismatch: "
936 "peer euid %u != uid %u",
937 (u_int) euid, (u_int) getuid());
941 new_socket(AUTH_CONNECTION, sock);
944 case AUTH_CONNECTION:
945 if (buffer_len(&sockets[i].output) > 0 &&
946 FD_ISSET(sockets[i].fd, writeset)) {
947 len = write(sockets[i].fd,
948 buffer_ptr(&sockets[i].output),
949 buffer_len(&sockets[i].output));
950 if (len == -1 && (errno == EAGAIN ||
951 errno == EWOULDBLOCK ||
955 close_socket(&sockets[i]);
958 buffer_consume(&sockets[i].output, len);
960 if (FD_ISSET(sockets[i].fd, readset)) {
961 len = read(sockets[i].fd, buf, sizeof(buf));
962 if (len == -1 && (errno == EAGAIN ||
963 errno == EWOULDBLOCK ||
967 close_socket(&sockets[i]);
970 buffer_append(&sockets[i].input, buf, len);
971 explicit_bzero(buf, sizeof(buf));
972 process_message(&sockets[i]);
976 fatal("Unknown type %d", sockets[i].type);
983 if (cleanup_pid != 0 && getpid() != cleanup_pid)
985 debug("%s: cleanup", __func__);
1001 cleanup_handler(int sig)
1004 #ifdef ENABLE_PKCS11
1011 check_parent_exists(void)
1014 * If our parent has exited then getppid() will return (pid_t)1,
1015 * so testing for that should be safe.
1017 if (parent_pid != -1 && getppid() != parent_pid) {
1018 /* printf("Parent has died - Authentication agent exiting.\n"); */
1028 "usage: ssh-agent [-c | -s] [-d] [-a bind_address] [-t life]\n"
1029 " [command [arg ...]]\n"
1030 " ssh-agent [-c | -s] -k\n");
1035 main(int ac, char **av)
1037 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1038 int sock, fd, ch, result, saved_errno;
1040 char *shell, *format, *pidstr, *agentsocket = NULL;
1041 fd_set *readsetp = NULL, *writesetp = NULL;
1042 #ifdef HAVE_SETRLIMIT
1046 extern char *optarg;
1048 char pidstrbuf[1 + 3 * sizeof pid];
1049 struct timeval *tvp = NULL;
1053 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1061 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1062 /* Disable ptrace on Linux without sgid bit */
1063 prctl(PR_SET_DUMPABLE, 0);
1067 OpenSSL_add_all_algorithms();
1070 __progname = ssh_get_progname(av[0]);
1073 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1094 agentsocket = optarg;
1097 if ((lifetime = convtime(optarg)) == -1) {
1098 fprintf(stderr, "Invalid lifetime\n");
1109 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1112 if (ac == 0 && !c_flag && !s_flag) {
1113 shell = getenv("SHELL");
1114 if (shell != NULL && (len = strlen(shell)) > 2 &&
1115 strncmp(shell + len - 3, "csh", 3) == 0)
1119 const char *errstr = NULL;
1121 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1122 if (pidstr == NULL) {
1123 fprintf(stderr, "%s not set, cannot kill agent\n",
1124 SSH_AGENTPID_ENV_NAME);
1127 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1130 "%s=\"%s\", which is not a good PID: %s\n",
1131 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1134 if (kill(pid, SIGTERM) == -1) {
1138 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1139 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1140 printf(format, SSH_AGENTPID_ENV_NAME);
1141 printf("echo Agent pid %ld killed;\n", (long)pid);
1144 parent_pid = getpid();
1146 if (agentsocket == NULL) {
1147 /* Create private directory for agent socket */
1148 mktemp_proto(socket_dir, sizeof(socket_dir));
1149 if (mkdtemp(socket_dir) == NULL) {
1150 perror("mkdtemp: private socket dir");
1153 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1156 /* Try to use specified agent socket */
1157 socket_dir[0] = '\0';
1158 strlcpy(socket_name, agentsocket, sizeof socket_name);
1162 * Create socket early so it will exist before command gets run from
1165 prev_mask = umask(0177);
1166 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1168 /* XXX - unix_listener() calls error() not perror() */
1169 *socket_name = '\0'; /* Don't unlink any existing file */
1175 * Fork, and have the parent execute the command, if any, or present
1176 * the socket data. The child continues as the authentication agent.
1179 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1180 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1181 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1182 SSH_AUTHSOCKET_ENV_NAME);
1183 printf("echo Agent pid %ld;\n", (long)parent_pid);
1191 if (pid != 0) { /* Parent - execute the given command. */
1193 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1195 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1196 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1197 SSH_AUTHSOCKET_ENV_NAME);
1198 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1199 SSH_AGENTPID_ENV_NAME);
1200 printf("echo Agent pid %ld;\n", (long)pid);
1203 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1204 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1213 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1215 if (setsid() == -1) {
1216 error("setsid: %s", strerror(errno));
1221 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1222 /* XXX might close listen socket */
1223 (void)dup2(fd, STDIN_FILENO);
1224 (void)dup2(fd, STDOUT_FILENO);
1225 (void)dup2(fd, STDERR_FILENO);
1230 #ifdef HAVE_SETRLIMIT
1231 /* deny core dumps, since memory contains unencrypted private keys */
1232 rlim.rlim_cur = rlim.rlim_max = 0;
1233 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1234 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1241 cleanup_pid = getpid();
1243 #ifdef ENABLE_PKCS11
1246 new_socket(AUTH_SOCKET, sock);
1248 parent_alive_interval = 10;
1250 signal(SIGPIPE, SIG_IGN);
1251 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1252 signal(SIGHUP, cleanup_handler);
1253 signal(SIGTERM, cleanup_handler);
1257 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1258 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1259 saved_errno = errno;
1260 if (parent_alive_interval != 0)
1261 check_parent_exists();
1262 (void) reaper(); /* remove expired keys */
1264 if (saved_errno == EINTR)
1266 fatal("select: %s", strerror(saved_errno));
1267 } else if (result > 0)
1268 after_select(readsetp, writesetp);