1 /* $OpenBSD: ssh-agent.c,v 1.183 2014/02/02 03:44:31 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.
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 "openbsd-compat/openssl-compat.h"
80 #include "ssh-pkcs11.h"
83 #if defined(HAVE_SYS_PRCTL_H)
84 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
101 u_int sockets_alloc = 0;
102 SocketEntry *sockets = NULL;
104 typedef struct identity {
105 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 time_t 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 in seconds (0 == forever) */
138 static long 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)
180 /* return matching private key for given public key */
182 lookup_identity(Key *key, int version)
186 Idtab *tab = idtab_lookup(version);
187 TAILQ_FOREACH(id, &tab->idlist, next) {
188 if (key_equal(key, id->key))
194 /* Check confirmation of keysign request */
196 confirm_key(Identity *id)
201 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
202 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
210 /* send list of supported public keys to 'client' */
212 process_request_identities(SocketEntry *e, int version)
214 Idtab *tab = idtab_lookup(version);
219 buffer_put_char(&msg, (version == 1) ?
220 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
221 buffer_put_int(&msg, tab->nentries);
222 TAILQ_FOREACH(id, &tab->idlist, next) {
223 if (id->key->type == KEY_RSA1) {
224 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
225 buffer_put_bignum(&msg, id->key->rsa->e);
226 buffer_put_bignum(&msg, id->key->rsa->n);
230 key_to_blob(id->key, &blob, &blen);
231 buffer_put_string(&msg, blob, blen);
234 buffer_put_cstring(&msg, id->comment);
236 buffer_put_int(&e->output, buffer_len(&msg));
237 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
243 process_authentication_challenge1(SocketEntry *e)
245 u_char buf[32], mdbuf[16], session_id[16];
251 struct ssh_digest_ctx *md;
255 key = key_new(KEY_RSA1);
256 if ((challenge = BN_new()) == NULL)
257 fatal("process_authentication_challenge1: BN_new failed");
259 (void) buffer_get_int(&e->request); /* ignored */
260 buffer_get_bignum(&e->request, key->rsa->e);
261 buffer_get_bignum(&e->request, key->rsa->n);
262 buffer_get_bignum(&e->request, challenge);
264 /* Only protocol 1.1 is supported */
265 if (buffer_len(&e->request) == 0)
267 buffer_get(&e->request, session_id, 16);
268 response_type = buffer_get_int(&e->request);
269 if (response_type != 1)
272 id = lookup_identity(key, 1);
273 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
274 Key *private = id->key;
275 /* Decrypt the challenge using the private key. */
276 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
279 /* The response is MD5 of decrypted challenge plus session id. */
280 len = BN_num_bytes(challenge);
281 if (len <= 0 || len > 32) {
282 logit("process_authentication_challenge: bad challenge length %d", len);
286 BN_bn2bin(challenge, buf + 32 - len);
287 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
288 ssh_digest_update(md, buf, 32) < 0 ||
289 ssh_digest_update(md, session_id, 16) < 0 ||
290 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
291 fatal("%s: md5 failed", __func__);
294 /* Send the response. */
295 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
296 for (i = 0; i < 16; i++)
297 buffer_put_char(&msg, mdbuf[i]);
302 /* Unknown identity or protocol error. Send failure. */
303 buffer_put_char(&msg, SSH_AGENT_FAILURE);
305 buffer_put_int(&e->output, buffer_len(&msg));
306 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
308 BN_clear_free(challenge);
314 process_sign_request2(SocketEntry *e)
316 u_char *blob, *data, *signature = NULL;
317 u_int blen, dlen, slen = 0;
318 extern int datafellows;
326 blob = buffer_get_string(&e->request, &blen);
327 data = buffer_get_string(&e->request, &dlen);
329 flags = buffer_get_int(&e->request);
330 odatafellows = datafellows;
331 if (flags & SSH_AGENT_OLD_SIGNATURE)
332 datafellows = SSH_BUG_SIGBLOB;
334 key = key_from_blob(blob, blen);
336 Identity *id = lookup_identity(key, 2);
337 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
338 ok = key_sign(id->key, &signature, &slen, data, dlen);
343 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
344 buffer_put_string(&msg, signature, slen);
346 buffer_put_char(&msg, SSH_AGENT_FAILURE);
348 buffer_put_int(&e->output, buffer_len(&msg));
349 buffer_append(&e->output, buffer_ptr(&msg),
355 datafellows = odatafellows;
360 process_remove_identity(SocketEntry *e, int version)
369 key = key_new(KEY_RSA1);
370 bits = buffer_get_int(&e->request);
371 buffer_get_bignum(&e->request, key->rsa->e);
372 buffer_get_bignum(&e->request, key->rsa->n);
374 if (bits != key_size(key))
375 logit("Warning: identity keysize mismatch: actual %u, announced %u",
376 key_size(key), bits);
379 blob = buffer_get_string(&e->request, &blen);
380 key = key_from_blob(blob, blen);
385 Identity *id = lookup_identity(key, version);
388 * We have this key. Free the old key. Since we
389 * don't want to leave empty slots in the middle of
390 * the array, we actually free the key there and move
391 * all the entries between the empty slot and the end
394 Idtab *tab = idtab_lookup(version);
395 if (tab->nentries < 1)
396 fatal("process_remove_identity: "
397 "internal error: tab->nentries %d",
399 TAILQ_REMOVE(&tab->idlist, id, next);
406 buffer_put_int(&e->output, 1);
407 buffer_put_char(&e->output,
408 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
412 process_remove_all_identities(SocketEntry *e, int version)
414 Idtab *tab = idtab_lookup(version);
417 /* Loop over all identities and clear the keys. */
418 for (id = TAILQ_FIRST(&tab->idlist); id;
419 id = TAILQ_FIRST(&tab->idlist)) {
420 TAILQ_REMOVE(&tab->idlist, id, next);
424 /* Mark that there are no identities. */
428 buffer_put_int(&e->output, 1);
429 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
432 /* removes expired keys and returns number of seconds until the next expiry */
436 time_t deadline = 0, now = monotime();
441 for (version = 1; version < 3; version++) {
442 tab = idtab_lookup(version);
443 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
444 nxt = TAILQ_NEXT(id, next);
447 if (now >= id->death) {
448 debug("expiring key '%s'", id->comment);
449 TAILQ_REMOVE(&tab->idlist, id, next);
453 deadline = (deadline == 0) ? id->death :
454 MIN(deadline, id->death);
457 if (deadline == 0 || deadline <= now)
460 return (deadline - now);
464 process_add_identity(SocketEntry *e, int version)
466 Idtab *tab = idtab_lookup(version);
468 int type, success = 0, confirm = 0;
475 k = key_new_private(KEY_RSA1);
476 (void) buffer_get_int(&e->request); /* ignored */
477 buffer_get_bignum(&e->request, k->rsa->n);
478 buffer_get_bignum(&e->request, k->rsa->e);
479 buffer_get_bignum(&e->request, k->rsa->d);
480 buffer_get_bignum(&e->request, k->rsa->iqmp);
482 /* SSH and SSL have p and q swapped */
483 buffer_get_bignum(&e->request, k->rsa->q); /* p */
484 buffer_get_bignum(&e->request, k->rsa->p); /* q */
486 /* Generate additional parameters */
487 rsa_generate_additional_parameters(k->rsa);
489 /* enable blinding */
490 if (RSA_blinding_on(k->rsa, NULL) != 1) {
491 error("process_add_identity: RSA_blinding_on failed");
497 k = key_private_deserialize(&e->request);
499 buffer_clear(&e->request);
504 comment = buffer_get_string(&e->request, NULL);
509 while (buffer_len(&e->request)) {
510 switch ((type = buffer_get_char(&e->request))) {
511 case SSH_AGENT_CONSTRAIN_LIFETIME:
512 death = monotime() + buffer_get_int(&e->request);
514 case SSH_AGENT_CONSTRAIN_CONFIRM:
518 error("process_add_identity: "
519 "Unknown constraint type %d", type);
526 if (lifetime && !death)
527 death = monotime() + lifetime;
528 if ((id = lookup_identity(k, version)) == NULL) {
529 id = xcalloc(1, sizeof(Identity));
531 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
532 /* Increment the number of identities. */
538 id->comment = comment;
540 id->confirm = confirm;
542 buffer_put_int(&e->output, 1);
543 buffer_put_char(&e->output,
544 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
547 /* XXX todo: encrypt sensitive data with passphrase */
549 process_lock_agent(SocketEntry *e, int lock)
554 passwd = buffer_get_string(&e->request, NULL);
555 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
557 explicit_bzero(lock_passwd, strlen(lock_passwd));
561 } else if (!locked && lock) {
563 lock_passwd = xstrdup(passwd);
566 explicit_bzero(passwd, strlen(passwd));
569 buffer_put_int(&e->output, 1);
570 buffer_put_char(&e->output,
571 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
575 no_identities(SocketEntry *e, u_int type)
580 buffer_put_char(&msg,
581 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
582 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
583 buffer_put_int(&msg, 0);
584 buffer_put_int(&e->output, buffer_len(&msg));
585 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
591 process_add_smartcard_key(SocketEntry *e)
593 char *provider = NULL, *pin;
594 int i, type, version, count = 0, success = 0, confirm = 0;
596 Key **keys = NULL, *k;
600 provider = buffer_get_string(&e->request, NULL);
601 pin = buffer_get_string(&e->request, NULL);
603 while (buffer_len(&e->request)) {
604 switch ((type = buffer_get_char(&e->request))) {
605 case SSH_AGENT_CONSTRAIN_LIFETIME:
606 death = monotime() + buffer_get_int(&e->request);
608 case SSH_AGENT_CONSTRAIN_CONFIRM:
612 error("process_add_smartcard_key: "
613 "Unknown constraint type %d", type);
617 if (lifetime && !death)
618 death = monotime() + lifetime;
620 count = pkcs11_add_provider(provider, pin, &keys);
621 for (i = 0; i < count; i++) {
623 version = k->type == KEY_RSA1 ? 1 : 2;
624 tab = idtab_lookup(version);
625 if (lookup_identity(k, version) == NULL) {
626 id = xcalloc(1, sizeof(Identity));
628 id->provider = xstrdup(provider);
629 id->comment = xstrdup(provider); /* XXX */
631 id->confirm = confirm;
632 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
644 buffer_put_int(&e->output, 1);
645 buffer_put_char(&e->output,
646 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
650 process_remove_smartcard_key(SocketEntry *e)
652 char *provider = NULL, *pin = NULL;
653 int version, success = 0;
657 provider = buffer_get_string(&e->request, NULL);
658 pin = buffer_get_string(&e->request, NULL);
661 for (version = 1; version < 3; version++) {
662 tab = idtab_lookup(version);
663 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
664 nxt = TAILQ_NEXT(id, next);
665 /* Skip file--based keys */
666 if (id->provider == NULL)
668 if (!strcmp(provider, id->provider)) {
669 TAILQ_REMOVE(&tab->idlist, id, next);
675 if (pkcs11_del_provider(provider) == 0)
678 error("process_remove_smartcard_key:"
679 " pkcs11_del_provider failed");
681 buffer_put_int(&e->output, 1);
682 buffer_put_char(&e->output,
683 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
685 #endif /* ENABLE_PKCS11 */
687 /* dispatch incoming messages */
690 process_message(SocketEntry *e)
695 if (buffer_len(&e->input) < 5)
696 return; /* Incomplete message. */
697 cp = buffer_ptr(&e->input);
698 msg_len = get_u32(cp);
699 if (msg_len > 256 * 1024) {
703 if (buffer_len(&e->input) < msg_len + 4)
706 /* move the current input to e->request */
707 buffer_consume(&e->input, 4);
708 buffer_clear(&e->request);
709 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
710 buffer_consume(&e->input, msg_len);
711 type = buffer_get_char(&e->request);
713 /* check wheter agent is locked */
714 if (locked && type != SSH_AGENTC_UNLOCK) {
715 buffer_clear(&e->request);
717 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
718 case SSH2_AGENTC_REQUEST_IDENTITIES:
719 /* send empty lists */
720 no_identities(e, type);
723 /* send a fail message for all other request types */
724 buffer_put_int(&e->output, 1);
725 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
730 debug("type %d", type);
732 case SSH_AGENTC_LOCK:
733 case SSH_AGENTC_UNLOCK:
734 process_lock_agent(e, type == SSH_AGENTC_LOCK);
737 case SSH_AGENTC_RSA_CHALLENGE:
738 process_authentication_challenge1(e);
740 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
741 process_request_identities(e, 1);
743 case SSH_AGENTC_ADD_RSA_IDENTITY:
744 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
745 process_add_identity(e, 1);
747 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
748 process_remove_identity(e, 1);
750 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
751 process_remove_all_identities(e, 1);
754 case SSH2_AGENTC_SIGN_REQUEST:
755 process_sign_request2(e);
757 case SSH2_AGENTC_REQUEST_IDENTITIES:
758 process_request_identities(e, 2);
760 case SSH2_AGENTC_ADD_IDENTITY:
761 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
762 process_add_identity(e, 2);
764 case SSH2_AGENTC_REMOVE_IDENTITY:
765 process_remove_identity(e, 2);
767 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
768 process_remove_all_identities(e, 2);
771 case SSH_AGENTC_ADD_SMARTCARD_KEY:
772 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
773 process_add_smartcard_key(e);
775 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
776 process_remove_smartcard_key(e);
778 #endif /* ENABLE_PKCS11 */
780 /* Unknown message. Respond with failure. */
781 error("Unknown message %d", type);
782 buffer_clear(&e->request);
783 buffer_put_int(&e->output, 1);
784 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
790 new_socket(sock_type type, int fd)
792 u_int i, old_alloc, new_alloc;
799 for (i = 0; i < sockets_alloc; i++)
800 if (sockets[i].type == AUTH_UNUSED) {
802 buffer_init(&sockets[i].input);
803 buffer_init(&sockets[i].output);
804 buffer_init(&sockets[i].request);
805 sockets[i].type = type;
808 old_alloc = sockets_alloc;
809 new_alloc = sockets_alloc + 10;
810 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
811 for (i = old_alloc; i < new_alloc; i++)
812 sockets[i].type = AUTH_UNUSED;
813 sockets_alloc = new_alloc;
814 sockets[old_alloc].fd = fd;
815 buffer_init(&sockets[old_alloc].input);
816 buffer_init(&sockets[old_alloc].output);
817 buffer_init(&sockets[old_alloc].request);
818 sockets[old_alloc].type = type;
822 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
823 struct timeval **tvpp)
827 static struct timeval tv;
830 for (i = 0; i < sockets_alloc; i++) {
831 switch (sockets[i].type) {
833 case AUTH_CONNECTION:
834 n = MAX(n, sockets[i].fd);
839 fatal("Unknown socket type %d", sockets[i].type);
844 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
845 if (*fdrp == NULL || sz > *nallocp) {
853 debug("XXX shrink: %d < %d", n, *fdl);
855 memset(*fdrp, 0, sz);
856 memset(*fdwp, 0, sz);
858 for (i = 0; i < sockets_alloc; i++) {
859 switch (sockets[i].type) {
861 case AUTH_CONNECTION:
862 FD_SET(sockets[i].fd, *fdrp);
863 if (buffer_len(&sockets[i].output) > 0)
864 FD_SET(sockets[i].fd, *fdwp);
871 if (parent_alive_interval != 0)
872 deadline = (deadline == 0) ? parent_alive_interval :
873 MIN(deadline, parent_alive_interval);
877 tv.tv_sec = deadline;
885 after_select(fd_set *readset, fd_set *writeset)
887 struct sockaddr_un sunaddr;
895 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
896 switch (sockets[i].type) {
900 if (FD_ISSET(sockets[i].fd, readset)) {
901 slen = sizeof(sunaddr);
902 sock = accept(sockets[i].fd,
903 (struct sockaddr *)&sunaddr, &slen);
905 error("accept from AUTH_SOCKET: %s",
909 if (getpeereid(sock, &euid, &egid) < 0) {
910 error("getpeereid %d failed: %s",
911 sock, strerror(errno));
915 if ((euid != 0) && (getuid() != euid)) {
916 error("uid mismatch: "
917 "peer euid %u != uid %u",
918 (u_int) euid, (u_int) getuid());
922 new_socket(AUTH_CONNECTION, sock);
925 case AUTH_CONNECTION:
926 if (buffer_len(&sockets[i].output) > 0 &&
927 FD_ISSET(sockets[i].fd, writeset)) {
928 len = write(sockets[i].fd,
929 buffer_ptr(&sockets[i].output),
930 buffer_len(&sockets[i].output));
931 if (len == -1 && (errno == EAGAIN ||
932 errno == EWOULDBLOCK ||
936 close_socket(&sockets[i]);
939 buffer_consume(&sockets[i].output, len);
941 if (FD_ISSET(sockets[i].fd, readset)) {
942 len = read(sockets[i].fd, buf, sizeof(buf));
943 if (len == -1 && (errno == EAGAIN ||
944 errno == EWOULDBLOCK ||
948 close_socket(&sockets[i]);
951 buffer_append(&sockets[i].input, buf, len);
952 process_message(&sockets[i]);
956 fatal("Unknown type %d", sockets[i].type);
978 cleanup_handler(int sig)
988 check_parent_exists(void)
991 * If our parent has exited then getppid() will return (pid_t)1,
992 * so testing for that should be safe.
994 if (parent_pid != -1 && getppid() != parent_pid) {
995 /* printf("Parent has died - Authentication agent exiting.\n"); */
1004 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1006 fprintf(stderr, "Options:\n");
1007 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1008 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1009 fprintf(stderr, " -k Kill the current agent.\n");
1010 fprintf(stderr, " -d Debug mode.\n");
1011 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1012 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1017 main(int ac, char **av)
1019 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1020 int sock, fd, ch, result, saved_errno;
1022 char *shell, *format, *pidstr, *agentsocket = NULL;
1023 fd_set *readsetp = NULL, *writesetp = NULL;
1024 struct sockaddr_un sunaddr;
1025 #ifdef HAVE_SETRLIMIT
1030 extern char *optarg;
1032 char pidstrbuf[1 + 3 * sizeof pid];
1033 struct timeval *tvp = NULL;
1036 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1043 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1044 /* Disable ptrace on Linux without sgid bit */
1045 prctl(PR_SET_DUMPABLE, 0);
1048 OpenSSL_add_all_algorithms();
1050 __progname = ssh_get_progname(av[0]);
1053 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1074 agentsocket = optarg;
1077 if ((lifetime = convtime(optarg)) == -1) {
1078 fprintf(stderr, "Invalid lifetime\n");
1089 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1092 if (ac == 0 && !c_flag && !s_flag) {
1093 shell = getenv("SHELL");
1094 if (shell != NULL && (len = strlen(shell)) > 2 &&
1095 strncmp(shell + len - 3, "csh", 3) == 0)
1099 const char *errstr = NULL;
1101 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1102 if (pidstr == NULL) {
1103 fprintf(stderr, "%s not set, cannot kill agent\n",
1104 SSH_AGENTPID_ENV_NAME);
1107 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1110 "%s=\"%s\", which is not a good PID: %s\n",
1111 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1114 if (kill(pid, SIGTERM) == -1) {
1118 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1119 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1120 printf(format, SSH_AGENTPID_ENV_NAME);
1121 printf("echo Agent pid %ld killed;\n", (long)pid);
1124 parent_pid = getpid();
1126 if (agentsocket == NULL) {
1127 /* Create private directory for agent socket */
1128 mktemp_proto(socket_dir, sizeof(socket_dir));
1129 if (mkdtemp(socket_dir) == NULL) {
1130 perror("mkdtemp: private socket dir");
1133 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1136 /* Try to use specified agent socket */
1137 socket_dir[0] = '\0';
1138 strlcpy(socket_name, agentsocket, sizeof socket_name);
1142 * Create socket early so it will exist before command gets run from
1145 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1148 *socket_name = '\0'; /* Don't unlink any existing file */
1151 memset(&sunaddr, 0, sizeof(sunaddr));
1152 sunaddr.sun_family = AF_UNIX;
1153 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1154 prev_mask = umask(0177);
1155 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1157 *socket_name = '\0'; /* Don't unlink any existing file */
1162 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1168 * Fork, and have the parent execute the command, if any, or present
1169 * the socket data. The child continues as the authentication agent.
1172 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1173 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1174 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1175 SSH_AUTHSOCKET_ENV_NAME);
1176 printf("echo Agent pid %ld;\n", (long)parent_pid);
1184 if (pid != 0) { /* Parent - execute the given command. */
1186 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1188 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1189 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1190 SSH_AUTHSOCKET_ENV_NAME);
1191 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1192 SSH_AGENTPID_ENV_NAME);
1193 printf("echo Agent pid %ld;\n", (long)pid);
1196 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1197 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1206 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1208 if (setsid() == -1) {
1209 error("setsid: %s", strerror(errno));
1214 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1215 /* XXX might close listen socket */
1216 (void)dup2(fd, STDIN_FILENO);
1217 (void)dup2(fd, STDOUT_FILENO);
1218 (void)dup2(fd, STDERR_FILENO);
1223 #ifdef HAVE_SETRLIMIT
1224 /* deny core dumps, since memory contains unencrypted private keys */
1225 rlim.rlim_cur = rlim.rlim_max = 0;
1226 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1227 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1234 #ifdef ENABLE_PKCS11
1237 new_socket(AUTH_SOCKET, sock);
1239 parent_alive_interval = 10;
1241 signal(SIGPIPE, SIG_IGN);
1242 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1243 signal(SIGHUP, cleanup_handler);
1244 signal(SIGTERM, cleanup_handler);
1248 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1249 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1250 saved_errno = errno;
1251 if (parent_alive_interval != 0)
1252 check_parent_exists();
1253 (void) reaper(); /* remove expired keys */
1255 if (saved_errno == EINTR)
1257 fatal("select: %s", strerror(saved_errno));
1258 } else if (result > 0)
1259 after_select(readsetp, writesetp);