1 /* $OpenBSD: ssh-agent.c,v 1.181 2013/12/19 01:19:41 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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 <openssl/md5.h>
54 #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];
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);
288 MD5_Update(&md, buf, 32);
289 MD5_Update(&md, session_id, 16);
290 MD5_Final(mdbuf, &md);
292 /* Send the response. */
293 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
294 for (i = 0; i < 16; i++)
295 buffer_put_char(&msg, mdbuf[i]);
300 /* Unknown identity or protocol error. Send failure. */
301 buffer_put_char(&msg, SSH_AGENT_FAILURE);
303 buffer_put_int(&e->output, buffer_len(&msg));
304 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
306 BN_clear_free(challenge);
312 process_sign_request2(SocketEntry *e)
314 u_char *blob, *data, *signature = NULL;
315 u_int blen, dlen, slen = 0;
316 extern int datafellows;
324 blob = buffer_get_string(&e->request, &blen);
325 data = buffer_get_string(&e->request, &dlen);
327 flags = buffer_get_int(&e->request);
328 odatafellows = datafellows;
329 if (flags & SSH_AGENT_OLD_SIGNATURE)
330 datafellows = SSH_BUG_SIGBLOB;
332 key = key_from_blob(blob, blen);
334 Identity *id = lookup_identity(key, 2);
335 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
336 ok = key_sign(id->key, &signature, &slen, data, dlen);
341 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
342 buffer_put_string(&msg, signature, slen);
344 buffer_put_char(&msg, SSH_AGENT_FAILURE);
346 buffer_put_int(&e->output, buffer_len(&msg));
347 buffer_append(&e->output, buffer_ptr(&msg),
353 datafellows = odatafellows;
358 process_remove_identity(SocketEntry *e, int version)
367 key = key_new(KEY_RSA1);
368 bits = buffer_get_int(&e->request);
369 buffer_get_bignum(&e->request, key->rsa->e);
370 buffer_get_bignum(&e->request, key->rsa->n);
372 if (bits != key_size(key))
373 logit("Warning: identity keysize mismatch: actual %u, announced %u",
374 key_size(key), bits);
377 blob = buffer_get_string(&e->request, &blen);
378 key = key_from_blob(blob, blen);
383 Identity *id = lookup_identity(key, version);
386 * We have this key. Free the old key. Since we
387 * don't want to leave empty slots in the middle of
388 * the array, we actually free the key there and move
389 * all the entries between the empty slot and the end
392 Idtab *tab = idtab_lookup(version);
393 if (tab->nentries < 1)
394 fatal("process_remove_identity: "
395 "internal error: tab->nentries %d",
397 TAILQ_REMOVE(&tab->idlist, id, next);
404 buffer_put_int(&e->output, 1);
405 buffer_put_char(&e->output,
406 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
410 process_remove_all_identities(SocketEntry *e, int version)
412 Idtab *tab = idtab_lookup(version);
415 /* Loop over all identities and clear the keys. */
416 for (id = TAILQ_FIRST(&tab->idlist); id;
417 id = TAILQ_FIRST(&tab->idlist)) {
418 TAILQ_REMOVE(&tab->idlist, id, next);
422 /* Mark that there are no identities. */
426 buffer_put_int(&e->output, 1);
427 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
430 /* removes expired keys and returns number of seconds until the next expiry */
434 time_t deadline = 0, now = monotime();
439 for (version = 1; version < 3; version++) {
440 tab = idtab_lookup(version);
441 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
442 nxt = TAILQ_NEXT(id, next);
445 if (now >= id->death) {
446 debug("expiring key '%s'", id->comment);
447 TAILQ_REMOVE(&tab->idlist, id, next);
451 deadline = (deadline == 0) ? id->death :
452 MIN(deadline, id->death);
455 if (deadline == 0 || deadline <= now)
458 return (deadline - now);
462 process_add_identity(SocketEntry *e, int version)
464 Idtab *tab = idtab_lookup(version);
466 int type, success = 0, confirm = 0;
473 k = key_new_private(KEY_RSA1);
474 (void) buffer_get_int(&e->request); /* ignored */
475 buffer_get_bignum(&e->request, k->rsa->n);
476 buffer_get_bignum(&e->request, k->rsa->e);
477 buffer_get_bignum(&e->request, k->rsa->d);
478 buffer_get_bignum(&e->request, k->rsa->iqmp);
480 /* SSH and SSL have p and q swapped */
481 buffer_get_bignum(&e->request, k->rsa->q); /* p */
482 buffer_get_bignum(&e->request, k->rsa->p); /* q */
484 /* Generate additional parameters */
485 rsa_generate_additional_parameters(k->rsa);
487 /* enable blinding */
488 if (RSA_blinding_on(k->rsa, NULL) != 1) {
489 error("process_add_identity: RSA_blinding_on failed");
495 k = key_private_deserialize(&e->request);
497 buffer_clear(&e->request);
502 comment = buffer_get_string(&e->request, NULL);
507 while (buffer_len(&e->request)) {
508 switch ((type = buffer_get_char(&e->request))) {
509 case SSH_AGENT_CONSTRAIN_LIFETIME:
510 death = monotime() + buffer_get_int(&e->request);
512 case SSH_AGENT_CONSTRAIN_CONFIRM:
516 error("process_add_identity: "
517 "Unknown constraint type %d", type);
524 if (lifetime && !death)
525 death = monotime() + lifetime;
526 if ((id = lookup_identity(k, version)) == NULL) {
527 id = xcalloc(1, sizeof(Identity));
529 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
530 /* Increment the number of identities. */
536 id->comment = comment;
538 id->confirm = confirm;
540 buffer_put_int(&e->output, 1);
541 buffer_put_char(&e->output,
542 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
545 /* XXX todo: encrypt sensitive data with passphrase */
547 process_lock_agent(SocketEntry *e, int lock)
552 passwd = buffer_get_string(&e->request, NULL);
553 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
555 memset(lock_passwd, 0, strlen(lock_passwd));
559 } else if (!locked && lock) {
561 lock_passwd = xstrdup(passwd);
564 memset(passwd, 0, strlen(passwd));
567 buffer_put_int(&e->output, 1);
568 buffer_put_char(&e->output,
569 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
573 no_identities(SocketEntry *e, u_int type)
578 buffer_put_char(&msg,
579 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
580 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
581 buffer_put_int(&msg, 0);
582 buffer_put_int(&e->output, buffer_len(&msg));
583 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
589 process_add_smartcard_key(SocketEntry *e)
591 char *provider = NULL, *pin;
592 int i, type, version, count = 0, success = 0, confirm = 0;
594 Key **keys = NULL, *k;
598 provider = buffer_get_string(&e->request, NULL);
599 pin = buffer_get_string(&e->request, NULL);
601 while (buffer_len(&e->request)) {
602 switch ((type = buffer_get_char(&e->request))) {
603 case SSH_AGENT_CONSTRAIN_LIFETIME:
604 death = monotime() + buffer_get_int(&e->request);
606 case SSH_AGENT_CONSTRAIN_CONFIRM:
610 error("process_add_smartcard_key: "
611 "Unknown constraint type %d", type);
615 if (lifetime && !death)
616 death = monotime() + lifetime;
618 count = pkcs11_add_provider(provider, pin, &keys);
619 for (i = 0; i < count; i++) {
621 version = k->type == KEY_RSA1 ? 1 : 2;
622 tab = idtab_lookup(version);
623 if (lookup_identity(k, version) == NULL) {
624 id = xcalloc(1, sizeof(Identity));
626 id->provider = xstrdup(provider);
627 id->comment = xstrdup(provider); /* XXX */
629 id->confirm = confirm;
630 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
642 buffer_put_int(&e->output, 1);
643 buffer_put_char(&e->output,
644 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
648 process_remove_smartcard_key(SocketEntry *e)
650 char *provider = NULL, *pin = NULL;
651 int version, success = 0;
655 provider = buffer_get_string(&e->request, NULL);
656 pin = buffer_get_string(&e->request, NULL);
659 for (version = 1; version < 3; version++) {
660 tab = idtab_lookup(version);
661 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
662 nxt = TAILQ_NEXT(id, next);
663 /* Skip file--based keys */
664 if (id->provider == NULL)
666 if (!strcmp(provider, id->provider)) {
667 TAILQ_REMOVE(&tab->idlist, id, next);
673 if (pkcs11_del_provider(provider) == 0)
676 error("process_remove_smartcard_key:"
677 " pkcs11_del_provider failed");
679 buffer_put_int(&e->output, 1);
680 buffer_put_char(&e->output,
681 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
683 #endif /* ENABLE_PKCS11 */
685 /* dispatch incoming messages */
688 process_message(SocketEntry *e)
693 if (buffer_len(&e->input) < 5)
694 return; /* Incomplete message. */
695 cp = buffer_ptr(&e->input);
696 msg_len = get_u32(cp);
697 if (msg_len > 256 * 1024) {
701 if (buffer_len(&e->input) < msg_len + 4)
704 /* move the current input to e->request */
705 buffer_consume(&e->input, 4);
706 buffer_clear(&e->request);
707 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
708 buffer_consume(&e->input, msg_len);
709 type = buffer_get_char(&e->request);
711 /* check wheter agent is locked */
712 if (locked && type != SSH_AGENTC_UNLOCK) {
713 buffer_clear(&e->request);
715 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
716 case SSH2_AGENTC_REQUEST_IDENTITIES:
717 /* send empty lists */
718 no_identities(e, type);
721 /* send a fail message for all other request types */
722 buffer_put_int(&e->output, 1);
723 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
728 debug("type %d", type);
730 case SSH_AGENTC_LOCK:
731 case SSH_AGENTC_UNLOCK:
732 process_lock_agent(e, type == SSH_AGENTC_LOCK);
735 case SSH_AGENTC_RSA_CHALLENGE:
736 process_authentication_challenge1(e);
738 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
739 process_request_identities(e, 1);
741 case SSH_AGENTC_ADD_RSA_IDENTITY:
742 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
743 process_add_identity(e, 1);
745 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
746 process_remove_identity(e, 1);
748 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
749 process_remove_all_identities(e, 1);
752 case SSH2_AGENTC_SIGN_REQUEST:
753 process_sign_request2(e);
755 case SSH2_AGENTC_REQUEST_IDENTITIES:
756 process_request_identities(e, 2);
758 case SSH2_AGENTC_ADD_IDENTITY:
759 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
760 process_add_identity(e, 2);
762 case SSH2_AGENTC_REMOVE_IDENTITY:
763 process_remove_identity(e, 2);
765 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
766 process_remove_all_identities(e, 2);
769 case SSH_AGENTC_ADD_SMARTCARD_KEY:
770 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
771 process_add_smartcard_key(e);
773 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
774 process_remove_smartcard_key(e);
776 #endif /* ENABLE_PKCS11 */
778 /* Unknown message. Respond with failure. */
779 error("Unknown message %d", type);
780 buffer_clear(&e->request);
781 buffer_put_int(&e->output, 1);
782 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
788 new_socket(sock_type type, int fd)
790 u_int i, old_alloc, new_alloc;
797 for (i = 0; i < sockets_alloc; i++)
798 if (sockets[i].type == AUTH_UNUSED) {
800 buffer_init(&sockets[i].input);
801 buffer_init(&sockets[i].output);
802 buffer_init(&sockets[i].request);
803 sockets[i].type = type;
806 old_alloc = sockets_alloc;
807 new_alloc = sockets_alloc + 10;
808 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
809 for (i = old_alloc; i < new_alloc; i++)
810 sockets[i].type = AUTH_UNUSED;
811 sockets_alloc = new_alloc;
812 sockets[old_alloc].fd = fd;
813 buffer_init(&sockets[old_alloc].input);
814 buffer_init(&sockets[old_alloc].output);
815 buffer_init(&sockets[old_alloc].request);
816 sockets[old_alloc].type = type;
820 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
821 struct timeval **tvpp)
825 static struct timeval tv;
828 for (i = 0; i < sockets_alloc; i++) {
829 switch (sockets[i].type) {
831 case AUTH_CONNECTION:
832 n = MAX(n, sockets[i].fd);
837 fatal("Unknown socket type %d", sockets[i].type);
842 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
843 if (*fdrp == NULL || sz > *nallocp) {
851 debug("XXX shrink: %d < %d", n, *fdl);
853 memset(*fdrp, 0, sz);
854 memset(*fdwp, 0, sz);
856 for (i = 0; i < sockets_alloc; i++) {
857 switch (sockets[i].type) {
859 case AUTH_CONNECTION:
860 FD_SET(sockets[i].fd, *fdrp);
861 if (buffer_len(&sockets[i].output) > 0)
862 FD_SET(sockets[i].fd, *fdwp);
869 if (parent_alive_interval != 0)
870 deadline = (deadline == 0) ? parent_alive_interval :
871 MIN(deadline, parent_alive_interval);
875 tv.tv_sec = deadline;
883 after_select(fd_set *readset, fd_set *writeset)
885 struct sockaddr_un sunaddr;
893 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
894 switch (sockets[i].type) {
898 if (FD_ISSET(sockets[i].fd, readset)) {
899 slen = sizeof(sunaddr);
900 sock = accept(sockets[i].fd,
901 (struct sockaddr *)&sunaddr, &slen);
903 error("accept from AUTH_SOCKET: %s",
907 if (getpeereid(sock, &euid, &egid) < 0) {
908 error("getpeereid %d failed: %s",
909 sock, strerror(errno));
913 if ((euid != 0) && (getuid() != euid)) {
914 error("uid mismatch: "
915 "peer euid %u != uid %u",
916 (u_int) euid, (u_int) getuid());
920 new_socket(AUTH_CONNECTION, sock);
923 case AUTH_CONNECTION:
924 if (buffer_len(&sockets[i].output) > 0 &&
925 FD_ISSET(sockets[i].fd, writeset)) {
926 len = write(sockets[i].fd,
927 buffer_ptr(&sockets[i].output),
928 buffer_len(&sockets[i].output));
929 if (len == -1 && (errno == EAGAIN ||
930 errno == EWOULDBLOCK ||
934 close_socket(&sockets[i]);
937 buffer_consume(&sockets[i].output, len);
939 if (FD_ISSET(sockets[i].fd, readset)) {
940 len = read(sockets[i].fd, buf, sizeof(buf));
941 if (len == -1 && (errno == EAGAIN ||
942 errno == EWOULDBLOCK ||
946 close_socket(&sockets[i]);
949 buffer_append(&sockets[i].input, buf, len);
950 process_message(&sockets[i]);
954 fatal("Unknown type %d", sockets[i].type);
976 cleanup_handler(int sig)
986 check_parent_exists(void)
989 * If our parent has exited then getppid() will return (pid_t)1,
990 * so testing for that should be safe.
992 if (parent_pid != -1 && getppid() != parent_pid) {
993 /* printf("Parent has died - Authentication agent exiting.\n"); */
1002 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1004 fprintf(stderr, "Options:\n");
1005 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1006 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1007 fprintf(stderr, " -k Kill the current agent.\n");
1008 fprintf(stderr, " -d Debug mode.\n");
1009 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1010 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1015 main(int ac, char **av)
1017 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1018 int sock, fd, ch, result, saved_errno;
1020 char *shell, *format, *pidstr, *agentsocket = NULL;
1021 fd_set *readsetp = NULL, *writesetp = NULL;
1022 struct sockaddr_un sunaddr;
1023 #ifdef HAVE_SETRLIMIT
1028 extern char *optarg;
1030 char pidstrbuf[1 + 3 * sizeof pid];
1031 struct timeval *tvp = NULL;
1034 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1041 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1042 /* Disable ptrace on Linux without sgid bit */
1043 prctl(PR_SET_DUMPABLE, 0);
1046 OpenSSL_add_all_algorithms();
1048 __progname = ssh_get_progname(av[0]);
1051 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1072 agentsocket = optarg;
1075 if ((lifetime = convtime(optarg)) == -1) {
1076 fprintf(stderr, "Invalid lifetime\n");
1087 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1090 if (ac == 0 && !c_flag && !s_flag) {
1091 shell = getenv("SHELL");
1092 if (shell != NULL && (len = strlen(shell)) > 2 &&
1093 strncmp(shell + len - 3, "csh", 3) == 0)
1097 const char *errstr = NULL;
1099 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1100 if (pidstr == NULL) {
1101 fprintf(stderr, "%s not set, cannot kill agent\n",
1102 SSH_AGENTPID_ENV_NAME);
1105 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1108 "%s=\"%s\", which is not a good PID: %s\n",
1109 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1112 if (kill(pid, SIGTERM) == -1) {
1116 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1117 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1118 printf(format, SSH_AGENTPID_ENV_NAME);
1119 printf("echo Agent pid %ld killed;\n", (long)pid);
1122 parent_pid = getpid();
1124 if (agentsocket == NULL) {
1125 /* Create private directory for agent socket */
1126 mktemp_proto(socket_dir, sizeof(socket_dir));
1127 if (mkdtemp(socket_dir) == NULL) {
1128 perror("mkdtemp: private socket dir");
1131 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1134 /* Try to use specified agent socket */
1135 socket_dir[0] = '\0';
1136 strlcpy(socket_name, agentsocket, sizeof socket_name);
1140 * Create socket early so it will exist before command gets run from
1143 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1146 *socket_name = '\0'; /* Don't unlink any existing file */
1149 memset(&sunaddr, 0, sizeof(sunaddr));
1150 sunaddr.sun_family = AF_UNIX;
1151 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1152 prev_mask = umask(0177);
1153 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1155 *socket_name = '\0'; /* Don't unlink any existing file */
1160 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1166 * Fork, and have the parent execute the command, if any, or present
1167 * the socket data. The child continues as the authentication agent.
1170 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1171 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1172 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1173 SSH_AUTHSOCKET_ENV_NAME);
1174 printf("echo Agent pid %ld;\n", (long)parent_pid);
1182 if (pid != 0) { /* Parent - execute the given command. */
1184 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1186 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1187 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1188 SSH_AUTHSOCKET_ENV_NAME);
1189 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1190 SSH_AGENTPID_ENV_NAME);
1191 printf("echo Agent pid %ld;\n", (long)pid);
1194 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1195 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1204 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1206 if (setsid() == -1) {
1207 error("setsid: %s", strerror(errno));
1212 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1213 /* XXX might close listen socket */
1214 (void)dup2(fd, STDIN_FILENO);
1215 (void)dup2(fd, STDOUT_FILENO);
1216 (void)dup2(fd, STDERR_FILENO);
1221 #ifdef HAVE_SETRLIMIT
1222 /* deny core dumps, since memory contains unencrypted private keys */
1223 rlim.rlim_cur = rlim.rlim_max = 0;
1224 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1225 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1232 #ifdef ENABLE_PKCS11
1235 new_socket(AUTH_SOCKET, sock);
1237 parent_alive_interval = 10;
1239 signal(SIGPIPE, SIG_IGN);
1240 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1241 signal(SIGHUP, cleanup_handler);
1242 signal(SIGTERM, cleanup_handler);
1246 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1247 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1248 saved_errno = errno;
1249 if (parent_alive_interval != 0)
1250 check_parent_exists();
1251 (void) reaper(); /* remove expired keys */
1253 if (saved_errno == EINTR)
1255 fatal("select: %s", strerror(saved_errno));
1256 } else if (result > 0)
1257 after_select(readsetp, writesetp);