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.
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 "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];
271 struct ssh_digest_ctx *md;
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);
307 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
308 ssh_digest_update(md, buf, 32) < 0 ||
309 ssh_digest_update(md, session_id, 16) < 0 ||
310 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
311 fatal("%s: md5 failed", __func__);
314 /* Send the response. */
315 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
316 for (i = 0; i < 16; i++)
317 buffer_put_char(&msg, mdbuf[i]);
322 /* Unknown identity or protocol error. Send failure. */
323 buffer_put_char(&msg, SSH_AGENT_FAILURE);
325 buffer_put_int(&e->output, buffer_len(&msg));
326 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
328 BN_clear_free(challenge);
334 process_sign_request2(SocketEntry *e)
336 u_char *blob, *data, *signature = NULL;
337 u_int blen, dlen, slen = 0;
338 extern int datafellows;
346 blob = buffer_get_string(&e->request, &blen);
347 data = buffer_get_string(&e->request, &dlen);
349 flags = buffer_get_int(&e->request);
350 odatafellows = datafellows;
351 if (flags & SSH_AGENT_OLD_SIGNATURE)
352 datafellows = SSH_BUG_SIGBLOB;
354 key = key_from_blob(blob, blen);
356 Identity *id = lookup_identity(key, 2);
357 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
358 ok = key_sign(id->key, &signature, &slen, data, dlen);
363 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
364 buffer_put_string(&msg, signature, slen);
366 buffer_put_char(&msg, SSH_AGENT_FAILURE);
368 buffer_put_int(&e->output, buffer_len(&msg));
369 buffer_append(&e->output, buffer_ptr(&msg),
375 datafellows = odatafellows;
380 process_remove_identity(SocketEntry *e, int version)
389 key = key_new(KEY_RSA1);
390 bits = buffer_get_int(&e->request);
391 buffer_get_bignum(&e->request, key->rsa->e);
392 buffer_get_bignum(&e->request, key->rsa->n);
394 if (bits != key_size(key))
395 logit("Warning: identity keysize mismatch: actual %u, announced %u",
396 key_size(key), bits);
399 blob = buffer_get_string(&e->request, &blen);
400 key = key_from_blob(blob, blen);
405 Identity *id = lookup_identity(key, version);
408 * We have this key. Free the old key. Since we
409 * don't want to leave empty slots in the middle of
410 * the array, we actually free the key there and move
411 * all the entries between the empty slot and the end
414 Idtab *tab = idtab_lookup(version);
415 if (tab->nentries < 1)
416 fatal("process_remove_identity: "
417 "internal error: tab->nentries %d",
419 TAILQ_REMOVE(&tab->idlist, id, next);
426 buffer_put_int(&e->output, 1);
427 buffer_put_char(&e->output,
428 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
432 process_remove_all_identities(SocketEntry *e, int version)
434 Idtab *tab = idtab_lookup(version);
437 /* Loop over all identities and clear the keys. */
438 for (id = TAILQ_FIRST(&tab->idlist); id;
439 id = TAILQ_FIRST(&tab->idlist)) {
440 TAILQ_REMOVE(&tab->idlist, id, next);
444 /* Mark that there are no identities. */
448 buffer_put_int(&e->output, 1);
449 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
452 /* removes expired keys and returns number of seconds until the next expiry */
456 time_t deadline = 0, now = monotime();
461 for (version = 1; version < 3; version++) {
462 tab = idtab_lookup(version);
463 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
464 nxt = TAILQ_NEXT(id, next);
467 if (now >= id->death) {
468 debug("expiring key '%s'", id->comment);
469 TAILQ_REMOVE(&tab->idlist, id, next);
473 deadline = (deadline == 0) ? id->death :
474 MIN(deadline, id->death);
477 if (deadline == 0 || deadline <= now)
480 return (deadline - now);
484 process_add_identity(SocketEntry *e, int version)
486 Idtab *tab = idtab_lookup(version);
488 int type, success = 0, confirm = 0;
495 k = key_new_private(KEY_RSA1);
496 (void) buffer_get_int(&e->request); /* ignored */
497 buffer_get_bignum(&e->request, k->rsa->n);
498 buffer_get_bignum(&e->request, k->rsa->e);
499 buffer_get_bignum(&e->request, k->rsa->d);
500 buffer_get_bignum(&e->request, k->rsa->iqmp);
502 /* SSH and SSL have p and q swapped */
503 buffer_get_bignum(&e->request, k->rsa->q); /* p */
504 buffer_get_bignum(&e->request, k->rsa->p); /* q */
506 /* Generate additional parameters */
507 rsa_generate_additional_parameters(k->rsa);
509 /* enable blinding */
510 if (RSA_blinding_on(k->rsa, NULL) != 1) {
511 error("process_add_identity: RSA_blinding_on failed");
517 k = key_private_deserialize(&e->request);
519 buffer_clear(&e->request);
524 comment = buffer_get_string(&e->request, NULL);
529 while (buffer_len(&e->request)) {
530 switch ((type = buffer_get_char(&e->request))) {
531 case SSH_AGENT_CONSTRAIN_LIFETIME:
532 death = monotime() + buffer_get_int(&e->request);
534 case SSH_AGENT_CONSTRAIN_CONFIRM:
538 error("process_add_identity: "
539 "Unknown constraint type %d", type);
546 if (lifetime && !death)
547 death = monotime() + lifetime;
548 if ((id = lookup_identity(k, version)) == NULL) {
549 id = xcalloc(1, sizeof(Identity));
551 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
552 /* Increment the number of identities. */
558 id->comment = comment;
560 id->confirm = confirm;
562 buffer_put_int(&e->output, 1);
563 buffer_put_char(&e->output,
564 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
567 /* XXX todo: encrypt sensitive data with passphrase */
569 process_lock_agent(SocketEntry *e, int lock)
574 passwd = buffer_get_string(&e->request, NULL);
575 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
577 explicit_bzero(lock_passwd, strlen(lock_passwd));
581 } else if (!locked && lock) {
583 lock_passwd = xstrdup(passwd);
586 explicit_bzero(passwd, strlen(passwd));
589 buffer_put_int(&e->output, 1);
590 buffer_put_char(&e->output,
591 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
595 no_identities(SocketEntry *e, u_int type)
600 buffer_put_char(&msg,
601 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
602 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
603 buffer_put_int(&msg, 0);
604 buffer_put_int(&e->output, buffer_len(&msg));
605 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
611 process_add_smartcard_key(SocketEntry *e)
613 char *provider = NULL, *pin;
614 int i, type, version, count = 0, success = 0, confirm = 0;
616 Key **keys = NULL, *k;
620 provider = buffer_get_string(&e->request, NULL);
621 pin = buffer_get_string(&e->request, NULL);
623 while (buffer_len(&e->request)) {
624 switch ((type = buffer_get_char(&e->request))) {
625 case SSH_AGENT_CONSTRAIN_LIFETIME:
626 death = monotime() + buffer_get_int(&e->request);
628 case SSH_AGENT_CONSTRAIN_CONFIRM:
632 error("process_add_smartcard_key: "
633 "Unknown constraint type %d", type);
637 if (lifetime && !death)
638 death = monotime() + lifetime;
640 count = pkcs11_add_provider(provider, pin, &keys);
641 for (i = 0; i < count; i++) {
643 version = k->type == KEY_RSA1 ? 1 : 2;
644 tab = idtab_lookup(version);
645 if (lookup_identity(k, version) == NULL) {
646 id = xcalloc(1, sizeof(Identity));
648 id->provider = xstrdup(provider);
649 id->comment = xstrdup(provider); /* XXX */
651 id->confirm = confirm;
652 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
664 buffer_put_int(&e->output, 1);
665 buffer_put_char(&e->output,
666 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
670 process_remove_smartcard_key(SocketEntry *e)
672 char *provider = NULL, *pin = NULL;
673 int version, success = 0;
677 provider = buffer_get_string(&e->request, NULL);
678 pin = buffer_get_string(&e->request, NULL);
681 for (version = 1; version < 3; version++) {
682 tab = idtab_lookup(version);
683 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
684 nxt = TAILQ_NEXT(id, next);
685 /* Skip file--based keys */
686 if (id->provider == NULL)
688 if (!strcmp(provider, id->provider)) {
689 TAILQ_REMOVE(&tab->idlist, id, next);
695 if (pkcs11_del_provider(provider) == 0)
698 error("process_remove_smartcard_key:"
699 " pkcs11_del_provider failed");
701 buffer_put_int(&e->output, 1);
702 buffer_put_char(&e->output,
703 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
705 #endif /* ENABLE_PKCS11 */
707 /* dispatch incoming messages */
710 process_message(SocketEntry *e)
715 if (buffer_len(&e->input) < 5)
716 return; /* Incomplete message. */
717 cp = buffer_ptr(&e->input);
718 msg_len = get_u32(cp);
719 if (msg_len > 256 * 1024) {
723 if (buffer_len(&e->input) < msg_len + 4)
726 /* move the current input to e->request */
727 buffer_consume(&e->input, 4);
728 buffer_clear(&e->request);
729 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
730 buffer_consume(&e->input, msg_len);
731 type = buffer_get_char(&e->request);
733 /* check wheter agent is locked */
734 if (locked && type != SSH_AGENTC_UNLOCK) {
735 buffer_clear(&e->request);
737 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
738 case SSH2_AGENTC_REQUEST_IDENTITIES:
739 /* send empty lists */
740 no_identities(e, type);
743 /* send a fail message for all other request types */
744 buffer_put_int(&e->output, 1);
745 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
750 debug("type %d", type);
752 case SSH_AGENTC_LOCK:
753 case SSH_AGENTC_UNLOCK:
754 process_lock_agent(e, type == SSH_AGENTC_LOCK);
757 case SSH_AGENTC_RSA_CHALLENGE:
758 process_authentication_challenge1(e);
760 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
761 process_request_identities(e, 1);
763 case SSH_AGENTC_ADD_RSA_IDENTITY:
764 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
765 process_add_identity(e, 1);
767 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
768 process_remove_identity(e, 1);
770 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
771 process_remove_all_identities(e, 1);
774 case SSH2_AGENTC_SIGN_REQUEST:
775 process_sign_request2(e);
777 case SSH2_AGENTC_REQUEST_IDENTITIES:
778 process_request_identities(e, 2);
780 case SSH2_AGENTC_ADD_IDENTITY:
781 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
782 process_add_identity(e, 2);
784 case SSH2_AGENTC_REMOVE_IDENTITY:
785 process_remove_identity(e, 2);
787 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
788 process_remove_all_identities(e, 2);
791 case SSH_AGENTC_ADD_SMARTCARD_KEY:
792 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
793 process_add_smartcard_key(e);
795 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
796 process_remove_smartcard_key(e);
798 #endif /* ENABLE_PKCS11 */
800 /* Unknown message. Respond with failure. */
801 error("Unknown message %d", type);
802 buffer_clear(&e->request);
803 buffer_put_int(&e->output, 1);
804 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
810 new_socket(sock_type type, int fd)
812 u_int i, old_alloc, new_alloc;
814 if (type == AUTH_CONNECTION) {
815 debug("xcount %d -> %d", xcount, xcount + 1);
823 for (i = 0; i < sockets_alloc; i++)
824 if (sockets[i].type == AUTH_UNUSED) {
826 buffer_init(&sockets[i].input);
827 buffer_init(&sockets[i].output);
828 buffer_init(&sockets[i].request);
829 sockets[i].type = type;
832 old_alloc = sockets_alloc;
833 new_alloc = sockets_alloc + 10;
834 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
835 for (i = old_alloc; i < new_alloc; i++)
836 sockets[i].type = AUTH_UNUSED;
837 sockets_alloc = new_alloc;
838 sockets[old_alloc].fd = fd;
839 buffer_init(&sockets[old_alloc].input);
840 buffer_init(&sockets[old_alloc].output);
841 buffer_init(&sockets[old_alloc].request);
842 sockets[old_alloc].type = type;
846 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
847 struct timeval **tvpp)
851 static struct timeval tv;
854 for (i = 0; i < sockets_alloc; i++) {
855 switch (sockets[i].type) {
857 case AUTH_CONNECTION:
858 n = MAX(n, sockets[i].fd);
863 fatal("Unknown socket type %d", sockets[i].type);
868 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
869 if (*fdrp == NULL || sz > *nallocp) {
877 debug("XXX shrink: %d < %d", n, *fdl);
879 memset(*fdrp, 0, sz);
880 memset(*fdwp, 0, sz);
882 for (i = 0; i < sockets_alloc; i++) {
883 switch (sockets[i].type) {
885 case AUTH_CONNECTION:
886 FD_SET(sockets[i].fd, *fdrp);
887 if (buffer_len(&sockets[i].output) > 0)
888 FD_SET(sockets[i].fd, *fdwp);
895 if (parent_alive_interval != 0)
896 deadline = (deadline == 0) ? parent_alive_interval :
897 MIN(deadline, parent_alive_interval);
901 tv.tv_sec = deadline;
909 after_select(fd_set *readset, fd_set *writeset)
911 struct sockaddr_un sunaddr;
919 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
920 switch (sockets[i].type) {
924 if (FD_ISSET(sockets[i].fd, readset)) {
925 slen = sizeof(sunaddr);
926 sock = accept(sockets[i].fd,
927 (struct sockaddr *)&sunaddr, &slen);
929 error("accept from AUTH_SOCKET: %s",
933 if (getpeereid(sock, &euid, &egid) < 0) {
934 error("getpeereid %d failed: %s",
935 sock, strerror(errno));
939 if ((euid != 0) && (getuid() != euid)) {
940 error("uid mismatch: "
941 "peer euid %u != uid %u",
942 (u_int) euid, (u_int) getuid());
946 new_socket(AUTH_CONNECTION, sock);
949 case AUTH_CONNECTION:
950 if (buffer_len(&sockets[i].output) > 0 &&
951 FD_ISSET(sockets[i].fd, writeset)) {
952 len = write(sockets[i].fd,
953 buffer_ptr(&sockets[i].output),
954 buffer_len(&sockets[i].output));
955 if (len == -1 && (errno == EAGAIN ||
956 errno == EWOULDBLOCK ||
960 close_socket(&sockets[i]);
963 buffer_consume(&sockets[i].output, len);
965 if (FD_ISSET(sockets[i].fd, readset)) {
966 len = read(sockets[i].fd, buf, sizeof(buf));
967 if (len == -1 && (errno == EAGAIN ||
968 errno == EWOULDBLOCK ||
972 close_socket(&sockets[i]);
975 buffer_append(&sockets[i].input, buf, len);
976 process_message(&sockets[i]);
980 fatal("Unknown type %d", sockets[i].type);
1002 cleanup_handler(int sig)
1005 #ifdef ENABLE_PKCS11
1012 check_parent_exists(void)
1015 * If our parent has exited then getppid() will return (pid_t)1,
1016 * so testing for that should be safe.
1018 if (parent_pid != -1 && getppid() != parent_pid) {
1019 /* printf("Parent has died - Authentication agent exiting.\n"); */
1028 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1030 fprintf(stderr, "Options:\n");
1031 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1032 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1033 fprintf(stderr, " -k Kill the current agent.\n");
1034 fprintf(stderr, " -d Debug mode.\n");
1035 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1036 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1037 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1042 main(int ac, char **av)
1044 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1045 int sock, fd, ch, result, saved_errno;
1047 char *shell, *format, *pidstr, *agentsocket = NULL;
1048 fd_set *readsetp = NULL, *writesetp = NULL;
1049 struct sockaddr_un sunaddr;
1050 #ifdef HAVE_SETRLIMIT
1055 extern char *optarg;
1057 char pidstrbuf[1 + 3 * sizeof pid];
1058 struct timeval *tvp = NULL;
1061 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1069 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1070 /* Disable ptrace on Linux without sgid bit */
1071 prctl(PR_SET_DUMPABLE, 0);
1074 OpenSSL_add_all_algorithms();
1076 __progname = ssh_get_progname(av[0]);
1079 while ((ch = getopt(ac, av, "cdksa:t:x")) != -1) {
1100 agentsocket = optarg;
1103 if ((lifetime = convtime(optarg)) == -1) {
1104 fprintf(stderr, "Invalid lifetime\n");
1118 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1121 if (ac == 0 && !c_flag && !s_flag) {
1122 shell = getenv("SHELL");
1123 if (shell != NULL && (len = strlen(shell)) > 2 &&
1124 strncmp(shell + len - 3, "csh", 3) == 0)
1128 const char *errstr = NULL;
1130 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1131 if (pidstr == NULL) {
1132 fprintf(stderr, "%s not set, cannot kill agent\n",
1133 SSH_AGENTPID_ENV_NAME);
1136 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1139 "%s=\"%s\", which is not a good PID: %s\n",
1140 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1143 if (kill(pid, SIGTERM) == -1) {
1147 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1148 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1149 printf(format, SSH_AGENTPID_ENV_NAME);
1150 printf("echo Agent pid %ld killed;\n", (long)pid);
1153 parent_pid = getpid();
1155 if (agentsocket == NULL) {
1156 /* Create private directory for agent socket */
1157 mktemp_proto(socket_dir, sizeof(socket_dir));
1158 if (mkdtemp(socket_dir) == NULL) {
1159 perror("mkdtemp: private socket dir");
1162 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1165 /* Try to use specified agent socket */
1166 socket_dir[0] = '\0';
1167 strlcpy(socket_name, agentsocket, sizeof socket_name);
1171 * Create socket early so it will exist before command gets run from
1174 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1177 *socket_name = '\0'; /* Don't unlink any existing file */
1180 memset(&sunaddr, 0, sizeof(sunaddr));
1181 sunaddr.sun_family = AF_UNIX;
1182 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1183 prev_mask = umask(0177);
1184 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1186 *socket_name = '\0'; /* Don't unlink any existing file */
1191 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1197 * Fork, and have the parent execute the command, if any, or present
1198 * the socket data. The child continues as the authentication agent.
1201 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1202 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1203 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1204 SSH_AUTHSOCKET_ENV_NAME);
1205 printf("echo Agent pid %ld;\n", (long)parent_pid);
1213 if (pid != 0) { /* Parent - execute the given command. */
1215 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1217 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1218 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1219 SSH_AUTHSOCKET_ENV_NAME);
1220 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1221 SSH_AGENTPID_ENV_NAME);
1222 printf("echo Agent pid %ld;\n", (long)pid);
1225 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1226 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1235 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1237 if (setsid() == -1) {
1238 error("setsid: %s", strerror(errno));
1243 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1244 /* XXX might close listen socket */
1245 (void)dup2(fd, STDIN_FILENO);
1246 (void)dup2(fd, STDOUT_FILENO);
1247 (void)dup2(fd, STDERR_FILENO);
1252 #ifdef HAVE_SETRLIMIT
1253 /* deny core dumps, since memory contains unencrypted private keys */
1254 rlim.rlim_cur = rlim.rlim_max = 0;
1255 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1256 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1263 #ifdef ENABLE_PKCS11
1266 new_socket(AUTH_SOCKET, sock);
1268 parent_alive_interval = 10;
1270 signal(SIGPIPE, SIG_IGN);
1271 signal(SIGINT, d_flag ? cleanup_handler : 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);