1 /* $OpenBSD: ssh-agent.c,v 1.177 2013/07/20 01:50:20 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 time_t 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 in seconds (0 == forever) */
139 static long lifetime = 0;
142 * Client connection count; incremented in new_socket() and decremented in
143 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
144 * normally initialized to 1, it will never reach 0. However, if the -x
145 * option is specified, it is initialized to 0 in main(); in that case,
146 * ssh-agent will exit as soon as it has had at least one client but no
149 static int xcount = 1;
152 close_socket(SocketEntry *e)
156 if (e->type == AUTH_CONNECTION) {
157 debug("xcount %d -> %d", xcount, xcount - 1);
163 e->type = AUTH_UNUSED;
164 buffer_free(&e->input);
165 buffer_free(&e->output);
166 buffer_free(&e->request);
176 for (i = 0; i <=2; i++) {
177 TAILQ_INIT(&idtable[i].idlist);
178 idtable[i].nentries = 0;
182 /* return private key table for requested protocol version */
184 idtab_lookup(int version)
186 if (version < 1 || version > 2)
187 fatal("internal error, bad protocol version %d", version);
188 return &idtable[version];
192 free_identity(Identity *id)
200 /* return matching private key for given public key */
202 lookup_identity(Key *key, int version)
206 Idtab *tab = idtab_lookup(version);
207 TAILQ_FOREACH(id, &tab->idlist, next) {
208 if (key_equal(key, id->key))
214 /* Check confirmation of keysign request */
216 confirm_key(Identity *id)
221 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
222 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
230 /* send list of supported public keys to 'client' */
232 process_request_identities(SocketEntry *e, int version)
234 Idtab *tab = idtab_lookup(version);
239 buffer_put_char(&msg, (version == 1) ?
240 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
241 buffer_put_int(&msg, tab->nentries);
242 TAILQ_FOREACH(id, &tab->idlist, next) {
243 if (id->key->type == KEY_RSA1) {
244 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
245 buffer_put_bignum(&msg, id->key->rsa->e);
246 buffer_put_bignum(&msg, id->key->rsa->n);
250 key_to_blob(id->key, &blob, &blen);
251 buffer_put_string(&msg, blob, blen);
254 buffer_put_cstring(&msg, id->comment);
256 buffer_put_int(&e->output, buffer_len(&msg));
257 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
263 process_authentication_challenge1(SocketEntry *e)
265 u_char buf[32], mdbuf[16], session_id[16];
275 key = key_new(KEY_RSA1);
276 if ((challenge = BN_new()) == NULL)
277 fatal("process_authentication_challenge1: BN_new failed");
279 (void) buffer_get_int(&e->request); /* ignored */
280 buffer_get_bignum(&e->request, key->rsa->e);
281 buffer_get_bignum(&e->request, key->rsa->n);
282 buffer_get_bignum(&e->request, challenge);
284 /* Only protocol 1.1 is supported */
285 if (buffer_len(&e->request) == 0)
287 buffer_get(&e->request, session_id, 16);
288 response_type = buffer_get_int(&e->request);
289 if (response_type != 1)
292 id = lookup_identity(key, 1);
293 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
294 Key *private = id->key;
295 /* Decrypt the challenge using the private key. */
296 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
299 /* The response is MD5 of decrypted challenge plus session id. */
300 len = BN_num_bytes(challenge);
301 if (len <= 0 || len > 32) {
302 logit("process_authentication_challenge: bad challenge length %d", len);
306 BN_bn2bin(challenge, buf + 32 - len);
308 MD5_Update(&md, buf, 32);
309 MD5_Update(&md, session_id, 16);
310 MD5_Final(mdbuf, &md);
312 /* Send the response. */
313 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
314 for (i = 0; i < 16; i++)
315 buffer_put_char(&msg, mdbuf[i]);
320 /* Unknown identity or protocol error. Send failure. */
321 buffer_put_char(&msg, SSH_AGENT_FAILURE);
323 buffer_put_int(&e->output, buffer_len(&msg));
324 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
326 BN_clear_free(challenge);
332 process_sign_request2(SocketEntry *e)
334 u_char *blob, *data, *signature = NULL;
335 u_int blen, dlen, slen = 0;
336 extern int datafellows;
344 blob = buffer_get_string(&e->request, &blen);
345 data = buffer_get_string(&e->request, &dlen);
347 flags = buffer_get_int(&e->request);
348 odatafellows = datafellows;
349 if (flags & SSH_AGENT_OLD_SIGNATURE)
350 datafellows = SSH_BUG_SIGBLOB;
352 key = key_from_blob(blob, blen);
354 Identity *id = lookup_identity(key, 2);
355 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
356 ok = key_sign(id->key, &signature, &slen, data, dlen);
361 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
362 buffer_put_string(&msg, signature, slen);
364 buffer_put_char(&msg, SSH_AGENT_FAILURE);
366 buffer_put_int(&e->output, buffer_len(&msg));
367 buffer_append(&e->output, buffer_ptr(&msg),
373 datafellows = odatafellows;
378 process_remove_identity(SocketEntry *e, int version)
387 key = key_new(KEY_RSA1);
388 bits = buffer_get_int(&e->request);
389 buffer_get_bignum(&e->request, key->rsa->e);
390 buffer_get_bignum(&e->request, key->rsa->n);
392 if (bits != key_size(key))
393 logit("Warning: identity keysize mismatch: actual %u, announced %u",
394 key_size(key), bits);
397 blob = buffer_get_string(&e->request, &blen);
398 key = key_from_blob(blob, blen);
403 Identity *id = lookup_identity(key, version);
406 * We have this key. Free the old key. Since we
407 * don't want to leave empty slots in the middle of
408 * the array, we actually free the key there and move
409 * all the entries between the empty slot and the end
412 Idtab *tab = idtab_lookup(version);
413 if (tab->nentries < 1)
414 fatal("process_remove_identity: "
415 "internal error: tab->nentries %d",
417 TAILQ_REMOVE(&tab->idlist, id, next);
424 buffer_put_int(&e->output, 1);
425 buffer_put_char(&e->output,
426 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
430 process_remove_all_identities(SocketEntry *e, int version)
432 Idtab *tab = idtab_lookup(version);
435 /* Loop over all identities and clear the keys. */
436 for (id = TAILQ_FIRST(&tab->idlist); id;
437 id = TAILQ_FIRST(&tab->idlist)) {
438 TAILQ_REMOVE(&tab->idlist, id, next);
442 /* Mark that there are no identities. */
446 buffer_put_int(&e->output, 1);
447 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
450 /* removes expired keys and returns number of seconds until the next expiry */
454 time_t deadline = 0, now = monotime();
459 for (version = 1; version < 3; version++) {
460 tab = idtab_lookup(version);
461 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
462 nxt = TAILQ_NEXT(id, next);
465 if (now >= id->death) {
466 debug("expiring key '%s'", id->comment);
467 TAILQ_REMOVE(&tab->idlist, id, next);
471 deadline = (deadline == 0) ? id->death :
472 MIN(deadline, id->death);
475 if (deadline == 0 || deadline <= now)
478 return (deadline - now);
482 process_add_identity(SocketEntry *e, int version)
484 Idtab *tab = idtab_lookup(version);
486 int type, success = 0, confirm = 0;
487 char *type_name, *comment;
490 #ifdef OPENSSL_HAS_ECC
500 k = key_new_private(KEY_RSA1);
501 (void) buffer_get_int(&e->request); /* ignored */
502 buffer_get_bignum(&e->request, k->rsa->n);
503 buffer_get_bignum(&e->request, k->rsa->e);
504 buffer_get_bignum(&e->request, k->rsa->d);
505 buffer_get_bignum(&e->request, k->rsa->iqmp);
507 /* SSH and SSL have p and q swapped */
508 buffer_get_bignum(&e->request, k->rsa->q); /* p */
509 buffer_get_bignum(&e->request, k->rsa->p); /* q */
511 /* Generate additional parameters */
512 rsa_generate_additional_parameters(k->rsa);
515 type_name = buffer_get_string(&e->request, NULL);
516 type = key_type_from_name(type_name);
519 k = key_new_private(type);
520 buffer_get_bignum2(&e->request, k->dsa->p);
521 buffer_get_bignum2(&e->request, k->dsa->q);
522 buffer_get_bignum2(&e->request, k->dsa->g);
523 buffer_get_bignum2(&e->request, k->dsa->pub_key);
524 buffer_get_bignum2(&e->request, k->dsa->priv_key);
526 case KEY_DSA_CERT_V00:
528 cert = buffer_get_string(&e->request, &len);
529 if ((k = key_from_blob(cert, len)) == NULL)
530 fatal("Certificate parse failed");
533 buffer_get_bignum2(&e->request, k->dsa->priv_key);
535 #ifdef OPENSSL_HAS_ECC
537 k = key_new_private(type);
538 k->ecdsa_nid = key_ecdsa_nid_from_name(type_name);
539 curve = buffer_get_string(&e->request, NULL);
540 if (k->ecdsa_nid != key_curve_name_to_nid(curve))
541 fatal("%s: curve names mismatch", __func__);
543 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
544 if (k->ecdsa == NULL)
545 fatal("%s: EC_KEY_new_by_curve_name failed",
547 q = EC_POINT_new(EC_KEY_get0_group(k->ecdsa));
549 fatal("%s: BN_new failed", __func__);
550 if ((exponent = BN_new()) == NULL)
551 fatal("%s: BN_new failed", __func__);
552 buffer_get_ecpoint(&e->request,
553 EC_KEY_get0_group(k->ecdsa), q);
554 buffer_get_bignum2(&e->request, exponent);
555 if (EC_KEY_set_public_key(k->ecdsa, q) != 1)
556 fatal("%s: EC_KEY_set_public_key failed",
558 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
559 fatal("%s: EC_KEY_set_private_key failed",
561 if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
562 EC_KEY_get0_public_key(k->ecdsa)) != 0)
563 fatal("%s: bad ECDSA public key", __func__);
564 if (key_ec_validate_private(k->ecdsa) != 0)
565 fatal("%s: bad ECDSA private key", __func__);
566 BN_clear_free(exponent);
570 cert = buffer_get_string(&e->request, &len);
571 if ((k = key_from_blob(cert, len)) == NULL)
572 fatal("Certificate parse failed");
575 if ((exponent = BN_new()) == NULL)
576 fatal("%s: BN_new failed", __func__);
577 buffer_get_bignum2(&e->request, exponent);
578 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
579 fatal("%s: EC_KEY_set_private_key failed",
581 if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
582 EC_KEY_get0_public_key(k->ecdsa)) != 0 ||
583 key_ec_validate_private(k->ecdsa) != 0)
584 fatal("%s: bad ECDSA key", __func__);
585 BN_clear_free(exponent);
587 #endif /* OPENSSL_HAS_ECC */
589 k = key_new_private(type);
590 buffer_get_bignum2(&e->request, k->rsa->n);
591 buffer_get_bignum2(&e->request, k->rsa->e);
592 buffer_get_bignum2(&e->request, k->rsa->d);
593 buffer_get_bignum2(&e->request, k->rsa->iqmp);
594 buffer_get_bignum2(&e->request, k->rsa->p);
595 buffer_get_bignum2(&e->request, k->rsa->q);
597 /* Generate additional parameters */
598 rsa_generate_additional_parameters(k->rsa);
600 case KEY_RSA_CERT_V00:
602 cert = buffer_get_string(&e->request, &len);
603 if ((k = key_from_blob(cert, len)) == NULL)
604 fatal("Certificate parse failed");
607 buffer_get_bignum2(&e->request, k->rsa->d);
608 buffer_get_bignum2(&e->request, k->rsa->iqmp);
609 buffer_get_bignum2(&e->request, k->rsa->p);
610 buffer_get_bignum2(&e->request, k->rsa->q);
614 buffer_clear(&e->request);
620 /* enable blinding */
623 case KEY_RSA_CERT_V00:
626 if (RSA_blinding_on(k->rsa, NULL) != 1) {
627 error("process_add_identity: RSA_blinding_on failed");
633 comment = buffer_get_string(&e->request, NULL);
638 while (buffer_len(&e->request)) {
639 switch ((type = buffer_get_char(&e->request))) {
640 case SSH_AGENT_CONSTRAIN_LIFETIME:
641 death = monotime() + buffer_get_int(&e->request);
643 case SSH_AGENT_CONSTRAIN_CONFIRM:
647 error("process_add_identity: "
648 "Unknown constraint type %d", type);
655 if (lifetime && !death)
656 death = monotime() + lifetime;
657 if ((id = lookup_identity(k, version)) == NULL) {
658 id = xcalloc(1, sizeof(Identity));
660 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
661 /* Increment the number of identities. */
667 id->comment = comment;
669 id->confirm = confirm;
671 buffer_put_int(&e->output, 1);
672 buffer_put_char(&e->output,
673 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
676 /* XXX todo: encrypt sensitive data with passphrase */
678 process_lock_agent(SocketEntry *e, int lock)
683 passwd = buffer_get_string(&e->request, NULL);
684 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
686 memset(lock_passwd, 0, strlen(lock_passwd));
690 } else if (!locked && lock) {
692 lock_passwd = xstrdup(passwd);
695 memset(passwd, 0, strlen(passwd));
698 buffer_put_int(&e->output, 1);
699 buffer_put_char(&e->output,
700 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
704 no_identities(SocketEntry *e, u_int type)
709 buffer_put_char(&msg,
710 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
711 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
712 buffer_put_int(&msg, 0);
713 buffer_put_int(&e->output, buffer_len(&msg));
714 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
720 process_add_smartcard_key(SocketEntry *e)
722 char *provider = NULL, *pin;
723 int i, type, version, count = 0, success = 0, confirm = 0;
725 Key **keys = NULL, *k;
729 provider = buffer_get_string(&e->request, NULL);
730 pin = buffer_get_string(&e->request, NULL);
732 while (buffer_len(&e->request)) {
733 switch ((type = buffer_get_char(&e->request))) {
734 case SSH_AGENT_CONSTRAIN_LIFETIME:
735 death = monotime() + buffer_get_int(&e->request);
737 case SSH_AGENT_CONSTRAIN_CONFIRM:
741 error("process_add_smartcard_key: "
742 "Unknown constraint type %d", type);
746 if (lifetime && !death)
747 death = monotime() + lifetime;
749 count = pkcs11_add_provider(provider, pin, &keys);
750 for (i = 0; i < count; i++) {
752 version = k->type == KEY_RSA1 ? 1 : 2;
753 tab = idtab_lookup(version);
754 if (lookup_identity(k, version) == NULL) {
755 id = xcalloc(1, sizeof(Identity));
757 id->provider = xstrdup(provider);
758 id->comment = xstrdup(provider); /* XXX */
760 id->confirm = confirm;
761 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
773 buffer_put_int(&e->output, 1);
774 buffer_put_char(&e->output,
775 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
779 process_remove_smartcard_key(SocketEntry *e)
781 char *provider = NULL, *pin = NULL;
782 int version, success = 0;
786 provider = buffer_get_string(&e->request, NULL);
787 pin = buffer_get_string(&e->request, NULL);
790 for (version = 1; version < 3; version++) {
791 tab = idtab_lookup(version);
792 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
793 nxt = TAILQ_NEXT(id, next);
794 if (!strcmp(provider, id->provider)) {
795 TAILQ_REMOVE(&tab->idlist, id, next);
801 if (pkcs11_del_provider(provider) == 0)
804 error("process_remove_smartcard_key:"
805 " pkcs11_del_provider failed");
807 buffer_put_int(&e->output, 1);
808 buffer_put_char(&e->output,
809 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
811 #endif /* ENABLE_PKCS11 */
813 /* dispatch incoming messages */
816 process_message(SocketEntry *e)
821 if (buffer_len(&e->input) < 5)
822 return; /* Incomplete message. */
823 cp = buffer_ptr(&e->input);
824 msg_len = get_u32(cp);
825 if (msg_len > 256 * 1024) {
829 if (buffer_len(&e->input) < msg_len + 4)
832 /* move the current input to e->request */
833 buffer_consume(&e->input, 4);
834 buffer_clear(&e->request);
835 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
836 buffer_consume(&e->input, msg_len);
837 type = buffer_get_char(&e->request);
839 /* check wheter agent is locked */
840 if (locked && type != SSH_AGENTC_UNLOCK) {
841 buffer_clear(&e->request);
843 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
844 case SSH2_AGENTC_REQUEST_IDENTITIES:
845 /* send empty lists */
846 no_identities(e, type);
849 /* send a fail message for all other request types */
850 buffer_put_int(&e->output, 1);
851 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
856 debug("type %d", type);
858 case SSH_AGENTC_LOCK:
859 case SSH_AGENTC_UNLOCK:
860 process_lock_agent(e, type == SSH_AGENTC_LOCK);
863 case SSH_AGENTC_RSA_CHALLENGE:
864 process_authentication_challenge1(e);
866 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
867 process_request_identities(e, 1);
869 case SSH_AGENTC_ADD_RSA_IDENTITY:
870 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
871 process_add_identity(e, 1);
873 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
874 process_remove_identity(e, 1);
876 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
877 process_remove_all_identities(e, 1);
880 case SSH2_AGENTC_SIGN_REQUEST:
881 process_sign_request2(e);
883 case SSH2_AGENTC_REQUEST_IDENTITIES:
884 process_request_identities(e, 2);
886 case SSH2_AGENTC_ADD_IDENTITY:
887 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
888 process_add_identity(e, 2);
890 case SSH2_AGENTC_REMOVE_IDENTITY:
891 process_remove_identity(e, 2);
893 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
894 process_remove_all_identities(e, 2);
897 case SSH_AGENTC_ADD_SMARTCARD_KEY:
898 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
899 process_add_smartcard_key(e);
901 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
902 process_remove_smartcard_key(e);
904 #endif /* ENABLE_PKCS11 */
906 /* Unknown message. Respond with failure. */
907 error("Unknown message %d", type);
908 buffer_clear(&e->request);
909 buffer_put_int(&e->output, 1);
910 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
916 new_socket(sock_type type, int fd)
918 u_int i, old_alloc, new_alloc;
920 if (type == AUTH_CONNECTION) {
921 debug("xcount %d -> %d", xcount, xcount + 1);
929 for (i = 0; i < sockets_alloc; i++)
930 if (sockets[i].type == AUTH_UNUSED) {
932 buffer_init(&sockets[i].input);
933 buffer_init(&sockets[i].output);
934 buffer_init(&sockets[i].request);
935 sockets[i].type = type;
938 old_alloc = sockets_alloc;
939 new_alloc = sockets_alloc + 10;
940 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
941 for (i = old_alloc; i < new_alloc; i++)
942 sockets[i].type = AUTH_UNUSED;
943 sockets_alloc = new_alloc;
944 sockets[old_alloc].fd = fd;
945 buffer_init(&sockets[old_alloc].input);
946 buffer_init(&sockets[old_alloc].output);
947 buffer_init(&sockets[old_alloc].request);
948 sockets[old_alloc].type = type;
952 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
953 struct timeval **tvpp)
957 static struct timeval tv;
960 for (i = 0; i < sockets_alloc; i++) {
961 switch (sockets[i].type) {
963 case AUTH_CONNECTION:
964 n = MAX(n, sockets[i].fd);
969 fatal("Unknown socket type %d", sockets[i].type);
974 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
975 if (*fdrp == NULL || sz > *nallocp) {
983 debug("XXX shrink: %d < %d", n, *fdl);
985 memset(*fdrp, 0, sz);
986 memset(*fdwp, 0, sz);
988 for (i = 0; i < sockets_alloc; i++) {
989 switch (sockets[i].type) {
991 case AUTH_CONNECTION:
992 FD_SET(sockets[i].fd, *fdrp);
993 if (buffer_len(&sockets[i].output) > 0)
994 FD_SET(sockets[i].fd, *fdwp);
1000 deadline = reaper();
1001 if (parent_alive_interval != 0)
1002 deadline = (deadline == 0) ? parent_alive_interval :
1003 MIN(deadline, parent_alive_interval);
1004 if (deadline == 0) {
1007 tv.tv_sec = deadline;
1015 after_select(fd_set *readset, fd_set *writeset)
1017 struct sockaddr_un sunaddr;
1021 u_int i, orig_alloc;
1025 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1026 switch (sockets[i].type) {
1030 if (FD_ISSET(sockets[i].fd, readset)) {
1031 slen = sizeof(sunaddr);
1032 sock = accept(sockets[i].fd,
1033 (struct sockaddr *)&sunaddr, &slen);
1035 error("accept from AUTH_SOCKET: %s",
1039 if (getpeereid(sock, &euid, &egid) < 0) {
1040 error("getpeereid %d failed: %s",
1041 sock, strerror(errno));
1045 if ((euid != 0) && (getuid() != euid)) {
1046 error("uid mismatch: "
1047 "peer euid %u != uid %u",
1048 (u_int) euid, (u_int) getuid());
1052 new_socket(AUTH_CONNECTION, sock);
1055 case AUTH_CONNECTION:
1056 if (buffer_len(&sockets[i].output) > 0 &&
1057 FD_ISSET(sockets[i].fd, writeset)) {
1058 len = write(sockets[i].fd,
1059 buffer_ptr(&sockets[i].output),
1060 buffer_len(&sockets[i].output));
1061 if (len == -1 && (errno == EAGAIN ||
1062 errno == EWOULDBLOCK ||
1066 close_socket(&sockets[i]);
1069 buffer_consume(&sockets[i].output, len);
1071 if (FD_ISSET(sockets[i].fd, readset)) {
1072 len = read(sockets[i].fd, buf, sizeof(buf));
1073 if (len == -1 && (errno == EAGAIN ||
1074 errno == EWOULDBLOCK ||
1078 close_socket(&sockets[i]);
1081 buffer_append(&sockets[i].input, buf, len);
1082 process_message(&sockets[i]);
1086 fatal("Unknown type %d", sockets[i].type);
1091 cleanup_socket(void)
1094 unlink(socket_name);
1108 cleanup_handler(int sig)
1111 #ifdef ENABLE_PKCS11
1118 check_parent_exists(void)
1121 * If our parent has exited then getppid() will return (pid_t)1,
1122 * so testing for that should be safe.
1124 if (parent_pid != -1 && getppid() != parent_pid) {
1125 /* printf("Parent has died - Authentication agent exiting.\n"); */
1134 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1136 fprintf(stderr, "Options:\n");
1137 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1138 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1139 fprintf(stderr, " -k Kill the current agent.\n");
1140 fprintf(stderr, " -d Debug mode.\n");
1141 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1142 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1143 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1148 main(int ac, char **av)
1150 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1151 int sock, fd, ch, result, saved_errno;
1153 char *shell, *format, *pidstr, *agentsocket = NULL;
1154 fd_set *readsetp = NULL, *writesetp = NULL;
1155 struct sockaddr_un sunaddr;
1156 #ifdef HAVE_SETRLIMIT
1161 extern char *optarg;
1163 char pidstrbuf[1 + 3 * sizeof pid];
1164 struct timeval *tvp = NULL;
1167 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1175 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1176 /* Disable ptrace on Linux without sgid bit */
1177 prctl(PR_SET_DUMPABLE, 0);
1180 OpenSSL_add_all_algorithms();
1182 __progname = ssh_get_progname(av[0]);
1185 while ((ch = getopt(ac, av, "cdksa:t:x")) != -1) {
1206 agentsocket = optarg;
1209 if ((lifetime = convtime(optarg)) == -1) {
1210 fprintf(stderr, "Invalid lifetime\n");
1224 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1227 if (ac == 0 && !c_flag && !s_flag) {
1228 shell = getenv("SHELL");
1229 if (shell != NULL && (len = strlen(shell)) > 2 &&
1230 strncmp(shell + len - 3, "csh", 3) == 0)
1234 const char *errstr = NULL;
1236 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1237 if (pidstr == NULL) {
1238 fprintf(stderr, "%s not set, cannot kill agent\n",
1239 SSH_AGENTPID_ENV_NAME);
1242 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1245 "%s=\"%s\", which is not a good PID: %s\n",
1246 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1249 if (kill(pid, SIGTERM) == -1) {
1253 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1254 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1255 printf(format, SSH_AGENTPID_ENV_NAME);
1256 printf("echo Agent pid %ld killed;\n", (long)pid);
1259 parent_pid = getpid();
1261 if (agentsocket == NULL) {
1262 /* Create private directory for agent socket */
1263 mktemp_proto(socket_dir, sizeof(socket_dir));
1264 if (mkdtemp(socket_dir) == NULL) {
1265 perror("mkdtemp: private socket dir");
1268 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1271 /* Try to use specified agent socket */
1272 socket_dir[0] = '\0';
1273 strlcpy(socket_name, agentsocket, sizeof socket_name);
1277 * Create socket early so it will exist before command gets run from
1280 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1283 *socket_name = '\0'; /* Don't unlink any existing file */
1286 memset(&sunaddr, 0, sizeof(sunaddr));
1287 sunaddr.sun_family = AF_UNIX;
1288 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1289 prev_mask = umask(0177);
1290 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1292 *socket_name = '\0'; /* Don't unlink any existing file */
1297 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1303 * Fork, and have the parent execute the command, if any, or present
1304 * the socket data. The child continues as the authentication agent.
1307 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1308 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1309 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1310 SSH_AUTHSOCKET_ENV_NAME);
1311 printf("echo Agent pid %ld;\n", (long)parent_pid);
1319 if (pid != 0) { /* Parent - execute the given command. */
1321 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1323 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1324 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1325 SSH_AUTHSOCKET_ENV_NAME);
1326 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1327 SSH_AGENTPID_ENV_NAME);
1328 printf("echo Agent pid %ld;\n", (long)pid);
1331 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1332 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1341 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1343 if (setsid() == -1) {
1344 error("setsid: %s", strerror(errno));
1349 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1350 /* XXX might close listen socket */
1351 (void)dup2(fd, STDIN_FILENO);
1352 (void)dup2(fd, STDOUT_FILENO);
1353 (void)dup2(fd, STDERR_FILENO);
1358 #ifdef HAVE_SETRLIMIT
1359 /* deny core dumps, since memory contains unencrypted private keys */
1360 rlim.rlim_cur = rlim.rlim_max = 0;
1361 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1362 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1369 #ifdef ENABLE_PKCS11
1372 new_socket(AUTH_SOCKET, sock);
1374 parent_alive_interval = 10;
1376 signal(SIGPIPE, SIG_IGN);
1377 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1378 signal(SIGHUP, cleanup_handler);
1379 signal(SIGTERM, cleanup_handler);
1383 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1384 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1385 saved_errno = errno;
1386 if (parent_alive_interval != 0)
1387 check_parent_exists();
1388 (void) reaper(); /* remove expired keys */
1390 if (saved_errno == EINTR)
1392 fatal("select: %s", strerror(saved_errno));
1393 } else if (result > 0)
1394 after_select(readsetp, writesetp);