1 /* $OpenBSD: ssh-agent.c,v 1.172 2011/06/03 01:37:40 dtucker 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 * 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)
195 if (id->provider != NULL)
201 /* return matching private key for given public key */
203 lookup_identity(Key *key, int version)
207 Idtab *tab = idtab_lookup(version);
208 TAILQ_FOREACH(id, &tab->idlist, next) {
209 if (key_equal(key, id->key))
215 /* Check confirmation of keysign request */
217 confirm_key(Identity *id)
222 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
223 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
231 /* send list of supported public keys to 'client' */
233 process_request_identities(SocketEntry *e, int version)
235 Idtab *tab = idtab_lookup(version);
240 buffer_put_char(&msg, (version == 1) ?
241 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
242 buffer_put_int(&msg, tab->nentries);
243 TAILQ_FOREACH(id, &tab->idlist, next) {
244 if (id->key->type == KEY_RSA1) {
245 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
246 buffer_put_bignum(&msg, id->key->rsa->e);
247 buffer_put_bignum(&msg, id->key->rsa->n);
251 key_to_blob(id->key, &blob, &blen);
252 buffer_put_string(&msg, blob, blen);
255 buffer_put_cstring(&msg, id->comment);
257 buffer_put_int(&e->output, buffer_len(&msg));
258 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
264 process_authentication_challenge1(SocketEntry *e)
266 u_char buf[32], mdbuf[16], session_id[16];
276 key = key_new(KEY_RSA1);
277 if ((challenge = BN_new()) == NULL)
278 fatal("process_authentication_challenge1: BN_new failed");
280 (void) buffer_get_int(&e->request); /* ignored */
281 buffer_get_bignum(&e->request, key->rsa->e);
282 buffer_get_bignum(&e->request, key->rsa->n);
283 buffer_get_bignum(&e->request, challenge);
285 /* Only protocol 1.1 is supported */
286 if (buffer_len(&e->request) == 0)
288 buffer_get(&e->request, session_id, 16);
289 response_type = buffer_get_int(&e->request);
290 if (response_type != 1)
293 id = lookup_identity(key, 1);
294 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
295 Key *private = id->key;
296 /* Decrypt the challenge using the private key. */
297 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
300 /* The response is MD5 of decrypted challenge plus session id. */
301 len = BN_num_bytes(challenge);
302 if (len <= 0 || len > 32) {
303 logit("process_authentication_challenge: bad challenge length %d", len);
307 BN_bn2bin(challenge, buf + 32 - len);
309 MD5_Update(&md, buf, 32);
310 MD5_Update(&md, session_id, 16);
311 MD5_Final(mdbuf, &md);
313 /* Send the response. */
314 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
315 for (i = 0; i < 16; i++)
316 buffer_put_char(&msg, mdbuf[i]);
321 /* Unknown identity or protocol error. Send failure. */
322 buffer_put_char(&msg, SSH_AGENT_FAILURE);
324 buffer_put_int(&e->output, buffer_len(&msg));
325 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
327 BN_clear_free(challenge);
333 process_sign_request2(SocketEntry *e)
335 u_char *blob, *data, *signature = NULL;
336 u_int blen, dlen, slen = 0;
337 extern int datafellows;
345 blob = buffer_get_string(&e->request, &blen);
346 data = buffer_get_string(&e->request, &dlen);
348 flags = buffer_get_int(&e->request);
349 odatafellows = datafellows;
350 if (flags & SSH_AGENT_OLD_SIGNATURE)
351 datafellows = SSH_BUG_SIGBLOB;
353 key = key_from_blob(blob, blen);
355 Identity *id = lookup_identity(key, 2);
356 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
357 ok = key_sign(id->key, &signature, &slen, data, dlen);
362 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
363 buffer_put_string(&msg, signature, slen);
365 buffer_put_char(&msg, SSH_AGENT_FAILURE);
367 buffer_put_int(&e->output, buffer_len(&msg));
368 buffer_append(&e->output, buffer_ptr(&msg),
373 if (signature != NULL)
375 datafellows = odatafellows;
380 process_remove_identity(SocketEntry *e, int version)
389 key = key_new(KEY_RSA1);
390 bits = buffer_get_int(&e->request);
391 buffer_get_bignum(&e->request, key->rsa->e);
392 buffer_get_bignum(&e->request, key->rsa->n);
394 if (bits != key_size(key))
395 logit("Warning: identity keysize mismatch: actual %u, announced %u",
396 key_size(key), bits);
399 blob = buffer_get_string(&e->request, &blen);
400 key = key_from_blob(blob, blen);
405 Identity *id = lookup_identity(key, version);
408 * We have this key. Free the old key. Since we
409 * don't want to leave empty slots in the middle of
410 * the array, we actually free the key there and move
411 * all the entries between the empty slot and the end
414 Idtab *tab = idtab_lookup(version);
415 if (tab->nentries < 1)
416 fatal("process_remove_identity: "
417 "internal error: tab->nentries %d",
419 TAILQ_REMOVE(&tab->idlist, id, next);
426 buffer_put_int(&e->output, 1);
427 buffer_put_char(&e->output,
428 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
432 process_remove_all_identities(SocketEntry *e, int version)
434 Idtab *tab = idtab_lookup(version);
437 /* Loop over all identities and clear the keys. */
438 for (id = TAILQ_FIRST(&tab->idlist); id;
439 id = TAILQ_FIRST(&tab->idlist)) {
440 TAILQ_REMOVE(&tab->idlist, id, next);
444 /* Mark that there are no identities. */
448 buffer_put_int(&e->output, 1);
449 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
452 /* removes expired keys and returns number of seconds until the next expiry */
456 u_int deadline = 0, now = time(NULL);
461 for (version = 1; version < 3; version++) {
462 tab = idtab_lookup(version);
463 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
464 nxt = TAILQ_NEXT(id, next);
467 if (now >= id->death) {
468 debug("expiring key '%s'", id->comment);
469 TAILQ_REMOVE(&tab->idlist, id, next);
473 deadline = (deadline == 0) ? id->death :
474 MIN(deadline, id->death);
477 if (deadline == 0 || deadline <= now)
480 return (deadline - now);
484 process_add_identity(SocketEntry *e, int version)
486 Idtab *tab = idtab_lookup(version);
488 int type, success = 0, death = 0, confirm = 0;
489 char *type_name, *comment;
491 #ifdef OPENSSL_HAS_ECC
501 k = key_new_private(KEY_RSA1);
502 (void) buffer_get_int(&e->request); /* ignored */
503 buffer_get_bignum(&e->request, k->rsa->n);
504 buffer_get_bignum(&e->request, k->rsa->e);
505 buffer_get_bignum(&e->request, k->rsa->d);
506 buffer_get_bignum(&e->request, k->rsa->iqmp);
508 /* SSH and SSL have p and q swapped */
509 buffer_get_bignum(&e->request, k->rsa->q); /* p */
510 buffer_get_bignum(&e->request, k->rsa->p); /* q */
512 /* Generate additional parameters */
513 rsa_generate_additional_parameters(k->rsa);
516 type_name = buffer_get_string(&e->request, NULL);
517 type = key_type_from_name(type_name);
520 k = key_new_private(type);
521 buffer_get_bignum2(&e->request, k->dsa->p);
522 buffer_get_bignum2(&e->request, k->dsa->q);
523 buffer_get_bignum2(&e->request, k->dsa->g);
524 buffer_get_bignum2(&e->request, k->dsa->pub_key);
525 buffer_get_bignum2(&e->request, k->dsa->priv_key);
527 case KEY_DSA_CERT_V00:
529 cert = buffer_get_string(&e->request, &len);
530 if ((k = key_from_blob(cert, len)) == NULL)
531 fatal("Certificate parse failed");
534 buffer_get_bignum2(&e->request, k->dsa->priv_key);
536 #ifdef OPENSSL_HAS_ECC
538 k = key_new_private(type);
539 k->ecdsa_nid = key_ecdsa_nid_from_name(type_name);
540 curve = buffer_get_string(&e->request, NULL);
541 if (k->ecdsa_nid != key_curve_name_to_nid(curve))
542 fatal("%s: curve names mismatch", __func__);
544 k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
545 if (k->ecdsa == NULL)
546 fatal("%s: EC_KEY_new_by_curve_name failed",
548 q = EC_POINT_new(EC_KEY_get0_group(k->ecdsa));
550 fatal("%s: BN_new failed", __func__);
551 if ((exponent = BN_new()) == NULL)
552 fatal("%s: BN_new failed", __func__);
553 buffer_get_ecpoint(&e->request,
554 EC_KEY_get0_group(k->ecdsa), q);
555 buffer_get_bignum2(&e->request, exponent);
556 if (EC_KEY_set_public_key(k->ecdsa, q) != 1)
557 fatal("%s: EC_KEY_set_public_key failed",
559 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
560 fatal("%s: EC_KEY_set_private_key failed",
562 if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
563 EC_KEY_get0_public_key(k->ecdsa)) != 0)
564 fatal("%s: bad ECDSA public key", __func__);
565 if (key_ec_validate_private(k->ecdsa) != 0)
566 fatal("%s: bad ECDSA private key", __func__);
567 BN_clear_free(exponent);
571 cert = buffer_get_string(&e->request, &len);
572 if ((k = key_from_blob(cert, len)) == NULL)
573 fatal("Certificate parse failed");
576 if ((exponent = BN_new()) == NULL)
577 fatal("%s: BN_new failed", __func__);
578 buffer_get_bignum2(&e->request, exponent);
579 if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
580 fatal("%s: EC_KEY_set_private_key failed",
582 if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
583 EC_KEY_get0_public_key(k->ecdsa)) != 0 ||
584 key_ec_validate_private(k->ecdsa) != 0)
585 fatal("%s: bad ECDSA key", __func__);
586 BN_clear_free(exponent);
588 #endif /* OPENSSL_HAS_ECC */
590 k = key_new_private(type);
591 buffer_get_bignum2(&e->request, k->rsa->n);
592 buffer_get_bignum2(&e->request, k->rsa->e);
593 buffer_get_bignum2(&e->request, k->rsa->d);
594 buffer_get_bignum2(&e->request, k->rsa->iqmp);
595 buffer_get_bignum2(&e->request, k->rsa->p);
596 buffer_get_bignum2(&e->request, k->rsa->q);
598 /* Generate additional parameters */
599 rsa_generate_additional_parameters(k->rsa);
601 case KEY_RSA_CERT_V00:
603 cert = buffer_get_string(&e->request, &len);
604 if ((k = key_from_blob(cert, len)) == NULL)
605 fatal("Certificate parse failed");
608 buffer_get_bignum2(&e->request, k->rsa->d);
609 buffer_get_bignum2(&e->request, k->rsa->iqmp);
610 buffer_get_bignum2(&e->request, k->rsa->p);
611 buffer_get_bignum2(&e->request, k->rsa->q);
615 buffer_clear(&e->request);
621 /* enable blinding */
624 case KEY_RSA_CERT_V00:
627 if (RSA_blinding_on(k->rsa, NULL) != 1) {
628 error("process_add_identity: RSA_blinding_on failed");
634 comment = buffer_get_string(&e->request, NULL);
639 while (buffer_len(&e->request)) {
640 switch ((type = buffer_get_char(&e->request))) {
641 case SSH_AGENT_CONSTRAIN_LIFETIME:
642 death = time(NULL) + buffer_get_int(&e->request);
644 case SSH_AGENT_CONSTRAIN_CONFIRM:
648 error("process_add_identity: "
649 "Unknown constraint type %d", type);
656 if (lifetime && !death)
657 death = time(NULL) + lifetime;
658 if ((id = lookup_identity(k, version)) == NULL) {
659 id = xcalloc(1, sizeof(Identity));
661 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
662 /* Increment the number of identities. */
668 id->comment = comment;
670 id->confirm = confirm;
672 buffer_put_int(&e->output, 1);
673 buffer_put_char(&e->output,
674 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
677 /* XXX todo: encrypt sensitive data with passphrase */
679 process_lock_agent(SocketEntry *e, int lock)
684 passwd = buffer_get_string(&e->request, NULL);
685 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
687 memset(lock_passwd, 0, strlen(lock_passwd));
691 } else if (!locked && lock) {
693 lock_passwd = xstrdup(passwd);
696 memset(passwd, 0, strlen(passwd));
699 buffer_put_int(&e->output, 1);
700 buffer_put_char(&e->output,
701 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
705 no_identities(SocketEntry *e, u_int type)
710 buffer_put_char(&msg,
711 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
712 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
713 buffer_put_int(&msg, 0);
714 buffer_put_int(&e->output, buffer_len(&msg));
715 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
721 process_add_smartcard_key(SocketEntry *e)
723 char *provider = NULL, *pin;
724 int i, type, version, count = 0, success = 0, death = 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 = time(NULL) + 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 = time(NULL) + 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);
776 buffer_put_int(&e->output, 1);
777 buffer_put_char(&e->output,
778 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
782 process_remove_smartcard_key(SocketEntry *e)
784 char *provider = NULL, *pin = NULL;
785 int version, success = 0;
789 provider = buffer_get_string(&e->request, NULL);
790 pin = buffer_get_string(&e->request, NULL);
793 for (version = 1; version < 3; version++) {
794 tab = idtab_lookup(version);
795 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
796 nxt = TAILQ_NEXT(id, next);
797 if (!strcmp(provider, id->provider)) {
798 TAILQ_REMOVE(&tab->idlist, id, next);
804 if (pkcs11_del_provider(provider) == 0)
807 error("process_remove_smartcard_key:"
808 " pkcs11_del_provider failed");
810 buffer_put_int(&e->output, 1);
811 buffer_put_char(&e->output,
812 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
814 #endif /* ENABLE_PKCS11 */
816 /* dispatch incoming messages */
819 process_message(SocketEntry *e)
824 if (buffer_len(&e->input) < 5)
825 return; /* Incomplete message. */
826 cp = buffer_ptr(&e->input);
827 msg_len = get_u32(cp);
828 if (msg_len > 256 * 1024) {
832 if (buffer_len(&e->input) < msg_len + 4)
835 /* move the current input to e->request */
836 buffer_consume(&e->input, 4);
837 buffer_clear(&e->request);
838 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
839 buffer_consume(&e->input, msg_len);
840 type = buffer_get_char(&e->request);
842 /* check wheter agent is locked */
843 if (locked && type != SSH_AGENTC_UNLOCK) {
844 buffer_clear(&e->request);
846 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
847 case SSH2_AGENTC_REQUEST_IDENTITIES:
848 /* send empty lists */
849 no_identities(e, type);
852 /* send a fail message for all other request types */
853 buffer_put_int(&e->output, 1);
854 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
859 debug("type %d", type);
861 case SSH_AGENTC_LOCK:
862 case SSH_AGENTC_UNLOCK:
863 process_lock_agent(e, type == SSH_AGENTC_LOCK);
866 case SSH_AGENTC_RSA_CHALLENGE:
867 process_authentication_challenge1(e);
869 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
870 process_request_identities(e, 1);
872 case SSH_AGENTC_ADD_RSA_IDENTITY:
873 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
874 process_add_identity(e, 1);
876 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
877 process_remove_identity(e, 1);
879 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
880 process_remove_all_identities(e, 1);
883 case SSH2_AGENTC_SIGN_REQUEST:
884 process_sign_request2(e);
886 case SSH2_AGENTC_REQUEST_IDENTITIES:
887 process_request_identities(e, 2);
889 case SSH2_AGENTC_ADD_IDENTITY:
890 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
891 process_add_identity(e, 2);
893 case SSH2_AGENTC_REMOVE_IDENTITY:
894 process_remove_identity(e, 2);
896 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
897 process_remove_all_identities(e, 2);
900 case SSH_AGENTC_ADD_SMARTCARD_KEY:
901 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
902 process_add_smartcard_key(e);
904 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
905 process_remove_smartcard_key(e);
907 #endif /* ENABLE_PKCS11 */
909 /* Unknown message. Respond with failure. */
910 error("Unknown message %d", type);
911 buffer_clear(&e->request);
912 buffer_put_int(&e->output, 1);
913 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
919 new_socket(sock_type type, int fd)
921 u_int i, old_alloc, new_alloc;
923 if (type == AUTH_CONNECTION) {
924 debug("xcount %d -> %d", xcount, xcount + 1);
932 for (i = 0; i < sockets_alloc; i++)
933 if (sockets[i].type == AUTH_UNUSED) {
935 buffer_init(&sockets[i].input);
936 buffer_init(&sockets[i].output);
937 buffer_init(&sockets[i].request);
938 sockets[i].type = type;
941 old_alloc = sockets_alloc;
942 new_alloc = sockets_alloc + 10;
943 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
944 for (i = old_alloc; i < new_alloc; i++)
945 sockets[i].type = AUTH_UNUSED;
946 sockets_alloc = new_alloc;
947 sockets[old_alloc].fd = fd;
948 buffer_init(&sockets[old_alloc].input);
949 buffer_init(&sockets[old_alloc].output);
950 buffer_init(&sockets[old_alloc].request);
951 sockets[old_alloc].type = type;
955 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
956 struct timeval **tvpp)
958 u_int i, sz, deadline;
960 static struct timeval tv;
962 for (i = 0; i < sockets_alloc; i++) {
963 switch (sockets[i].type) {
965 case AUTH_CONNECTION:
966 n = MAX(n, sockets[i].fd);
971 fatal("Unknown socket type %d", sockets[i].type);
976 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
977 if (*fdrp == NULL || sz > *nallocp) {
987 debug("XXX shrink: %d < %d", n, *fdl);
989 memset(*fdrp, 0, sz);
990 memset(*fdwp, 0, sz);
992 for (i = 0; i < sockets_alloc; i++) {
993 switch (sockets[i].type) {
995 case AUTH_CONNECTION:
996 FD_SET(sockets[i].fd, *fdrp);
997 if (buffer_len(&sockets[i].output) > 0)
998 FD_SET(sockets[i].fd, *fdwp);
1004 deadline = reaper();
1005 if (parent_alive_interval != 0)
1006 deadline = (deadline == 0) ? parent_alive_interval :
1007 MIN(deadline, parent_alive_interval);
1008 if (deadline == 0) {
1011 tv.tv_sec = deadline;
1019 after_select(fd_set *readset, fd_set *writeset)
1021 struct sockaddr_un sunaddr;
1025 u_int i, orig_alloc;
1029 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1030 switch (sockets[i].type) {
1034 if (FD_ISSET(sockets[i].fd, readset)) {
1035 slen = sizeof(sunaddr);
1036 sock = accept(sockets[i].fd,
1037 (struct sockaddr *)&sunaddr, &slen);
1039 error("accept from AUTH_SOCKET: %s",
1043 if (getpeereid(sock, &euid, &egid) < 0) {
1044 error("getpeereid %d failed: %s",
1045 sock, strerror(errno));
1049 if ((euid != 0) && (getuid() != euid)) {
1050 error("uid mismatch: "
1051 "peer euid %u != uid %u",
1052 (u_int) euid, (u_int) getuid());
1056 new_socket(AUTH_CONNECTION, sock);
1059 case AUTH_CONNECTION:
1060 if (buffer_len(&sockets[i].output) > 0 &&
1061 FD_ISSET(sockets[i].fd, writeset)) {
1062 len = write(sockets[i].fd,
1063 buffer_ptr(&sockets[i].output),
1064 buffer_len(&sockets[i].output));
1065 if (len == -1 && (errno == EAGAIN ||
1066 errno == EWOULDBLOCK ||
1070 close_socket(&sockets[i]);
1073 buffer_consume(&sockets[i].output, len);
1075 if (FD_ISSET(sockets[i].fd, readset)) {
1076 len = read(sockets[i].fd, buf, sizeof(buf));
1077 if (len == -1 && (errno == EAGAIN ||
1078 errno == EWOULDBLOCK ||
1082 close_socket(&sockets[i]);
1085 buffer_append(&sockets[i].input, buf, len);
1086 process_message(&sockets[i]);
1090 fatal("Unknown type %d", sockets[i].type);
1095 cleanup_socket(void)
1098 unlink(socket_name);
1112 cleanup_handler(int sig)
1115 #ifdef ENABLE_PKCS11
1122 check_parent_exists(void)
1125 * If our parent has exited then getppid() will return (pid_t)1,
1126 * so testing for that should be safe.
1128 if (parent_pid != -1 && getppid() != parent_pid) {
1129 /* printf("Parent has died - Authentication agent exiting.\n"); */
1138 fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1140 fprintf(stderr, "Options:\n");
1141 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
1142 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1143 fprintf(stderr, " -k Kill the current agent.\n");
1144 fprintf(stderr, " -d Debug mode.\n");
1145 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1146 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1147 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1152 main(int ac, char **av)
1154 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1155 int sock, fd, ch, result, saved_errno;
1157 char *shell, *format, *pidstr, *agentsocket = NULL;
1158 fd_set *readsetp = NULL, *writesetp = NULL;
1159 struct sockaddr_un sunaddr;
1160 #ifdef HAVE_SETRLIMIT
1165 extern char *optarg;
1167 char pidstrbuf[1 + 3 * sizeof pid];
1168 struct timeval *tvp = NULL;
1171 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1179 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1180 /* Disable ptrace on Linux without sgid bit */
1181 prctl(PR_SET_DUMPABLE, 0);
1184 OpenSSL_add_all_algorithms();
1186 __progname = ssh_get_progname(av[0]);
1189 while ((ch = getopt(ac, av, "cdksa:t:x")) != -1) {
1210 agentsocket = optarg;
1213 if ((lifetime = convtime(optarg)) == -1) {
1214 fprintf(stderr, "Invalid lifetime\n");
1228 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1231 if (ac == 0 && !c_flag && !s_flag) {
1232 shell = getenv("SHELL");
1233 if (shell != NULL && (len = strlen(shell)) > 2 &&
1234 strncmp(shell + len - 3, "csh", 3) == 0)
1238 const char *errstr = NULL;
1240 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1241 if (pidstr == NULL) {
1242 fprintf(stderr, "%s not set, cannot kill agent\n",
1243 SSH_AGENTPID_ENV_NAME);
1246 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1249 "%s=\"%s\", which is not a good PID: %s\n",
1250 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1253 if (kill(pid, SIGTERM) == -1) {
1257 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1258 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1259 printf(format, SSH_AGENTPID_ENV_NAME);
1260 printf("echo Agent pid %ld killed;\n", (long)pid);
1263 parent_pid = getpid();
1265 if (agentsocket == NULL) {
1266 /* Create private directory for agent socket */
1267 mktemp_proto(socket_dir, sizeof(socket_dir));
1268 if (mkdtemp(socket_dir) == NULL) {
1269 perror("mkdtemp: private socket dir");
1272 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1275 /* Try to use specified agent socket */
1276 socket_dir[0] = '\0';
1277 strlcpy(socket_name, agentsocket, sizeof socket_name);
1281 * Create socket early so it will exist before command gets run from
1284 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1287 *socket_name = '\0'; /* Don't unlink any existing file */
1290 memset(&sunaddr, 0, sizeof(sunaddr));
1291 sunaddr.sun_family = AF_UNIX;
1292 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1293 prev_mask = umask(0177);
1294 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1296 *socket_name = '\0'; /* Don't unlink any existing file */
1301 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1307 * Fork, and have the parent execute the command, if any, or present
1308 * the socket data. The child continues as the authentication agent.
1311 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1312 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1313 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1314 SSH_AUTHSOCKET_ENV_NAME);
1315 printf("echo Agent pid %ld;\n", (long)parent_pid);
1323 if (pid != 0) { /* Parent - execute the given command. */
1325 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1327 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1328 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1329 SSH_AUTHSOCKET_ENV_NAME);
1330 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1331 SSH_AGENTPID_ENV_NAME);
1332 printf("echo Agent pid %ld;\n", (long)pid);
1335 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1336 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1345 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1347 if (setsid() == -1) {
1348 error("setsid: %s", strerror(errno));
1353 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1354 /* XXX might close listen socket */
1355 (void)dup2(fd, STDIN_FILENO);
1356 (void)dup2(fd, STDOUT_FILENO);
1357 (void)dup2(fd, STDERR_FILENO);
1362 #ifdef HAVE_SETRLIMIT
1363 /* deny core dumps, since memory contains unencrypted private keys */
1364 rlim.rlim_cur = rlim.rlim_max = 0;
1365 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1366 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1373 #ifdef ENABLE_PKCS11
1376 new_socket(AUTH_SOCKET, sock);
1378 parent_alive_interval = 10;
1380 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1381 signal(SIGPIPE, SIG_IGN);
1382 signal(SIGHUP, cleanup_handler);
1383 signal(SIGTERM, cleanup_handler);
1387 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1388 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1389 saved_errno = errno;
1390 if (parent_alive_interval != 0)
1391 check_parent_exists();
1392 (void) reaper(); /* remove expired keys */
1394 if (saved_errno == EINTR)
1396 fatal("select: %s", strerror(saved_errno));
1397 } else if (result > 0)
1398 after_select(readsetp, writesetp);