1 /* $OpenBSD: ssh-agent.c,v 1.183 2014/02/02 03:44:31 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * The authentication agent program.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
52 #include "openbsd-compat/sys-queue.h"
54 #include <openssl/evp.h>
55 #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 /* pathname and directory for AUTH_SOCKET */
130 char socket_name[MAXPATHLEN];
131 char socket_dir[MAXPATHLEN];
135 char *lock_passwd = NULL;
137 extern char *__progname;
139 /* Default lifetime in seconds (0 == forever) */
140 static long lifetime = 0;
143 * Client connection count; incremented in new_socket() and decremented in
144 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
145 * normally initialized to 1, it will never reach 0. However, if the -x
146 * option is specified, it is initialized to 0 in main(); in that case,
147 * ssh-agent will exit as soon as it has had at least one client but no
150 static int xcount = 1;
153 close_socket(SocketEntry *e)
157 if (e->type == AUTH_CONNECTION) {
158 debug("xcount %d -> %d", xcount, xcount - 1);
164 e->type = AUTH_UNUSED;
165 buffer_free(&e->input);
166 buffer_free(&e->output);
167 buffer_free(&e->request);
177 for (i = 0; i <=2; i++) {
178 TAILQ_INIT(&idtable[i].idlist);
179 idtable[i].nentries = 0;
183 /* return private key table for requested protocol version */
185 idtab_lookup(int version)
187 if (version < 1 || version > 2)
188 fatal("internal error, bad protocol version %d", version);
189 return &idtable[version];
193 free_identity(Identity *id)
201 /* return matching private key for given public key */
203 lookup_identity(Key *key, int version)
207 Idtab *tab = idtab_lookup(version);
208 TAILQ_FOREACH(id, &tab->idlist, next) {
209 if (key_equal(key, id->key))
215 /* Check confirmation of keysign request */
217 confirm_key(Identity *id)
222 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
223 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
231 /* send list of supported public keys to 'client' */
233 process_request_identities(SocketEntry *e, int version)
235 Idtab *tab = idtab_lookup(version);
240 buffer_put_char(&msg, (version == 1) ?
241 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
242 buffer_put_int(&msg, tab->nentries);
243 TAILQ_FOREACH(id, &tab->idlist, next) {
244 if (id->key->type == KEY_RSA1) {
245 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
246 buffer_put_bignum(&msg, id->key->rsa->e);
247 buffer_put_bignum(&msg, id->key->rsa->n);
251 key_to_blob(id->key, &blob, &blen);
252 buffer_put_string(&msg, blob, blen);
255 buffer_put_cstring(&msg, id->comment);
257 buffer_put_int(&e->output, buffer_len(&msg));
258 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
264 process_authentication_challenge1(SocketEntry *e)
266 u_char buf[32], mdbuf[16], session_id[16];
272 struct ssh_digest_ctx *md;
276 key = key_new(KEY_RSA1);
277 if ((challenge = BN_new()) == NULL)
278 fatal("process_authentication_challenge1: BN_new failed");
280 (void) buffer_get_int(&e->request); /* ignored */
281 buffer_get_bignum(&e->request, key->rsa->e);
282 buffer_get_bignum(&e->request, key->rsa->n);
283 buffer_get_bignum(&e->request, challenge);
285 /* Only protocol 1.1 is supported */
286 if (buffer_len(&e->request) == 0)
288 buffer_get(&e->request, session_id, 16);
289 response_type = buffer_get_int(&e->request);
290 if (response_type != 1)
293 id = lookup_identity(key, 1);
294 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
295 Key *private = id->key;
296 /* Decrypt the challenge using the private key. */
297 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
300 /* The response is MD5 of decrypted challenge plus session id. */
301 len = BN_num_bytes(challenge);
302 if (len <= 0 || len > 32) {
303 logit("process_authentication_challenge: bad challenge length %d", len);
307 BN_bn2bin(challenge, buf + 32 - len);
308 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
309 ssh_digest_update(md, buf, 32) < 0 ||
310 ssh_digest_update(md, session_id, 16) < 0 ||
311 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
312 fatal("%s: md5 failed", __func__);
315 /* Send the response. */
316 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
317 for (i = 0; i < 16; i++)
318 buffer_put_char(&msg, mdbuf[i]);
323 /* Unknown identity or protocol error. Send failure. */
324 buffer_put_char(&msg, SSH_AGENT_FAILURE);
326 buffer_put_int(&e->output, buffer_len(&msg));
327 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
329 BN_clear_free(challenge);
335 process_sign_request2(SocketEntry *e)
337 u_char *blob, *data, *signature = NULL;
338 u_int blen, dlen, slen = 0;
339 extern int datafellows;
347 blob = buffer_get_string(&e->request, &blen);
348 data = buffer_get_string(&e->request, &dlen);
350 flags = buffer_get_int(&e->request);
351 odatafellows = datafellows;
352 if (flags & SSH_AGENT_OLD_SIGNATURE)
353 datafellows = SSH_BUG_SIGBLOB;
355 key = key_from_blob(blob, blen);
357 Identity *id = lookup_identity(key, 2);
358 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
359 ok = key_sign(id->key, &signature, &slen, data, dlen);
364 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
365 buffer_put_string(&msg, signature, slen);
367 buffer_put_char(&msg, SSH_AGENT_FAILURE);
369 buffer_put_int(&e->output, buffer_len(&msg));
370 buffer_append(&e->output, buffer_ptr(&msg),
376 datafellows = odatafellows;
381 process_remove_identity(SocketEntry *e, int version)
390 key = key_new(KEY_RSA1);
391 bits = buffer_get_int(&e->request);
392 buffer_get_bignum(&e->request, key->rsa->e);
393 buffer_get_bignum(&e->request, key->rsa->n);
395 if (bits != key_size(key))
396 logit("Warning: identity keysize mismatch: actual %u, announced %u",
397 key_size(key), bits);
400 blob = buffer_get_string(&e->request, &blen);
401 key = key_from_blob(blob, blen);
406 Identity *id = lookup_identity(key, version);
409 * We have this key. Free the old key. Since we
410 * don't want to leave empty slots in the middle of
411 * the array, we actually free the key there and move
412 * all the entries between the empty slot and the end
415 Idtab *tab = idtab_lookup(version);
416 if (tab->nentries < 1)
417 fatal("process_remove_identity: "
418 "internal error: tab->nentries %d",
420 TAILQ_REMOVE(&tab->idlist, id, next);
427 buffer_put_int(&e->output, 1);
428 buffer_put_char(&e->output,
429 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
433 process_remove_all_identities(SocketEntry *e, int version)
435 Idtab *tab = idtab_lookup(version);
438 /* Loop over all identities and clear the keys. */
439 for (id = TAILQ_FIRST(&tab->idlist); id;
440 id = TAILQ_FIRST(&tab->idlist)) {
441 TAILQ_REMOVE(&tab->idlist, id, next);
445 /* Mark that there are no identities. */
449 buffer_put_int(&e->output, 1);
450 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
453 /* removes expired keys and returns number of seconds until the next expiry */
457 time_t deadline = 0, now = monotime();
462 for (version = 1; version < 3; version++) {
463 tab = idtab_lookup(version);
464 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
465 nxt = TAILQ_NEXT(id, next);
468 if (now >= id->death) {
469 debug("expiring key '%s'", id->comment);
470 TAILQ_REMOVE(&tab->idlist, id, next);
474 deadline = (deadline == 0) ? id->death :
475 MIN(deadline, id->death);
478 if (deadline == 0 || deadline <= now)
481 return (deadline - now);
485 process_add_identity(SocketEntry *e, int version)
487 Idtab *tab = idtab_lookup(version);
489 int type, success = 0, confirm = 0;
496 k = key_new_private(KEY_RSA1);
497 (void) buffer_get_int(&e->request); /* ignored */
498 buffer_get_bignum(&e->request, k->rsa->n);
499 buffer_get_bignum(&e->request, k->rsa->e);
500 buffer_get_bignum(&e->request, k->rsa->d);
501 buffer_get_bignum(&e->request, k->rsa->iqmp);
503 /* SSH and SSL have p and q swapped */
504 buffer_get_bignum(&e->request, k->rsa->q); /* p */
505 buffer_get_bignum(&e->request, k->rsa->p); /* q */
507 /* Generate additional parameters */
508 rsa_generate_additional_parameters(k->rsa);
510 /* enable blinding */
511 if (RSA_blinding_on(k->rsa, NULL) != 1) {
512 error("process_add_identity: RSA_blinding_on failed");
518 k = key_private_deserialize(&e->request);
520 buffer_clear(&e->request);
525 comment = buffer_get_string(&e->request, NULL);
530 while (buffer_len(&e->request)) {
531 switch ((type = buffer_get_char(&e->request))) {
532 case SSH_AGENT_CONSTRAIN_LIFETIME:
533 death = monotime() + buffer_get_int(&e->request);
535 case SSH_AGENT_CONSTRAIN_CONFIRM:
539 error("process_add_identity: "
540 "Unknown constraint type %d", type);
547 if (lifetime && !death)
548 death = monotime() + lifetime;
549 if ((id = lookup_identity(k, version)) == NULL) {
550 id = xcalloc(1, sizeof(Identity));
552 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
553 /* Increment the number of identities. */
559 id->comment = comment;
561 id->confirm = confirm;
563 buffer_put_int(&e->output, 1);
564 buffer_put_char(&e->output,
565 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
568 /* XXX todo: encrypt sensitive data with passphrase */
570 process_lock_agent(SocketEntry *e, int lock)
575 passwd = buffer_get_string(&e->request, NULL);
576 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
578 explicit_bzero(lock_passwd, strlen(lock_passwd));
582 } else if (!locked && lock) {
584 lock_passwd = xstrdup(passwd);
587 explicit_bzero(passwd, strlen(passwd));
590 buffer_put_int(&e->output, 1);
591 buffer_put_char(&e->output,
592 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
596 no_identities(SocketEntry *e, u_int type)
601 buffer_put_char(&msg,
602 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
603 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
604 buffer_put_int(&msg, 0);
605 buffer_put_int(&e->output, buffer_len(&msg));
606 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
612 process_add_smartcard_key(SocketEntry *e)
614 char *provider = NULL, *pin;
615 int i, type, version, count = 0, success = 0, confirm = 0;
617 Key **keys = NULL, *k;
621 provider = buffer_get_string(&e->request, NULL);
622 pin = buffer_get_string(&e->request, NULL);
624 while (buffer_len(&e->request)) {
625 switch ((type = buffer_get_char(&e->request))) {
626 case SSH_AGENT_CONSTRAIN_LIFETIME:
627 death = monotime() + buffer_get_int(&e->request);
629 case SSH_AGENT_CONSTRAIN_CONFIRM:
633 error("process_add_smartcard_key: "
634 "Unknown constraint type %d", type);
638 if (lifetime && !death)
639 death = monotime() + lifetime;
641 count = pkcs11_add_provider(provider, pin, &keys);
642 for (i = 0; i < count; i++) {
644 version = k->type == KEY_RSA1 ? 1 : 2;
645 tab = idtab_lookup(version);
646 if (lookup_identity(k, version) == NULL) {
647 id = xcalloc(1, sizeof(Identity));
649 id->provider = xstrdup(provider);
650 id->comment = xstrdup(provider); /* XXX */
652 id->confirm = confirm;
653 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
665 buffer_put_int(&e->output, 1);
666 buffer_put_char(&e->output,
667 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
671 process_remove_smartcard_key(SocketEntry *e)
673 char *provider = NULL, *pin = NULL;
674 int version, success = 0;
678 provider = buffer_get_string(&e->request, NULL);
679 pin = buffer_get_string(&e->request, NULL);
682 for (version = 1; version < 3; version++) {
683 tab = idtab_lookup(version);
684 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
685 nxt = TAILQ_NEXT(id, next);
686 /* Skip file--based keys */
687 if (id->provider == NULL)
689 if (!strcmp(provider, id->provider)) {
690 TAILQ_REMOVE(&tab->idlist, id, next);
696 if (pkcs11_del_provider(provider) == 0)
699 error("process_remove_smartcard_key:"
700 " pkcs11_del_provider failed");
702 buffer_put_int(&e->output, 1);
703 buffer_put_char(&e->output,
704 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
706 #endif /* ENABLE_PKCS11 */
708 /* dispatch incoming messages */
711 process_message(SocketEntry *e)
716 if (buffer_len(&e->input) < 5)
717 return; /* Incomplete message. */
718 cp = buffer_ptr(&e->input);
719 msg_len = get_u32(cp);
720 if (msg_len > 256 * 1024) {
724 if (buffer_len(&e->input) < msg_len + 4)
727 /* move the current input to e->request */
728 buffer_consume(&e->input, 4);
729 buffer_clear(&e->request);
730 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
731 buffer_consume(&e->input, msg_len);
732 type = buffer_get_char(&e->request);
734 /* check wheter agent is locked */
735 if (locked && type != SSH_AGENTC_UNLOCK) {
736 buffer_clear(&e->request);
738 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
739 case SSH2_AGENTC_REQUEST_IDENTITIES:
740 /* send empty lists */
741 no_identities(e, type);
744 /* send a fail message for all other request types */
745 buffer_put_int(&e->output, 1);
746 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
751 debug("type %d", type);
753 case SSH_AGENTC_LOCK:
754 case SSH_AGENTC_UNLOCK:
755 process_lock_agent(e, type == SSH_AGENTC_LOCK);
758 case SSH_AGENTC_RSA_CHALLENGE:
759 process_authentication_challenge1(e);
761 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
762 process_request_identities(e, 1);
764 case SSH_AGENTC_ADD_RSA_IDENTITY:
765 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
766 process_add_identity(e, 1);
768 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
769 process_remove_identity(e, 1);
771 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
772 process_remove_all_identities(e, 1);
775 case SSH2_AGENTC_SIGN_REQUEST:
776 process_sign_request2(e);
778 case SSH2_AGENTC_REQUEST_IDENTITIES:
779 process_request_identities(e, 2);
781 case SSH2_AGENTC_ADD_IDENTITY:
782 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
783 process_add_identity(e, 2);
785 case SSH2_AGENTC_REMOVE_IDENTITY:
786 process_remove_identity(e, 2);
788 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
789 process_remove_all_identities(e, 2);
792 case SSH_AGENTC_ADD_SMARTCARD_KEY:
793 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
794 process_add_smartcard_key(e);
796 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
797 process_remove_smartcard_key(e);
799 #endif /* ENABLE_PKCS11 */
801 /* Unknown message. Respond with failure. */
802 error("Unknown message %d", type);
803 buffer_clear(&e->request);
804 buffer_put_int(&e->output, 1);
805 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
811 new_socket(sock_type type, int fd)
813 u_int i, old_alloc, new_alloc;
815 if (type == AUTH_CONNECTION) {
816 debug("xcount %d -> %d", xcount, xcount + 1);
824 for (i = 0; i < sockets_alloc; i++)
825 if (sockets[i].type == AUTH_UNUSED) {
827 buffer_init(&sockets[i].input);
828 buffer_init(&sockets[i].output);
829 buffer_init(&sockets[i].request);
830 sockets[i].type = type;
833 old_alloc = sockets_alloc;
834 new_alloc = sockets_alloc + 10;
835 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
836 for (i = old_alloc; i < new_alloc; i++)
837 sockets[i].type = AUTH_UNUSED;
838 sockets_alloc = new_alloc;
839 sockets[old_alloc].fd = fd;
840 buffer_init(&sockets[old_alloc].input);
841 buffer_init(&sockets[old_alloc].output);
842 buffer_init(&sockets[old_alloc].request);
843 sockets[old_alloc].type = type;
847 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
848 struct timeval **tvpp)
852 static struct timeval tv;
855 for (i = 0; i < sockets_alloc; i++) {
856 switch (sockets[i].type) {
858 case AUTH_CONNECTION:
859 n = MAX(n, sockets[i].fd);
864 fatal("Unknown socket type %d", sockets[i].type);
869 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
870 if (*fdrp == NULL || sz > *nallocp) {
878 debug("XXX shrink: %d < %d", n, *fdl);
880 memset(*fdrp, 0, sz);
881 memset(*fdwp, 0, sz);
883 for (i = 0; i < sockets_alloc; i++) {
884 switch (sockets[i].type) {
886 case AUTH_CONNECTION:
887 FD_SET(sockets[i].fd, *fdrp);
888 if (buffer_len(&sockets[i].output) > 0)
889 FD_SET(sockets[i].fd, *fdwp);
896 if (parent_alive_interval != 0)
897 deadline = (deadline == 0) ? parent_alive_interval :
898 MIN(deadline, parent_alive_interval);
902 tv.tv_sec = deadline;
910 after_select(fd_set *readset, fd_set *writeset)
912 struct sockaddr_un sunaddr;
920 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
921 switch (sockets[i].type) {
925 if (FD_ISSET(sockets[i].fd, readset)) {
926 slen = sizeof(sunaddr);
927 sock = accept(sockets[i].fd,
928 (struct sockaddr *)&sunaddr, &slen);
930 error("accept from AUTH_SOCKET: %s",
934 if (getpeereid(sock, &euid, &egid) < 0) {
935 error("getpeereid %d failed: %s",
936 sock, strerror(errno));
940 if ((euid != 0) && (getuid() != euid)) {
941 error("uid mismatch: "
942 "peer euid %u != uid %u",
943 (u_int) euid, (u_int) getuid());
947 new_socket(AUTH_CONNECTION, sock);
950 case AUTH_CONNECTION:
951 if (buffer_len(&sockets[i].output) > 0 &&
952 FD_ISSET(sockets[i].fd, writeset)) {
953 len = write(sockets[i].fd,
954 buffer_ptr(&sockets[i].output),
955 buffer_len(&sockets[i].output));
956 if (len == -1 && (errno == EAGAIN ||
957 errno == EWOULDBLOCK ||
961 close_socket(&sockets[i]);
964 buffer_consume(&sockets[i].output, len);
966 if (FD_ISSET(sockets[i].fd, readset)) {
967 len = read(sockets[i].fd, buf, sizeof(buf));
968 if (len == -1 && (errno == EAGAIN ||
969 errno == EWOULDBLOCK ||
973 close_socket(&sockets[i]);
976 buffer_append(&sockets[i].input, buf, len);
977 process_message(&sockets[i]);
981 fatal("Unknown type %d", sockets[i].type);
1003 cleanup_handler(int sig)
1006 #ifdef ENABLE_PKCS11
1013 check_parent_exists(void)
1016 * If our parent has exited then getppid() will return (pid_t)1,
1017 * so testing for that should be safe.
1019 if (parent_pid != -1 && getppid() != parent_pid) {
1020 /* printf("Parent has died - Authentication agent exiting.\n"); */
1029 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1031 fprintf(stderr, "Options:\n");
1032 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1033 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1034 fprintf(stderr, " -k Kill the current agent.\n");
1035 fprintf(stderr, " -d Debug mode.\n");
1036 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1037 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1038 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1043 main(int ac, char **av)
1045 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1046 int sock, fd, ch, result, saved_errno;
1048 char *shell, *format, *pidstr, *agentsocket = NULL;
1049 fd_set *readsetp = NULL, *writesetp = NULL;
1050 struct sockaddr_un sunaddr;
1051 #ifdef HAVE_SETRLIMIT
1056 extern char *optarg;
1058 char pidstrbuf[1 + 3 * sizeof pid];
1059 struct timeval *tvp = NULL;
1062 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1070 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1071 /* Disable ptrace on Linux without sgid bit */
1072 prctl(PR_SET_DUMPABLE, 0);
1075 OpenSSL_add_all_algorithms();
1077 __progname = ssh_get_progname(av[0]);
1080 while ((ch = getopt(ac, av, "cdksa:t:x")) != -1) {
1101 agentsocket = optarg;
1104 if ((lifetime = convtime(optarg)) == -1) {
1105 fprintf(stderr, "Invalid lifetime\n");
1119 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1122 if (ac == 0 && !c_flag && !s_flag) {
1123 shell = getenv("SHELL");
1124 if (shell != NULL && (len = strlen(shell)) > 2 &&
1125 strncmp(shell + len - 3, "csh", 3) == 0)
1129 const char *errstr = NULL;
1131 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1132 if (pidstr == NULL) {
1133 fprintf(stderr, "%s not set, cannot kill agent\n",
1134 SSH_AGENTPID_ENV_NAME);
1137 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1140 "%s=\"%s\", which is not a good PID: %s\n",
1141 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1144 if (kill(pid, SIGTERM) == -1) {
1148 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1149 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1150 printf(format, SSH_AGENTPID_ENV_NAME);
1151 printf("echo Agent pid %ld killed;\n", (long)pid);
1154 parent_pid = getpid();
1156 if (agentsocket == NULL) {
1157 /* Create private directory for agent socket */
1158 mktemp_proto(socket_dir, sizeof(socket_dir));
1159 if (mkdtemp(socket_dir) == NULL) {
1160 perror("mkdtemp: private socket dir");
1163 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1166 /* Try to use specified agent socket */
1167 socket_dir[0] = '\0';
1168 strlcpy(socket_name, agentsocket, sizeof socket_name);
1172 * Create socket early so it will exist before command gets run from
1175 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1178 *socket_name = '\0'; /* Don't unlink any existing file */
1181 memset(&sunaddr, 0, sizeof(sunaddr));
1182 sunaddr.sun_family = AF_UNIX;
1183 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1184 prev_mask = umask(0177);
1185 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1187 *socket_name = '\0'; /* Don't unlink any existing file */
1192 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1198 * Fork, and have the parent execute the command, if any, or present
1199 * the socket data. The child continues as the authentication agent.
1202 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1203 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1204 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1205 SSH_AUTHSOCKET_ENV_NAME);
1206 printf("echo Agent pid %ld;\n", (long)parent_pid);
1214 if (pid != 0) { /* Parent - execute the given command. */
1216 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1218 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1219 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1220 SSH_AUTHSOCKET_ENV_NAME);
1221 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1222 SSH_AGENTPID_ENV_NAME);
1223 printf("echo Agent pid %ld;\n", (long)pid);
1226 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1227 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1236 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1238 if (setsid() == -1) {
1239 error("setsid: %s", strerror(errno));
1244 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1245 /* XXX might close listen socket */
1246 (void)dup2(fd, STDIN_FILENO);
1247 (void)dup2(fd, STDOUT_FILENO);
1248 (void)dup2(fd, STDERR_FILENO);
1253 #ifdef HAVE_SETRLIMIT
1254 /* deny core dumps, since memory contains unencrypted private keys */
1255 rlim.rlim_cur = rlim.rlim_max = 0;
1256 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1257 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1264 #ifdef ENABLE_PKCS11
1267 new_socket(AUTH_SOCKET, sock);
1269 parent_alive_interval = 10;
1271 signal(SIGPIPE, SIG_IGN);
1272 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1273 signal(SIGHUP, cleanup_handler);
1274 signal(SIGTERM, cleanup_handler);
1278 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1279 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1280 saved_errno = errno;
1281 if (parent_alive_interval != 0)
1282 check_parent_exists();
1283 (void) reaper(); /* remove expired keys */
1285 if (saved_errno == EINTR)
1287 fatal("select: %s", strerror(saved_errno));
1288 } else if (result > 0)
1289 after_select(readsetp, writesetp);