1 /* $OpenBSD: ssh-agent.c,v 1.166 2010/04/16 01:47:26 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 <openssl/md5.h>
55 #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 u_int 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 (0 == forever) */
139 static int lifetime = 0;
142 close_socket(SocketEntry *e)
146 e->type = AUTH_UNUSED;
147 buffer_free(&e->input);
148 buffer_free(&e->output);
149 buffer_free(&e->request);
157 for (i = 0; i <=2; i++) {
158 TAILQ_INIT(&idtable[i].idlist);
159 idtable[i].nentries = 0;
163 /* return private key table for requested protocol version */
165 idtab_lookup(int version)
167 if (version < 1 || version > 2)
168 fatal("internal error, bad protocol version %d", version);
169 return &idtable[version];
173 free_identity(Identity *id)
176 if (id->provider != NULL)
182 /* return matching private key for given public key */
184 lookup_identity(Key *key, int version)
188 Idtab *tab = idtab_lookup(version);
189 TAILQ_FOREACH(id, &tab->idlist, next) {
190 if (key_equal(key, id->key))
196 /* Check confirmation of keysign request */
198 confirm_key(Identity *id)
203 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
204 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
212 /* send list of supported public keys to 'client' */
214 process_request_identities(SocketEntry *e, int version)
216 Idtab *tab = idtab_lookup(version);
221 buffer_put_char(&msg, (version == 1) ?
222 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
223 buffer_put_int(&msg, tab->nentries);
224 TAILQ_FOREACH(id, &tab->idlist, next) {
225 if (id->key->type == KEY_RSA1) {
226 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
227 buffer_put_bignum(&msg, id->key->rsa->e);
228 buffer_put_bignum(&msg, id->key->rsa->n);
232 key_to_blob(id->key, &blob, &blen);
233 buffer_put_string(&msg, blob, blen);
236 buffer_put_cstring(&msg, id->comment);
238 buffer_put_int(&e->output, buffer_len(&msg));
239 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
245 process_authentication_challenge1(SocketEntry *e)
247 u_char buf[32], mdbuf[16], session_id[16];
257 key = key_new(KEY_RSA1);
258 if ((challenge = BN_new()) == NULL)
259 fatal("process_authentication_challenge1: BN_new failed");
261 (void) buffer_get_int(&e->request); /* ignored */
262 buffer_get_bignum(&e->request, key->rsa->e);
263 buffer_get_bignum(&e->request, key->rsa->n);
264 buffer_get_bignum(&e->request, challenge);
266 /* Only protocol 1.1 is supported */
267 if (buffer_len(&e->request) == 0)
269 buffer_get(&e->request, session_id, 16);
270 response_type = buffer_get_int(&e->request);
271 if (response_type != 1)
274 id = lookup_identity(key, 1);
275 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
276 Key *private = id->key;
277 /* Decrypt the challenge using the private key. */
278 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
281 /* The response is MD5 of decrypted challenge plus session id. */
282 len = BN_num_bytes(challenge);
283 if (len <= 0 || len > 32) {
284 logit("process_authentication_challenge: bad challenge length %d", len);
288 BN_bn2bin(challenge, buf + 32 - len);
290 MD5_Update(&md, buf, 32);
291 MD5_Update(&md, session_id, 16);
292 MD5_Final(mdbuf, &md);
294 /* Send the response. */
295 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
296 for (i = 0; i < 16; i++)
297 buffer_put_char(&msg, mdbuf[i]);
302 /* Unknown identity or protocol error. Send failure. */
303 buffer_put_char(&msg, SSH_AGENT_FAILURE);
305 buffer_put_int(&e->output, buffer_len(&msg));
306 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
308 BN_clear_free(challenge);
314 process_sign_request2(SocketEntry *e)
316 u_char *blob, *data, *signature = NULL;
317 u_int blen, dlen, slen = 0;
318 extern int datafellows;
326 blob = buffer_get_string(&e->request, &blen);
327 data = buffer_get_string(&e->request, &dlen);
329 flags = buffer_get_int(&e->request);
330 odatafellows = datafellows;
331 if (flags & SSH_AGENT_OLD_SIGNATURE)
332 datafellows = SSH_BUG_SIGBLOB;
334 key = key_from_blob(blob, blen);
336 Identity *id = lookup_identity(key, 2);
337 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
338 ok = key_sign(id->key, &signature, &slen, data, dlen);
343 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
344 buffer_put_string(&msg, signature, slen);
346 buffer_put_char(&msg, SSH_AGENT_FAILURE);
348 buffer_put_int(&e->output, buffer_len(&msg));
349 buffer_append(&e->output, buffer_ptr(&msg),
354 if (signature != NULL)
356 datafellows = odatafellows;
361 process_remove_identity(SocketEntry *e, int version)
370 key = key_new(KEY_RSA1);
371 bits = buffer_get_int(&e->request);
372 buffer_get_bignum(&e->request, key->rsa->e);
373 buffer_get_bignum(&e->request, key->rsa->n);
375 if (bits != key_size(key))
376 logit("Warning: identity keysize mismatch: actual %u, announced %u",
377 key_size(key), bits);
380 blob = buffer_get_string(&e->request, &blen);
381 key = key_from_blob(blob, blen);
386 Identity *id = lookup_identity(key, version);
389 * We have this key. Free the old key. Since we
390 * don't want to leave empty slots in the middle of
391 * the array, we actually free the key there and move
392 * all the entries between the empty slot and the end
395 Idtab *tab = idtab_lookup(version);
396 if (tab->nentries < 1)
397 fatal("process_remove_identity: "
398 "internal error: tab->nentries %d",
400 TAILQ_REMOVE(&tab->idlist, id, next);
407 buffer_put_int(&e->output, 1);
408 buffer_put_char(&e->output,
409 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
413 process_remove_all_identities(SocketEntry *e, int version)
415 Idtab *tab = idtab_lookup(version);
418 /* Loop over all identities and clear the keys. */
419 for (id = TAILQ_FIRST(&tab->idlist); id;
420 id = TAILQ_FIRST(&tab->idlist)) {
421 TAILQ_REMOVE(&tab->idlist, id, next);
425 /* Mark that there are no identities. */
429 buffer_put_int(&e->output, 1);
430 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
433 /* removes expired keys and returns number of seconds until the next expiry */
437 u_int deadline = 0, now = time(NULL);
442 for (version = 1; version < 3; version++) {
443 tab = idtab_lookup(version);
444 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
445 nxt = TAILQ_NEXT(id, next);
448 if (now >= id->death) {
449 debug("expiring key '%s'", id->comment);
450 TAILQ_REMOVE(&tab->idlist, id, next);
454 deadline = (deadline == 0) ? id->death :
455 MIN(deadline, id->death);
458 if (deadline == 0 || deadline <= now)
461 return (deadline - now);
465 process_add_identity(SocketEntry *e, int version)
467 Idtab *tab = idtab_lookup(version);
469 int type, success = 0, death = 0, confirm = 0;
470 char *type_name, *comment;
477 k = key_new_private(KEY_RSA1);
478 (void) buffer_get_int(&e->request); /* ignored */
479 buffer_get_bignum(&e->request, k->rsa->n);
480 buffer_get_bignum(&e->request, k->rsa->e);
481 buffer_get_bignum(&e->request, k->rsa->d);
482 buffer_get_bignum(&e->request, k->rsa->iqmp);
484 /* SSH and SSL have p and q swapped */
485 buffer_get_bignum(&e->request, k->rsa->q); /* p */
486 buffer_get_bignum(&e->request, k->rsa->p); /* q */
488 /* Generate additional parameters */
489 rsa_generate_additional_parameters(k->rsa);
492 type_name = buffer_get_string(&e->request, NULL);
493 type = key_type_from_name(type_name);
497 k = key_new_private(type);
498 buffer_get_bignum2(&e->request, k->dsa->p);
499 buffer_get_bignum2(&e->request, k->dsa->q);
500 buffer_get_bignum2(&e->request, k->dsa->g);
501 buffer_get_bignum2(&e->request, k->dsa->pub_key);
502 buffer_get_bignum2(&e->request, k->dsa->priv_key);
504 case KEY_DSA_CERT_V00:
506 cert = buffer_get_string(&e->request, &len);
507 if ((k = key_from_blob(cert, len)) == NULL)
508 fatal("Certificate parse failed");
511 buffer_get_bignum2(&e->request, k->dsa->priv_key);
514 k = key_new_private(type);
515 buffer_get_bignum2(&e->request, k->rsa->n);
516 buffer_get_bignum2(&e->request, k->rsa->e);
517 buffer_get_bignum2(&e->request, k->rsa->d);
518 buffer_get_bignum2(&e->request, k->rsa->iqmp);
519 buffer_get_bignum2(&e->request, k->rsa->p);
520 buffer_get_bignum2(&e->request, k->rsa->q);
522 /* Generate additional parameters */
523 rsa_generate_additional_parameters(k->rsa);
525 case KEY_RSA_CERT_V00:
527 cert = buffer_get_string(&e->request, &len);
528 if ((k = key_from_blob(cert, len)) == NULL)
529 fatal("Certificate parse failed");
532 buffer_get_bignum2(&e->request, k->rsa->d);
533 buffer_get_bignum2(&e->request, k->rsa->iqmp);
534 buffer_get_bignum2(&e->request, k->rsa->p);
535 buffer_get_bignum2(&e->request, k->rsa->q);
538 buffer_clear(&e->request);
543 /* enable blinding */
546 case KEY_RSA_CERT_V00:
549 if (RSA_blinding_on(k->rsa, NULL) != 1) {
550 error("process_add_identity: RSA_blinding_on failed");
556 comment = buffer_get_string(&e->request, NULL);
561 while (buffer_len(&e->request)) {
562 switch ((type = buffer_get_char(&e->request))) {
563 case SSH_AGENT_CONSTRAIN_LIFETIME:
564 death = time(NULL) + buffer_get_int(&e->request);
566 case SSH_AGENT_CONSTRAIN_CONFIRM:
570 error("process_add_identity: "
571 "Unknown constraint type %d", type);
578 if (lifetime && !death)
579 death = time(NULL) + lifetime;
580 if ((id = lookup_identity(k, version)) == NULL) {
581 id = xcalloc(1, sizeof(Identity));
583 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
584 /* Increment the number of identities. */
590 id->comment = comment;
592 id->confirm = confirm;
594 buffer_put_int(&e->output, 1);
595 buffer_put_char(&e->output,
596 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
599 /* XXX todo: encrypt sensitive data with passphrase */
601 process_lock_agent(SocketEntry *e, int lock)
606 passwd = buffer_get_string(&e->request, NULL);
607 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
609 memset(lock_passwd, 0, strlen(lock_passwd));
613 } else if (!locked && lock) {
615 lock_passwd = xstrdup(passwd);
618 memset(passwd, 0, strlen(passwd));
621 buffer_put_int(&e->output, 1);
622 buffer_put_char(&e->output,
623 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
627 no_identities(SocketEntry *e, u_int type)
632 buffer_put_char(&msg,
633 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
634 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
635 buffer_put_int(&msg, 0);
636 buffer_put_int(&e->output, buffer_len(&msg));
637 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
643 process_add_smartcard_key(SocketEntry *e)
645 char *provider = NULL, *pin;
646 int i, type, version, count = 0, success = 0, death = 0, confirm = 0;
647 Key **keys = NULL, *k;
651 provider = buffer_get_string(&e->request, NULL);
652 pin = buffer_get_string(&e->request, NULL);
654 while (buffer_len(&e->request)) {
655 switch ((type = buffer_get_char(&e->request))) {
656 case SSH_AGENT_CONSTRAIN_LIFETIME:
657 death = time(NULL) + buffer_get_int(&e->request);
659 case SSH_AGENT_CONSTRAIN_CONFIRM:
663 error("process_add_smartcard_key: "
664 "Unknown constraint type %d", type);
668 if (lifetime && !death)
669 death = time(NULL) + lifetime;
671 count = pkcs11_add_provider(provider, pin, &keys);
672 for (i = 0; i < count; i++) {
674 version = k->type == KEY_RSA1 ? 1 : 2;
675 tab = idtab_lookup(version);
676 if (lookup_identity(k, version) == NULL) {
677 id = xcalloc(1, sizeof(Identity));
679 id->provider = xstrdup(provider);
680 id->comment = xstrdup(provider); /* XXX */
682 id->confirm = confirm;
683 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
698 buffer_put_int(&e->output, 1);
699 buffer_put_char(&e->output,
700 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
704 process_remove_smartcard_key(SocketEntry *e)
706 char *provider = NULL, *pin = NULL;
707 int version, success = 0;
711 provider = buffer_get_string(&e->request, NULL);
712 pin = buffer_get_string(&e->request, NULL);
715 for (version = 1; version < 3; version++) {
716 tab = idtab_lookup(version);
717 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
718 nxt = TAILQ_NEXT(id, next);
719 if (!strcmp(provider, id->provider)) {
720 TAILQ_REMOVE(&tab->idlist, id, next);
726 if (pkcs11_del_provider(provider) == 0)
729 error("process_remove_smartcard_key:"
730 " pkcs11_del_provider failed");
732 buffer_put_int(&e->output, 1);
733 buffer_put_char(&e->output,
734 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
736 #endif /* ENABLE_PKCS11 */
738 /* dispatch incoming messages */
741 process_message(SocketEntry *e)
746 if (buffer_len(&e->input) < 5)
747 return; /* Incomplete message. */
748 cp = buffer_ptr(&e->input);
749 msg_len = get_u32(cp);
750 if (msg_len > 256 * 1024) {
754 if (buffer_len(&e->input) < msg_len + 4)
757 /* move the current input to e->request */
758 buffer_consume(&e->input, 4);
759 buffer_clear(&e->request);
760 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
761 buffer_consume(&e->input, msg_len);
762 type = buffer_get_char(&e->request);
764 /* check wheter agent is locked */
765 if (locked && type != SSH_AGENTC_UNLOCK) {
766 buffer_clear(&e->request);
768 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
769 case SSH2_AGENTC_REQUEST_IDENTITIES:
770 /* send empty lists */
771 no_identities(e, type);
774 /* send a fail message for all other request types */
775 buffer_put_int(&e->output, 1);
776 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
781 debug("type %d", type);
783 case SSH_AGENTC_LOCK:
784 case SSH_AGENTC_UNLOCK:
785 process_lock_agent(e, type == SSH_AGENTC_LOCK);
788 case SSH_AGENTC_RSA_CHALLENGE:
789 process_authentication_challenge1(e);
791 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
792 process_request_identities(e, 1);
794 case SSH_AGENTC_ADD_RSA_IDENTITY:
795 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
796 process_add_identity(e, 1);
798 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
799 process_remove_identity(e, 1);
801 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
802 process_remove_all_identities(e, 1);
805 case SSH2_AGENTC_SIGN_REQUEST:
806 process_sign_request2(e);
808 case SSH2_AGENTC_REQUEST_IDENTITIES:
809 process_request_identities(e, 2);
811 case SSH2_AGENTC_ADD_IDENTITY:
812 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
813 process_add_identity(e, 2);
815 case SSH2_AGENTC_REMOVE_IDENTITY:
816 process_remove_identity(e, 2);
818 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
819 process_remove_all_identities(e, 2);
822 case SSH_AGENTC_ADD_SMARTCARD_KEY:
823 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
824 process_add_smartcard_key(e);
826 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
827 process_remove_smartcard_key(e);
829 #endif /* ENABLE_PKCS11 */
831 /* Unknown message. Respond with failure. */
832 error("Unknown message %d", type);
833 buffer_clear(&e->request);
834 buffer_put_int(&e->output, 1);
835 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
841 new_socket(sock_type type, int fd)
843 u_int i, old_alloc, new_alloc;
850 for (i = 0; i < sockets_alloc; i++)
851 if (sockets[i].type == AUTH_UNUSED) {
853 buffer_init(&sockets[i].input);
854 buffer_init(&sockets[i].output);
855 buffer_init(&sockets[i].request);
856 sockets[i].type = type;
859 old_alloc = sockets_alloc;
860 new_alloc = sockets_alloc + 10;
861 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
862 for (i = old_alloc; i < new_alloc; i++)
863 sockets[i].type = AUTH_UNUSED;
864 sockets_alloc = new_alloc;
865 sockets[old_alloc].fd = fd;
866 buffer_init(&sockets[old_alloc].input);
867 buffer_init(&sockets[old_alloc].output);
868 buffer_init(&sockets[old_alloc].request);
869 sockets[old_alloc].type = type;
873 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
874 struct timeval **tvpp)
876 u_int i, sz, deadline;
878 static struct timeval tv;
880 for (i = 0; i < sockets_alloc; i++) {
881 switch (sockets[i].type) {
883 case AUTH_CONNECTION:
884 n = MAX(n, sockets[i].fd);
889 fatal("Unknown socket type %d", sockets[i].type);
894 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
895 if (*fdrp == NULL || sz > *nallocp) {
905 debug("XXX shrink: %d < %d", n, *fdl);
907 memset(*fdrp, 0, sz);
908 memset(*fdwp, 0, sz);
910 for (i = 0; i < sockets_alloc; i++) {
911 switch (sockets[i].type) {
913 case AUTH_CONNECTION:
914 FD_SET(sockets[i].fd, *fdrp);
915 if (buffer_len(&sockets[i].output) > 0)
916 FD_SET(sockets[i].fd, *fdwp);
923 if (parent_alive_interval != 0)
924 deadline = (deadline == 0) ? parent_alive_interval :
925 MIN(deadline, parent_alive_interval);
929 tv.tv_sec = deadline;
937 after_select(fd_set *readset, fd_set *writeset)
939 struct sockaddr_un sunaddr;
947 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
948 switch (sockets[i].type) {
952 if (FD_ISSET(sockets[i].fd, readset)) {
953 slen = sizeof(sunaddr);
954 sock = accept(sockets[i].fd,
955 (struct sockaddr *)&sunaddr, &slen);
957 error("accept from AUTH_SOCKET: %s",
961 if (getpeereid(sock, &euid, &egid) < 0) {
962 error("getpeereid %d failed: %s",
963 sock, strerror(errno));
967 if ((euid != 0) && (getuid() != euid)) {
968 error("uid mismatch: "
969 "peer euid %u != uid %u",
970 (u_int) euid, (u_int) getuid());
974 new_socket(AUTH_CONNECTION, sock);
977 case AUTH_CONNECTION:
978 if (buffer_len(&sockets[i].output) > 0 &&
979 FD_ISSET(sockets[i].fd, writeset)) {
980 len = write(sockets[i].fd,
981 buffer_ptr(&sockets[i].output),
982 buffer_len(&sockets[i].output));
983 if (len == -1 && (errno == EAGAIN ||
984 errno == EWOULDBLOCK ||
988 close_socket(&sockets[i]);
991 buffer_consume(&sockets[i].output, len);
993 if (FD_ISSET(sockets[i].fd, readset)) {
994 len = read(sockets[i].fd, buf, sizeof(buf));
995 if (len == -1 && (errno == EAGAIN ||
996 errno == EWOULDBLOCK ||
1000 close_socket(&sockets[i]);
1003 buffer_append(&sockets[i].input, buf, len);
1004 process_message(&sockets[i]);
1008 fatal("Unknown type %d", sockets[i].type);
1013 cleanup_socket(void)
1016 unlink(socket_name);
1030 cleanup_handler(int sig)
1033 #ifdef ENABLE_PKCS11
1040 check_parent_exists(void)
1042 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1043 /* printf("Parent has died - Authentication agent exiting.\n"); */
1052 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1054 fprintf(stderr, "Options:\n");
1055 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1056 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1057 fprintf(stderr, " -k Kill the current agent.\n");
1058 fprintf(stderr, " -d Debug mode.\n");
1059 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1060 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1065 main(int ac, char **av)
1067 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1068 int sock, fd, ch, result, saved_errno;
1070 char *shell, *format, *pidstr, *agentsocket = NULL;
1071 fd_set *readsetp = NULL, *writesetp = NULL;
1072 struct sockaddr_un sunaddr;
1073 #ifdef HAVE_SETRLIMIT
1078 extern char *optarg;
1080 char pidstrbuf[1 + 3 * sizeof pid];
1081 struct timeval *tvp = NULL;
1084 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1092 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1093 /* Disable ptrace on Linux without sgid bit */
1094 prctl(PR_SET_DUMPABLE, 0);
1097 SSLeay_add_all_algorithms();
1099 __progname = ssh_get_progname(av[0]);
1103 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1124 agentsocket = optarg;
1127 if ((lifetime = convtime(optarg)) == -1) {
1128 fprintf(stderr, "Invalid lifetime\n");
1139 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1142 if (ac == 0 && !c_flag && !s_flag) {
1143 shell = getenv("SHELL");
1144 if (shell != NULL && (len = strlen(shell)) > 2 &&
1145 strncmp(shell + len - 3, "csh", 3) == 0)
1149 const char *errstr = NULL;
1151 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1152 if (pidstr == NULL) {
1153 fprintf(stderr, "%s not set, cannot kill agent\n",
1154 SSH_AGENTPID_ENV_NAME);
1157 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1160 "%s=\"%s\", which is not a good PID: %s\n",
1161 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1164 if (kill(pid, SIGTERM) == -1) {
1168 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1169 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1170 printf(format, SSH_AGENTPID_ENV_NAME);
1171 printf("echo Agent pid %ld killed;\n", (long)pid);
1174 parent_pid = getpid();
1176 if (agentsocket == NULL) {
1177 /* Create private directory for agent socket */
1178 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1179 if (mkdtemp(socket_dir) == NULL) {
1180 perror("mkdtemp: private socket dir");
1183 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1186 /* Try to use specified agent socket */
1187 socket_dir[0] = '\0';
1188 strlcpy(socket_name, agentsocket, sizeof socket_name);
1192 * Create socket early so it will exist before command gets run from
1195 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1198 *socket_name = '\0'; /* Don't unlink any existing file */
1201 memset(&sunaddr, 0, sizeof(sunaddr));
1202 sunaddr.sun_family = AF_UNIX;
1203 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1204 prev_mask = umask(0177);
1205 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1207 *socket_name = '\0'; /* Don't unlink any existing file */
1212 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1218 * Fork, and have the parent execute the command, if any, or present
1219 * the socket data. The child continues as the authentication agent.
1222 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1223 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1224 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1225 SSH_AUTHSOCKET_ENV_NAME);
1226 printf("echo Agent pid %ld;\n", (long)parent_pid);
1234 if (pid != 0) { /* Parent - execute the given command. */
1236 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1238 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1239 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1240 SSH_AUTHSOCKET_ENV_NAME);
1241 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1242 SSH_AGENTPID_ENV_NAME);
1243 printf("echo Agent pid %ld;\n", (long)pid);
1246 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1247 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1256 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1258 if (setsid() == -1) {
1259 error("setsid: %s", strerror(errno));
1264 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1265 /* XXX might close listen socket */
1266 (void)dup2(fd, STDIN_FILENO);
1267 (void)dup2(fd, STDOUT_FILENO);
1268 (void)dup2(fd, STDERR_FILENO);
1273 #ifdef HAVE_SETRLIMIT
1274 /* deny core dumps, since memory contains unencrypted private keys */
1275 rlim.rlim_cur = rlim.rlim_max = 0;
1276 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1277 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1284 #ifdef ENABLE_PKCS11
1287 new_socket(AUTH_SOCKET, sock);
1289 parent_alive_interval = 10;
1292 signal(SIGINT, SIG_IGN);
1293 signal(SIGPIPE, SIG_IGN);
1294 signal(SIGHUP, cleanup_handler);
1295 signal(SIGTERM, cleanup_handler);
1299 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1300 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1301 saved_errno = errno;
1302 if (parent_alive_interval != 0)
1303 check_parent_exists();
1304 (void) reaper(); /* remove expired keys */
1306 if (saved_errno == EINTR)
1308 fatal("select: %s", strerror(saved_errno));
1309 } else if (result > 0)
1310 after_select(readsetp, writesetp);