1 /* $OpenBSD: ssh-agent.c,v 1.165 2010/02/26 20:29:54 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 u_int 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 (0 == forever) */
138 static int 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)
175 if (id->provider != NULL)
181 /* return matching private key for given public key */
183 lookup_identity(Key *key, int version)
187 Idtab *tab = idtab_lookup(version);
188 TAILQ_FOREACH(id, &tab->idlist, next) {
189 if (key_equal(key, id->key))
195 /* Check confirmation of keysign request */
197 confirm_key(Identity *id)
202 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
203 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
211 /* send list of supported public keys to 'client' */
213 process_request_identities(SocketEntry *e, int version)
215 Idtab *tab = idtab_lookup(version);
220 buffer_put_char(&msg, (version == 1) ?
221 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
222 buffer_put_int(&msg, tab->nentries);
223 TAILQ_FOREACH(id, &tab->idlist, next) {
224 if (id->key->type == KEY_RSA1) {
225 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
226 buffer_put_bignum(&msg, id->key->rsa->e);
227 buffer_put_bignum(&msg, id->key->rsa->n);
231 key_to_blob(id->key, &blob, &blen);
232 buffer_put_string(&msg, blob, blen);
235 buffer_put_cstring(&msg, id->comment);
237 buffer_put_int(&e->output, buffer_len(&msg));
238 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
244 process_authentication_challenge1(SocketEntry *e)
246 u_char buf[32], mdbuf[16], session_id[16];
256 key = key_new(KEY_RSA1);
257 if ((challenge = BN_new()) == NULL)
258 fatal("process_authentication_challenge1: BN_new failed");
260 (void) buffer_get_int(&e->request); /* ignored */
261 buffer_get_bignum(&e->request, key->rsa->e);
262 buffer_get_bignum(&e->request, key->rsa->n);
263 buffer_get_bignum(&e->request, challenge);
265 /* Only protocol 1.1 is supported */
266 if (buffer_len(&e->request) == 0)
268 buffer_get(&e->request, session_id, 16);
269 response_type = buffer_get_int(&e->request);
270 if (response_type != 1)
273 id = lookup_identity(key, 1);
274 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
275 Key *private = id->key;
276 /* Decrypt the challenge using the private key. */
277 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
280 /* The response is MD5 of decrypted challenge plus session id. */
281 len = BN_num_bytes(challenge);
282 if (len <= 0 || len > 32) {
283 logit("process_authentication_challenge: bad challenge length %d", len);
287 BN_bn2bin(challenge, buf + 32 - len);
289 MD5_Update(&md, buf, 32);
290 MD5_Update(&md, session_id, 16);
291 MD5_Final(mdbuf, &md);
293 /* Send the response. */
294 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
295 for (i = 0; i < 16; i++)
296 buffer_put_char(&msg, mdbuf[i]);
301 /* Unknown identity or protocol error. Send failure. */
302 buffer_put_char(&msg, SSH_AGENT_FAILURE);
304 buffer_put_int(&e->output, buffer_len(&msg));
305 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
307 BN_clear_free(challenge);
313 process_sign_request2(SocketEntry *e)
315 u_char *blob, *data, *signature = NULL;
316 u_int blen, dlen, slen = 0;
317 extern int datafellows;
325 blob = buffer_get_string(&e->request, &blen);
326 data = buffer_get_string(&e->request, &dlen);
328 flags = buffer_get_int(&e->request);
329 odatafellows = datafellows;
330 if (flags & SSH_AGENT_OLD_SIGNATURE)
331 datafellows = SSH_BUG_SIGBLOB;
333 key = key_from_blob(blob, blen);
335 Identity *id = lookup_identity(key, 2);
336 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
337 ok = key_sign(id->key, &signature, &slen, data, dlen);
342 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
343 buffer_put_string(&msg, signature, slen);
345 buffer_put_char(&msg, SSH_AGENT_FAILURE);
347 buffer_put_int(&e->output, buffer_len(&msg));
348 buffer_append(&e->output, buffer_ptr(&msg),
353 if (signature != NULL)
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 u_int deadline = 0, now = time(NULL);
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, death = 0, confirm = 0;
469 char *type_name, *comment;
476 k = key_new_private(KEY_RSA1);
477 (void) buffer_get_int(&e->request); /* ignored */
478 buffer_get_bignum(&e->request, k->rsa->n);
479 buffer_get_bignum(&e->request, k->rsa->e);
480 buffer_get_bignum(&e->request, k->rsa->d);
481 buffer_get_bignum(&e->request, k->rsa->iqmp);
483 /* SSH and SSL have p and q swapped */
484 buffer_get_bignum(&e->request, k->rsa->q); /* p */
485 buffer_get_bignum(&e->request, k->rsa->p); /* q */
487 /* Generate additional parameters */
488 rsa_generate_additional_parameters(k->rsa);
491 type_name = buffer_get_string(&e->request, NULL);
492 type = key_type_from_name(type_name);
496 k = key_new_private(type);
497 buffer_get_bignum2(&e->request, k->dsa->p);
498 buffer_get_bignum2(&e->request, k->dsa->q);
499 buffer_get_bignum2(&e->request, k->dsa->g);
500 buffer_get_bignum2(&e->request, k->dsa->pub_key);
501 buffer_get_bignum2(&e->request, k->dsa->priv_key);
504 cert = buffer_get_string(&e->request, &len);
505 if ((k = key_from_blob(cert, len)) == NULL)
506 fatal("Certificate parse failed");
509 buffer_get_bignum2(&e->request, k->dsa->priv_key);
512 k = key_new_private(type);
513 buffer_get_bignum2(&e->request, k->rsa->n);
514 buffer_get_bignum2(&e->request, k->rsa->e);
515 buffer_get_bignum2(&e->request, k->rsa->d);
516 buffer_get_bignum2(&e->request, k->rsa->iqmp);
517 buffer_get_bignum2(&e->request, k->rsa->p);
518 buffer_get_bignum2(&e->request, k->rsa->q);
520 /* Generate additional parameters */
521 rsa_generate_additional_parameters(k->rsa);
524 cert = buffer_get_string(&e->request, &len);
525 if ((k = key_from_blob(cert, len)) == NULL)
526 fatal("Certificate parse failed");
529 buffer_get_bignum2(&e->request, k->rsa->d);
530 buffer_get_bignum2(&e->request, k->rsa->iqmp);
531 buffer_get_bignum2(&e->request, k->rsa->p);
532 buffer_get_bignum2(&e->request, k->rsa->q);
535 buffer_clear(&e->request);
540 /* enable blinding */
545 if (RSA_blinding_on(k->rsa, NULL) != 1) {
546 error("process_add_identity: RSA_blinding_on failed");
552 comment = buffer_get_string(&e->request, NULL);
557 while (buffer_len(&e->request)) {
558 switch ((type = buffer_get_char(&e->request))) {
559 case SSH_AGENT_CONSTRAIN_LIFETIME:
560 death = time(NULL) + buffer_get_int(&e->request);
562 case SSH_AGENT_CONSTRAIN_CONFIRM:
566 error("process_add_identity: "
567 "Unknown constraint type %d", type);
574 if (lifetime && !death)
575 death = time(NULL) + lifetime;
576 if ((id = lookup_identity(k, version)) == NULL) {
577 id = xcalloc(1, sizeof(Identity));
579 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
580 /* Increment the number of identities. */
586 id->comment = comment;
588 id->confirm = confirm;
590 buffer_put_int(&e->output, 1);
591 buffer_put_char(&e->output,
592 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
595 /* XXX todo: encrypt sensitive data with passphrase */
597 process_lock_agent(SocketEntry *e, int lock)
602 passwd = buffer_get_string(&e->request, NULL);
603 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
605 memset(lock_passwd, 0, strlen(lock_passwd));
609 } else if (!locked && lock) {
611 lock_passwd = xstrdup(passwd);
614 memset(passwd, 0, strlen(passwd));
617 buffer_put_int(&e->output, 1);
618 buffer_put_char(&e->output,
619 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
623 no_identities(SocketEntry *e, u_int type)
628 buffer_put_char(&msg,
629 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
630 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
631 buffer_put_int(&msg, 0);
632 buffer_put_int(&e->output, buffer_len(&msg));
633 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
639 process_add_smartcard_key(SocketEntry *e)
641 char *provider = NULL, *pin;
642 int i, type, version, count = 0, success = 0, death = 0, confirm = 0;
643 Key **keys = NULL, *k;
647 provider = buffer_get_string(&e->request, NULL);
648 pin = buffer_get_string(&e->request, NULL);
650 while (buffer_len(&e->request)) {
651 switch ((type = buffer_get_char(&e->request))) {
652 case SSH_AGENT_CONSTRAIN_LIFETIME:
653 death = time(NULL) + buffer_get_int(&e->request);
655 case SSH_AGENT_CONSTRAIN_CONFIRM:
659 error("process_add_smartcard_key: "
660 "Unknown constraint type %d", type);
664 if (lifetime && !death)
665 death = time(NULL) + lifetime;
667 count = pkcs11_add_provider(provider, pin, &keys);
668 for (i = 0; i < count; i++) {
670 version = k->type == KEY_RSA1 ? 1 : 2;
671 tab = idtab_lookup(version);
672 if (lookup_identity(k, version) == NULL) {
673 id = xcalloc(1, sizeof(Identity));
675 id->provider = xstrdup(provider);
676 id->comment = xstrdup(provider); /* XXX */
678 id->confirm = confirm;
679 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
694 buffer_put_int(&e->output, 1);
695 buffer_put_char(&e->output,
696 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
700 process_remove_smartcard_key(SocketEntry *e)
702 char *provider = NULL, *pin = NULL;
703 int version, success = 0;
707 provider = buffer_get_string(&e->request, NULL);
708 pin = buffer_get_string(&e->request, NULL);
711 for (version = 1; version < 3; version++) {
712 tab = idtab_lookup(version);
713 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
714 nxt = TAILQ_NEXT(id, next);
715 if (!strcmp(provider, id->provider)) {
716 TAILQ_REMOVE(&tab->idlist, id, next);
722 if (pkcs11_del_provider(provider) == 0)
725 error("process_remove_smartcard_key:"
726 " pkcs11_del_provider failed");
728 buffer_put_int(&e->output, 1);
729 buffer_put_char(&e->output,
730 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
732 #endif /* ENABLE_PKCS11 */
734 /* dispatch incoming messages */
737 process_message(SocketEntry *e)
742 if (buffer_len(&e->input) < 5)
743 return; /* Incomplete message. */
744 cp = buffer_ptr(&e->input);
745 msg_len = get_u32(cp);
746 if (msg_len > 256 * 1024) {
750 if (buffer_len(&e->input) < msg_len + 4)
753 /* move the current input to e->request */
754 buffer_consume(&e->input, 4);
755 buffer_clear(&e->request);
756 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
757 buffer_consume(&e->input, msg_len);
758 type = buffer_get_char(&e->request);
760 /* check wheter agent is locked */
761 if (locked && type != SSH_AGENTC_UNLOCK) {
762 buffer_clear(&e->request);
764 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
765 case SSH2_AGENTC_REQUEST_IDENTITIES:
766 /* send empty lists */
767 no_identities(e, type);
770 /* send a fail message for all other request types */
771 buffer_put_int(&e->output, 1);
772 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
777 debug("type %d", type);
779 case SSH_AGENTC_LOCK:
780 case SSH_AGENTC_UNLOCK:
781 process_lock_agent(e, type == SSH_AGENTC_LOCK);
784 case SSH_AGENTC_RSA_CHALLENGE:
785 process_authentication_challenge1(e);
787 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
788 process_request_identities(e, 1);
790 case SSH_AGENTC_ADD_RSA_IDENTITY:
791 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
792 process_add_identity(e, 1);
794 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
795 process_remove_identity(e, 1);
797 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
798 process_remove_all_identities(e, 1);
801 case SSH2_AGENTC_SIGN_REQUEST:
802 process_sign_request2(e);
804 case SSH2_AGENTC_REQUEST_IDENTITIES:
805 process_request_identities(e, 2);
807 case SSH2_AGENTC_ADD_IDENTITY:
808 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
809 process_add_identity(e, 2);
811 case SSH2_AGENTC_REMOVE_IDENTITY:
812 process_remove_identity(e, 2);
814 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
815 process_remove_all_identities(e, 2);
818 case SSH_AGENTC_ADD_SMARTCARD_KEY:
819 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
820 process_add_smartcard_key(e);
822 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
823 process_remove_smartcard_key(e);
825 #endif /* ENABLE_PKCS11 */
827 /* Unknown message. Respond with failure. */
828 error("Unknown message %d", type);
829 buffer_clear(&e->request);
830 buffer_put_int(&e->output, 1);
831 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
837 new_socket(sock_type type, int fd)
839 u_int i, old_alloc, new_alloc;
846 for (i = 0; i < sockets_alloc; i++)
847 if (sockets[i].type == AUTH_UNUSED) {
849 buffer_init(&sockets[i].input);
850 buffer_init(&sockets[i].output);
851 buffer_init(&sockets[i].request);
852 sockets[i].type = type;
855 old_alloc = sockets_alloc;
856 new_alloc = sockets_alloc + 10;
857 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
858 for (i = old_alloc; i < new_alloc; i++)
859 sockets[i].type = AUTH_UNUSED;
860 sockets_alloc = new_alloc;
861 sockets[old_alloc].fd = fd;
862 buffer_init(&sockets[old_alloc].input);
863 buffer_init(&sockets[old_alloc].output);
864 buffer_init(&sockets[old_alloc].request);
865 sockets[old_alloc].type = type;
869 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
870 struct timeval **tvpp)
872 u_int i, sz, deadline;
874 static struct timeval tv;
876 for (i = 0; i < sockets_alloc; i++) {
877 switch (sockets[i].type) {
879 case AUTH_CONNECTION:
880 n = MAX(n, sockets[i].fd);
885 fatal("Unknown socket type %d", sockets[i].type);
890 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
891 if (*fdrp == NULL || sz > *nallocp) {
901 debug("XXX shrink: %d < %d", n, *fdl);
903 memset(*fdrp, 0, sz);
904 memset(*fdwp, 0, sz);
906 for (i = 0; i < sockets_alloc; i++) {
907 switch (sockets[i].type) {
909 case AUTH_CONNECTION:
910 FD_SET(sockets[i].fd, *fdrp);
911 if (buffer_len(&sockets[i].output) > 0)
912 FD_SET(sockets[i].fd, *fdwp);
919 if (parent_alive_interval != 0)
920 deadline = (deadline == 0) ? parent_alive_interval :
921 MIN(deadline, parent_alive_interval);
925 tv.tv_sec = deadline;
933 after_select(fd_set *readset, fd_set *writeset)
935 struct sockaddr_un sunaddr;
943 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
944 switch (sockets[i].type) {
948 if (FD_ISSET(sockets[i].fd, readset)) {
949 slen = sizeof(sunaddr);
950 sock = accept(sockets[i].fd,
951 (struct sockaddr *)&sunaddr, &slen);
953 error("accept from AUTH_SOCKET: %s",
957 if (getpeereid(sock, &euid, &egid) < 0) {
958 error("getpeereid %d failed: %s",
959 sock, strerror(errno));
963 if ((euid != 0) && (getuid() != euid)) {
964 error("uid mismatch: "
965 "peer euid %u != uid %u",
966 (u_int) euid, (u_int) getuid());
970 new_socket(AUTH_CONNECTION, sock);
973 case AUTH_CONNECTION:
974 if (buffer_len(&sockets[i].output) > 0 &&
975 FD_ISSET(sockets[i].fd, writeset)) {
976 len = write(sockets[i].fd,
977 buffer_ptr(&sockets[i].output),
978 buffer_len(&sockets[i].output));
979 if (len == -1 && (errno == EAGAIN ||
980 errno == EWOULDBLOCK ||
984 close_socket(&sockets[i]);
987 buffer_consume(&sockets[i].output, len);
989 if (FD_ISSET(sockets[i].fd, readset)) {
990 len = read(sockets[i].fd, buf, sizeof(buf));
991 if (len == -1 && (errno == EAGAIN ||
992 errno == EWOULDBLOCK ||
996 close_socket(&sockets[i]);
999 buffer_append(&sockets[i].input, buf, len);
1000 process_message(&sockets[i]);
1004 fatal("Unknown type %d", sockets[i].type);
1009 cleanup_socket(void)
1012 unlink(socket_name);
1026 cleanup_handler(int sig)
1029 #ifdef ENABLE_PKCS11
1036 check_parent_exists(void)
1038 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1039 /* printf("Parent has died - Authentication agent exiting.\n"); */
1048 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1050 fprintf(stderr, "Options:\n");
1051 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1052 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1053 fprintf(stderr, " -k Kill the current agent.\n");
1054 fprintf(stderr, " -d Debug mode.\n");
1055 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1056 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1061 main(int ac, char **av)
1063 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1064 int sock, fd, ch, result, saved_errno;
1066 char *shell, *format, *pidstr, *agentsocket = NULL;
1067 fd_set *readsetp = NULL, *writesetp = NULL;
1068 struct sockaddr_un sunaddr;
1069 #ifdef HAVE_SETRLIMIT
1074 extern char *optarg;
1076 char pidstrbuf[1 + 3 * sizeof pid];
1077 struct timeval *tvp = NULL;
1080 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1087 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1088 /* Disable ptrace on Linux without sgid bit */
1089 prctl(PR_SET_DUMPABLE, 0);
1092 SSLeay_add_all_algorithms();
1094 __progname = ssh_get_progname(av[0]);
1098 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1119 agentsocket = optarg;
1122 if ((lifetime = convtime(optarg)) == -1) {
1123 fprintf(stderr, "Invalid lifetime\n");
1134 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1137 if (ac == 0 && !c_flag && !s_flag) {
1138 shell = getenv("SHELL");
1139 if (shell != NULL && (len = strlen(shell)) > 2 &&
1140 strncmp(shell + len - 3, "csh", 3) == 0)
1144 const char *errstr = NULL;
1146 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1147 if (pidstr == NULL) {
1148 fprintf(stderr, "%s not set, cannot kill agent\n",
1149 SSH_AGENTPID_ENV_NAME);
1152 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1155 "%s=\"%s\", which is not a good PID: %s\n",
1156 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1159 if (kill(pid, SIGTERM) == -1) {
1163 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1164 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1165 printf(format, SSH_AGENTPID_ENV_NAME);
1166 printf("echo Agent pid %ld killed;\n", (long)pid);
1169 parent_pid = getpid();
1171 if (agentsocket == NULL) {
1172 /* Create private directory for agent socket */
1173 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1174 if (mkdtemp(socket_dir) == NULL) {
1175 perror("mkdtemp: private socket dir");
1178 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1181 /* Try to use specified agent socket */
1182 socket_dir[0] = '\0';
1183 strlcpy(socket_name, agentsocket, sizeof socket_name);
1187 * Create socket early so it will exist before command gets run from
1190 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1193 *socket_name = '\0'; /* Don't unlink any existing file */
1196 memset(&sunaddr, 0, sizeof(sunaddr));
1197 sunaddr.sun_family = AF_UNIX;
1198 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1199 prev_mask = umask(0177);
1200 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1202 *socket_name = '\0'; /* Don't unlink any existing file */
1207 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1213 * Fork, and have the parent execute the command, if any, or present
1214 * the socket data. The child continues as the authentication agent.
1217 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
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("echo Agent pid %ld;\n", (long)parent_pid);
1229 if (pid != 0) { /* Parent - execute the given command. */
1231 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1233 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1234 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1235 SSH_AUTHSOCKET_ENV_NAME);
1236 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1237 SSH_AGENTPID_ENV_NAME);
1238 printf("echo Agent pid %ld;\n", (long)pid);
1241 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1242 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1251 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1253 if (setsid() == -1) {
1254 error("setsid: %s", strerror(errno));
1259 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1260 /* XXX might close listen socket */
1261 (void)dup2(fd, STDIN_FILENO);
1262 (void)dup2(fd, STDOUT_FILENO);
1263 (void)dup2(fd, STDERR_FILENO);
1268 #ifdef HAVE_SETRLIMIT
1269 /* deny core dumps, since memory contains unencrypted private keys */
1270 rlim.rlim_cur = rlim.rlim_max = 0;
1271 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1272 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1279 #ifdef ENABLE_PKCS11
1282 new_socket(AUTH_SOCKET, sock);
1284 parent_alive_interval = 10;
1287 signal(SIGINT, SIG_IGN);
1288 signal(SIGPIPE, SIG_IGN);
1289 signal(SIGHUP, cleanup_handler);
1290 signal(SIGTERM, cleanup_handler);
1294 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1295 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1296 saved_errno = errno;
1297 if (parent_alive_interval != 0)
1298 check_parent_exists();
1299 (void) reaper(); /* remove expired keys */
1301 if (saved_errno == EINTR)
1303 fatal("select: %s", strerror(saved_errno));
1304 } else if (result > 0)
1305 after_select(readsetp, writesetp);