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.
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);
503 case KEY_DSA_CERT_V00:
505 cert = buffer_get_string(&e->request, &len);
506 if ((k = key_from_blob(cert, len)) == NULL)
507 fatal("Certificate parse failed");
510 buffer_get_bignum2(&e->request, k->dsa->priv_key);
513 k = key_new_private(type);
514 buffer_get_bignum2(&e->request, k->rsa->n);
515 buffer_get_bignum2(&e->request, k->rsa->e);
516 buffer_get_bignum2(&e->request, k->rsa->d);
517 buffer_get_bignum2(&e->request, k->rsa->iqmp);
518 buffer_get_bignum2(&e->request, k->rsa->p);
519 buffer_get_bignum2(&e->request, k->rsa->q);
521 /* Generate additional parameters */
522 rsa_generate_additional_parameters(k->rsa);
524 case KEY_RSA_CERT_V00:
526 cert = buffer_get_string(&e->request, &len);
527 if ((k = key_from_blob(cert, len)) == NULL)
528 fatal("Certificate parse failed");
531 buffer_get_bignum2(&e->request, k->rsa->d);
532 buffer_get_bignum2(&e->request, k->rsa->iqmp);
533 buffer_get_bignum2(&e->request, k->rsa->p);
534 buffer_get_bignum2(&e->request, k->rsa->q);
537 buffer_clear(&e->request);
542 /* enable blinding */
545 case KEY_RSA_CERT_V00:
548 if (RSA_blinding_on(k->rsa, NULL) != 1) {
549 error("process_add_identity: RSA_blinding_on failed");
555 comment = buffer_get_string(&e->request, NULL);
560 while (buffer_len(&e->request)) {
561 switch ((type = buffer_get_char(&e->request))) {
562 case SSH_AGENT_CONSTRAIN_LIFETIME:
563 death = time(NULL) + buffer_get_int(&e->request);
565 case SSH_AGENT_CONSTRAIN_CONFIRM:
569 error("process_add_identity: "
570 "Unknown constraint type %d", type);
577 if (lifetime && !death)
578 death = time(NULL) + lifetime;
579 if ((id = lookup_identity(k, version)) == NULL) {
580 id = xcalloc(1, sizeof(Identity));
582 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
583 /* Increment the number of identities. */
589 id->comment = comment;
591 id->confirm = confirm;
593 buffer_put_int(&e->output, 1);
594 buffer_put_char(&e->output,
595 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
598 /* XXX todo: encrypt sensitive data with passphrase */
600 process_lock_agent(SocketEntry *e, int lock)
605 passwd = buffer_get_string(&e->request, NULL);
606 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
608 memset(lock_passwd, 0, strlen(lock_passwd));
612 } else if (!locked && lock) {
614 lock_passwd = xstrdup(passwd);
617 memset(passwd, 0, strlen(passwd));
620 buffer_put_int(&e->output, 1);
621 buffer_put_char(&e->output,
622 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
626 no_identities(SocketEntry *e, u_int type)
631 buffer_put_char(&msg,
632 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
633 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
634 buffer_put_int(&msg, 0);
635 buffer_put_int(&e->output, buffer_len(&msg));
636 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
642 process_add_smartcard_key(SocketEntry *e)
644 char *provider = NULL, *pin;
645 int i, type, version, count = 0, success = 0, death = 0, confirm = 0;
646 Key **keys = NULL, *k;
650 provider = buffer_get_string(&e->request, NULL);
651 pin = buffer_get_string(&e->request, NULL);
653 while (buffer_len(&e->request)) {
654 switch ((type = buffer_get_char(&e->request))) {
655 case SSH_AGENT_CONSTRAIN_LIFETIME:
656 death = time(NULL) + buffer_get_int(&e->request);
658 case SSH_AGENT_CONSTRAIN_CONFIRM:
662 error("process_add_smartcard_key: "
663 "Unknown constraint type %d", type);
667 if (lifetime && !death)
668 death = time(NULL) + lifetime;
670 count = pkcs11_add_provider(provider, pin, &keys);
671 for (i = 0; i < count; i++) {
673 version = k->type == KEY_RSA1 ? 1 : 2;
674 tab = idtab_lookup(version);
675 if (lookup_identity(k, version) == NULL) {
676 id = xcalloc(1, sizeof(Identity));
678 id->provider = xstrdup(provider);
679 id->comment = xstrdup(provider); /* XXX */
681 id->confirm = confirm;
682 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
697 buffer_put_int(&e->output, 1);
698 buffer_put_char(&e->output,
699 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
703 process_remove_smartcard_key(SocketEntry *e)
705 char *provider = NULL, *pin = NULL;
706 int version, success = 0;
710 provider = buffer_get_string(&e->request, NULL);
711 pin = buffer_get_string(&e->request, NULL);
714 for (version = 1; version < 3; version++) {
715 tab = idtab_lookup(version);
716 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
717 nxt = TAILQ_NEXT(id, next);
718 if (!strcmp(provider, id->provider)) {
719 TAILQ_REMOVE(&tab->idlist, id, next);
725 if (pkcs11_del_provider(provider) == 0)
728 error("process_remove_smartcard_key:"
729 " pkcs11_del_provider failed");
731 buffer_put_int(&e->output, 1);
732 buffer_put_char(&e->output,
733 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
735 #endif /* ENABLE_PKCS11 */
737 /* dispatch incoming messages */
740 process_message(SocketEntry *e)
745 if (buffer_len(&e->input) < 5)
746 return; /* Incomplete message. */
747 cp = buffer_ptr(&e->input);
748 msg_len = get_u32(cp);
749 if (msg_len > 256 * 1024) {
753 if (buffer_len(&e->input) < msg_len + 4)
756 /* move the current input to e->request */
757 buffer_consume(&e->input, 4);
758 buffer_clear(&e->request);
759 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
760 buffer_consume(&e->input, msg_len);
761 type = buffer_get_char(&e->request);
763 /* check wheter agent is locked */
764 if (locked && type != SSH_AGENTC_UNLOCK) {
765 buffer_clear(&e->request);
767 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
768 case SSH2_AGENTC_REQUEST_IDENTITIES:
769 /* send empty lists */
770 no_identities(e, type);
773 /* send a fail message for all other request types */
774 buffer_put_int(&e->output, 1);
775 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
780 debug("type %d", type);
782 case SSH_AGENTC_LOCK:
783 case SSH_AGENTC_UNLOCK:
784 process_lock_agent(e, type == SSH_AGENTC_LOCK);
787 case SSH_AGENTC_RSA_CHALLENGE:
788 process_authentication_challenge1(e);
790 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
791 process_request_identities(e, 1);
793 case SSH_AGENTC_ADD_RSA_IDENTITY:
794 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
795 process_add_identity(e, 1);
797 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
798 process_remove_identity(e, 1);
800 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
801 process_remove_all_identities(e, 1);
804 case SSH2_AGENTC_SIGN_REQUEST:
805 process_sign_request2(e);
807 case SSH2_AGENTC_REQUEST_IDENTITIES:
808 process_request_identities(e, 2);
810 case SSH2_AGENTC_ADD_IDENTITY:
811 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
812 process_add_identity(e, 2);
814 case SSH2_AGENTC_REMOVE_IDENTITY:
815 process_remove_identity(e, 2);
817 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
818 process_remove_all_identities(e, 2);
821 case SSH_AGENTC_ADD_SMARTCARD_KEY:
822 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
823 process_add_smartcard_key(e);
825 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
826 process_remove_smartcard_key(e);
828 #endif /* ENABLE_PKCS11 */
830 /* Unknown message. Respond with failure. */
831 error("Unknown message %d", type);
832 buffer_clear(&e->request);
833 buffer_put_int(&e->output, 1);
834 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
840 new_socket(sock_type type, int fd)
842 u_int i, old_alloc, new_alloc;
849 for (i = 0; i < sockets_alloc; i++)
850 if (sockets[i].type == AUTH_UNUSED) {
852 buffer_init(&sockets[i].input);
853 buffer_init(&sockets[i].output);
854 buffer_init(&sockets[i].request);
855 sockets[i].type = type;
858 old_alloc = sockets_alloc;
859 new_alloc = sockets_alloc + 10;
860 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
861 for (i = old_alloc; i < new_alloc; i++)
862 sockets[i].type = AUTH_UNUSED;
863 sockets_alloc = new_alloc;
864 sockets[old_alloc].fd = fd;
865 buffer_init(&sockets[old_alloc].input);
866 buffer_init(&sockets[old_alloc].output);
867 buffer_init(&sockets[old_alloc].request);
868 sockets[old_alloc].type = type;
872 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
873 struct timeval **tvpp)
875 u_int i, sz, deadline;
877 static struct timeval tv;
879 for (i = 0; i < sockets_alloc; i++) {
880 switch (sockets[i].type) {
882 case AUTH_CONNECTION:
883 n = MAX(n, sockets[i].fd);
888 fatal("Unknown socket type %d", sockets[i].type);
893 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
894 if (*fdrp == NULL || sz > *nallocp) {
904 debug("XXX shrink: %d < %d", n, *fdl);
906 memset(*fdrp, 0, sz);
907 memset(*fdwp, 0, sz);
909 for (i = 0; i < sockets_alloc; i++) {
910 switch (sockets[i].type) {
912 case AUTH_CONNECTION:
913 FD_SET(sockets[i].fd, *fdrp);
914 if (buffer_len(&sockets[i].output) > 0)
915 FD_SET(sockets[i].fd, *fdwp);
922 if (parent_alive_interval != 0)
923 deadline = (deadline == 0) ? parent_alive_interval :
924 MIN(deadline, parent_alive_interval);
928 tv.tv_sec = deadline;
936 after_select(fd_set *readset, fd_set *writeset)
938 struct sockaddr_un sunaddr;
946 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
947 switch (sockets[i].type) {
951 if (FD_ISSET(sockets[i].fd, readset)) {
952 slen = sizeof(sunaddr);
953 sock = accept(sockets[i].fd,
954 (struct sockaddr *)&sunaddr, &slen);
956 error("accept from AUTH_SOCKET: %s",
960 if (getpeereid(sock, &euid, &egid) < 0) {
961 error("getpeereid %d failed: %s",
962 sock, strerror(errno));
966 if ((euid != 0) && (getuid() != euid)) {
967 error("uid mismatch: "
968 "peer euid %u != uid %u",
969 (u_int) euid, (u_int) getuid());
973 new_socket(AUTH_CONNECTION, sock);
976 case AUTH_CONNECTION:
977 if (buffer_len(&sockets[i].output) > 0 &&
978 FD_ISSET(sockets[i].fd, writeset)) {
979 len = write(sockets[i].fd,
980 buffer_ptr(&sockets[i].output),
981 buffer_len(&sockets[i].output));
982 if (len == -1 && (errno == EAGAIN ||
983 errno == EWOULDBLOCK ||
987 close_socket(&sockets[i]);
990 buffer_consume(&sockets[i].output, len);
992 if (FD_ISSET(sockets[i].fd, readset)) {
993 len = read(sockets[i].fd, buf, sizeof(buf));
994 if (len == -1 && (errno == EAGAIN ||
995 errno == EWOULDBLOCK ||
999 close_socket(&sockets[i]);
1002 buffer_append(&sockets[i].input, buf, len);
1003 process_message(&sockets[i]);
1007 fatal("Unknown type %d", sockets[i].type);
1012 cleanup_socket(void)
1015 unlink(socket_name);
1029 cleanup_handler(int sig)
1032 #ifdef ENABLE_PKCS11
1039 check_parent_exists(void)
1041 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1042 /* printf("Parent has died - Authentication agent exiting.\n"); */
1051 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1053 fprintf(stderr, "Options:\n");
1054 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1055 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1056 fprintf(stderr, " -k Kill the current agent.\n");
1057 fprintf(stderr, " -d Debug mode.\n");
1058 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1059 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1064 main(int ac, char **av)
1066 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1067 int sock, fd, ch, result, saved_errno;
1069 char *shell, *format, *pidstr, *agentsocket = NULL;
1070 fd_set *readsetp = NULL, *writesetp = NULL;
1071 struct sockaddr_un sunaddr;
1072 #ifdef HAVE_SETRLIMIT
1077 extern char *optarg;
1079 char pidstrbuf[1 + 3 * sizeof pid];
1080 struct timeval *tvp = NULL;
1083 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1091 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1092 /* Disable ptrace on Linux without sgid bit */
1093 prctl(PR_SET_DUMPABLE, 0);
1096 SSLeay_add_all_algorithms();
1098 __progname = ssh_get_progname(av[0]);
1102 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1123 agentsocket = optarg;
1126 if ((lifetime = convtime(optarg)) == -1) {
1127 fprintf(stderr, "Invalid lifetime\n");
1138 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1141 if (ac == 0 && !c_flag && !s_flag) {
1142 shell = getenv("SHELL");
1143 if (shell != NULL && (len = strlen(shell)) > 2 &&
1144 strncmp(shell + len - 3, "csh", 3) == 0)
1148 const char *errstr = NULL;
1150 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1151 if (pidstr == NULL) {
1152 fprintf(stderr, "%s not set, cannot kill agent\n",
1153 SSH_AGENTPID_ENV_NAME);
1156 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1159 "%s=\"%s\", which is not a good PID: %s\n",
1160 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1163 if (kill(pid, SIGTERM) == -1) {
1167 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1168 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1169 printf(format, SSH_AGENTPID_ENV_NAME);
1170 printf("echo Agent pid %ld killed;\n", (long)pid);
1173 parent_pid = getpid();
1175 if (agentsocket == NULL) {
1176 /* Create private directory for agent socket */
1177 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1178 if (mkdtemp(socket_dir) == NULL) {
1179 perror("mkdtemp: private socket dir");
1182 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1185 /* Try to use specified agent socket */
1186 socket_dir[0] = '\0';
1187 strlcpy(socket_name, agentsocket, sizeof socket_name);
1191 * Create socket early so it will exist before command gets run from
1194 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1197 *socket_name = '\0'; /* Don't unlink any existing file */
1200 memset(&sunaddr, 0, sizeof(sunaddr));
1201 sunaddr.sun_family = AF_UNIX;
1202 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1203 prev_mask = umask(0177);
1204 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1206 *socket_name = '\0'; /* Don't unlink any existing file */
1211 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1217 * Fork, and have the parent execute the command, if any, or present
1218 * the socket data. The child continues as the authentication agent.
1221 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1222 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1223 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1224 SSH_AUTHSOCKET_ENV_NAME);
1225 printf("echo Agent pid %ld;\n", (long)parent_pid);
1233 if (pid != 0) { /* Parent - execute the given command. */
1235 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1237 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1238 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1239 SSH_AUTHSOCKET_ENV_NAME);
1240 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1241 SSH_AGENTPID_ENV_NAME);
1242 printf("echo Agent pid %ld;\n", (long)pid);
1245 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1246 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1255 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1257 if (setsid() == -1) {
1258 error("setsid: %s", strerror(errno));
1263 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1264 /* XXX might close listen socket */
1265 (void)dup2(fd, STDIN_FILENO);
1266 (void)dup2(fd, STDOUT_FILENO);
1267 (void)dup2(fd, STDERR_FILENO);
1272 #ifdef HAVE_SETRLIMIT
1273 /* deny core dumps, since memory contains unencrypted private keys */
1274 rlim.rlim_cur = rlim.rlim_max = 0;
1275 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1276 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1283 #ifdef ENABLE_PKCS11
1286 new_socket(AUTH_SOCKET, sock);
1288 parent_alive_interval = 10;
1291 signal(SIGINT, SIG_IGN);
1292 signal(SIGPIPE, SIG_IGN);
1293 signal(SIGHUP, cleanup_handler);
1294 signal(SIGTERM, cleanup_handler);
1298 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1299 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1300 saved_errno = errno;
1301 if (parent_alive_interval != 0)
1302 check_parent_exists();
1303 (void) reaper(); /* remove expired keys */
1305 if (saved_errno == EINTR)
1307 fatal("select: %s", strerror(saved_errno));
1308 } else if (result > 0)
1309 after_select(readsetp, writesetp);