1 /* $OpenBSD: ssh-agent.c,v 1.213 2016/05/02 08:49:03 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/param.h> /* MIN MAX */
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
52 #include "openbsd-compat/sys-queue.h"
55 #include <openssl/evp.h>
56 #include "openbsd-compat/openssl-compat.h"
89 #include "ssh-pkcs11.h"
101 struct sshbuf *input;
102 struct sshbuf *output;
103 struct sshbuf *request;
106 u_int sockets_alloc = 0;
107 SocketEntry *sockets = NULL;
109 typedef struct identity {
110 TAILQ_ENTRY(identity) next;
120 TAILQ_HEAD(idqueue, identity) idlist;
123 /* private key table, one per protocol version */
128 /* pid of shell == parent of agent */
129 pid_t parent_pid = -1;
130 time_t parent_alive_interval = 0;
132 /* pid of process for which cleanup_socket is applicable */
133 pid_t cleanup_pid = 0;
135 /* pathname and directory for AUTH_SOCKET */
136 char socket_name[PATH_MAX];
137 char socket_dir[PATH_MAX];
141 #define LOCK_SALT_SIZE 16
142 #define LOCK_ROUNDS 1
144 u_char lock_pwhash[LOCK_SIZE];
145 u_char lock_salt[LOCK_SALT_SIZE];
147 extern char *__progname;
149 /* Default lifetime in seconds (0 == forever) */
150 static long lifetime = 0;
152 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
155 * Client connection count; incremented in new_socket() and decremented in
156 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
157 * normally initialized to 1, it will never reach 0. However, if the -x
158 * option is specified, it is initialized to 0 in main(); in that case,
159 * ssh-agent will exit as soon as it has had at least one client but no
162 static int xcount = 1;
165 close_socket(SocketEntry *e)
169 if (e->type == AUTH_CONNECTION) {
170 debug("xcount %d -> %d", xcount, xcount - 1);
176 e->type = AUTH_UNUSED;
177 sshbuf_free(e->input);
178 sshbuf_free(e->output);
179 sshbuf_free(e->request);
189 for (i = 0; i <=2; i++) {
190 TAILQ_INIT(&idtable[i].idlist);
191 idtable[i].nentries = 0;
195 /* return private key table for requested protocol version */
197 idtab_lookup(int version)
199 if (version < 1 || version > 2)
200 fatal("internal error, bad protocol version %d", version);
201 return &idtable[version];
205 free_identity(Identity *id)
207 sshkey_free(id->key);
213 /* return matching private key for given public key */
215 lookup_identity(struct sshkey *key, int version)
219 Idtab *tab = idtab_lookup(version);
220 TAILQ_FOREACH(id, &tab->idlist, next) {
221 if (sshkey_equal(key, id->key))
227 /* Check confirmation of keysign request */
229 confirm_key(Identity *id)
234 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
236 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
245 send_status(SocketEntry *e, int success)
249 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
250 (r = sshbuf_put_u8(e->output, success ?
251 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
252 fatal("%s: buffer error: %s", __func__, ssh_err(r));
255 /* send list of supported public keys to 'client' */
257 process_request_identities(SocketEntry *e, int version)
259 Idtab *tab = idtab_lookup(version);
264 if ((msg = sshbuf_new()) == NULL)
265 fatal("%s: sshbuf_new failed", __func__);
266 if ((r = sshbuf_put_u8(msg, (version == 1) ?
267 SSH_AGENT_RSA_IDENTITIES_ANSWER :
268 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
269 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
270 fatal("%s: buffer error: %s", __func__, ssh_err(r));
271 TAILQ_FOREACH(id, &tab->idlist, next) {
272 if (id->key->type == KEY_RSA1) {
274 if ((r = sshbuf_put_u32(msg,
275 BN_num_bits(id->key->rsa->n))) != 0 ||
276 (r = sshbuf_put_bignum1(msg,
277 id->key->rsa->e)) != 0 ||
278 (r = sshbuf_put_bignum1(msg,
279 id->key->rsa->n)) != 0)
280 fatal("%s: buffer error: %s",
281 __func__, ssh_err(r));
287 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
288 error("%s: sshkey_to_blob: %s", __func__,
292 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
293 fatal("%s: buffer error: %s",
294 __func__, ssh_err(r));
297 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
298 fatal("%s: buffer error: %s", __func__, ssh_err(r));
300 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
301 fatal("%s: buffer error: %s", __func__, ssh_err(r));
308 process_authentication_challenge1(SocketEntry *e)
310 u_char buf[32], mdbuf[16], session_id[16];
316 struct ssh_digest_ctx *md;
319 if ((msg = sshbuf_new()) == NULL)
320 fatal("%s: sshbuf_new failed", __func__);
321 if ((key = sshkey_new(KEY_RSA1)) == NULL)
322 fatal("%s: sshkey_new failed", __func__);
323 if ((challenge = BN_new()) == NULL)
324 fatal("%s: BN_new failed", __func__);
326 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
327 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
328 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
329 (r = sshbuf_get_bignum1(e->request, challenge)))
330 fatal("%s: buffer error: %s", __func__, ssh_err(r));
332 /* Only protocol 1.1 is supported */
333 if (sshbuf_len(e->request) == 0)
335 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
336 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
337 fatal("%s: buffer error: %s", __func__, ssh_err(r));
338 if (response_type != 1)
341 id = lookup_identity(key, 1);
342 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
343 struct sshkey *private = id->key;
344 /* Decrypt the challenge using the private key. */
345 if ((r = rsa_private_decrypt(challenge, challenge,
346 private->rsa) != 0)) {
347 fatal("%s: rsa_public_encrypt: %s", __func__,
349 goto failure; /* XXX ? */
352 /* The response is MD5 of decrypted challenge plus session id */
353 len = BN_num_bytes(challenge);
354 if (len <= 0 || len > 32) {
355 logit("%s: bad challenge length %d", __func__, len);
359 BN_bn2bin(challenge, buf + 32 - len);
360 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
361 ssh_digest_update(md, buf, 32) < 0 ||
362 ssh_digest_update(md, session_id, 16) < 0 ||
363 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
364 fatal("%s: md5 failed", __func__);
367 /* Send the response. */
368 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
369 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
370 fatal("%s: buffer error: %s", __func__, ssh_err(r));
375 /* Unknown identity or protocol error. Send failure. */
376 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
377 fatal("%s: buffer error: %s", __func__, ssh_err(r));
379 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
380 fatal("%s: buffer error: %s", __func__, ssh_err(r));
382 BN_clear_free(challenge);
388 agent_decode_alg(struct sshkey *key, u_int flags)
390 if (key->type == KEY_RSA) {
391 if (flags & SSH_AGENT_RSA_SHA2_256)
392 return "rsa-sha2-256";
393 else if (flags & SSH_AGENT_RSA_SHA2_512)
394 return "rsa-sha2-512";
401 process_sign_request2(SocketEntry *e)
403 u_char *blob, *data, *signature = NULL;
404 size_t blen, dlen, slen = 0;
405 u_int compat = 0, flags;
411 if ((msg = sshbuf_new()) == NULL)
412 fatal("%s: sshbuf_new failed", __func__);
413 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
414 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
415 (r = sshbuf_get_u32(e->request, &flags)) != 0)
416 fatal("%s: buffer error: %s", __func__, ssh_err(r));
417 if (flags & SSH_AGENT_OLD_SIGNATURE)
418 compat = SSH_BUG_SIGBLOB;
419 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
420 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
423 if ((id = lookup_identity(key, 2)) == NULL) {
424 verbose("%s: %s key not found", __func__, sshkey_type(key));
427 if (id->confirm && confirm_key(id) != 0) {
428 verbose("%s: user refused key", __func__);
431 if ((r = sshkey_sign(id->key, &signature, &slen,
432 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
433 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
441 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
442 (r = sshbuf_put_string(msg, signature, slen)) != 0)
443 fatal("%s: buffer error: %s", __func__, ssh_err(r));
444 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
445 fatal("%s: buffer error: %s", __func__, ssh_err(r));
447 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
448 fatal("%s: buffer error: %s", __func__, ssh_err(r));
458 process_remove_identity(SocketEntry *e, int version)
462 struct sshkey *key = NULL;
466 #endif /* WITH_SSH1 */
471 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
472 error("%s: sshkey_new failed", __func__);
475 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
476 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
477 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
478 fatal("%s: buffer error: %s", __func__, ssh_err(r));
480 if (bits != sshkey_size(key))
481 logit("Warning: identity keysize mismatch: "
482 "actual %u, announced %u",
483 sshkey_size(key), bits);
485 #endif /* WITH_SSH1 */
487 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
488 fatal("%s: buffer error: %s", __func__, ssh_err(r));
489 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
490 error("%s: sshkey_from_blob failed: %s",
491 __func__, ssh_err(r));
496 Identity *id = lookup_identity(key, version);
499 * We have this key. Free the old key. Since we
500 * don't want to leave empty slots in the middle of
501 * the array, we actually free the key there and move
502 * all the entries between the empty slot and the end
505 Idtab *tab = idtab_lookup(version);
506 if (tab->nentries < 1)
507 fatal("process_remove_identity: "
508 "internal error: tab->nentries %d",
510 TAILQ_REMOVE(&tab->idlist, id, next);
517 send_status(e, success);
521 process_remove_all_identities(SocketEntry *e, int version)
523 Idtab *tab = idtab_lookup(version);
526 /* Loop over all identities and clear the keys. */
527 for (id = TAILQ_FIRST(&tab->idlist); id;
528 id = TAILQ_FIRST(&tab->idlist)) {
529 TAILQ_REMOVE(&tab->idlist, id, next);
533 /* Mark that there are no identities. */
540 /* removes expired keys and returns number of seconds until the next expiry */
544 time_t deadline = 0, now = monotime();
549 for (version = 1; version < 3; version++) {
550 tab = idtab_lookup(version);
551 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
552 nxt = TAILQ_NEXT(id, next);
555 if (now >= id->death) {
556 debug("expiring key '%s'", id->comment);
557 TAILQ_REMOVE(&tab->idlist, id, next);
561 deadline = (deadline == 0) ? id->death :
562 MIN(deadline, id->death);
565 if (deadline == 0 || deadline <= now)
568 return (deadline - now);
572 * XXX this and the corresponding serialisation function probably belongs
577 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
579 struct sshkey *k = NULL;
580 int r = SSH_ERR_INTERNAL_ERROR;
583 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
584 return SSH_ERR_ALLOC_FAIL;
586 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
587 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
588 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
589 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
590 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
591 /* SSH1 and SSL have p and q swapped */
592 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
593 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
596 /* Generate additional parameters */
597 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
599 /* enable blinding */
600 if (RSA_blinding_on(k->rsa, NULL) != 1) {
601 r = SSH_ERR_LIBCRYPTO_ERROR;
613 #endif /* WITH_SSH1 */
616 process_add_identity(SocketEntry *e, int version)
618 Idtab *tab = idtab_lookup(version);
620 int success = 0, confirm = 0;
622 char *comment = NULL;
624 struct sshkey *k = NULL;
626 int r = SSH_ERR_INTERNAL_ERROR;
631 r = agent_decode_rsa1(e->request, &k);
633 #endif /* WITH_SSH1 */
635 r = sshkey_private_deserialize(e->request, &k);
638 if (r != 0 || k == NULL ||
639 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
640 error("%s: decode private key: %s", __func__, ssh_err(r));
644 while (sshbuf_len(e->request)) {
645 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
646 error("%s: buffer error: %s", __func__, ssh_err(r));
650 case SSH_AGENT_CONSTRAIN_LIFETIME:
651 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
652 error("%s: bad lifetime constraint: %s",
653 __func__, ssh_err(r));
656 death = monotime() + seconds;
658 case SSH_AGENT_CONSTRAIN_CONFIRM:
662 error("%s: Unknown constraint %d", __func__, ctype);
664 sshbuf_reset(e->request);
672 if (lifetime && !death)
673 death = monotime() + lifetime;
674 if ((id = lookup_identity(k, version)) == NULL) {
675 id = xcalloc(1, sizeof(Identity));
677 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
678 /* Increment the number of identities. */
684 id->comment = comment;
686 id->confirm = confirm;
688 send_status(e, success);
691 /* XXX todo: encrypt sensitive data with passphrase */
693 process_lock_agent(SocketEntry *e, int lock)
695 int r, success = 0, delay;
697 u_char passwdhash[LOCK_SIZE];
698 static u_int fail_count = 0;
701 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
702 fatal("%s: buffer error: %s", __func__, ssh_err(r));
704 debug("empty password not supported");
705 } else if (locked && !lock) {
706 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
707 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
708 fatal("bcrypt_pbkdf");
709 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
710 debug("agent unlocked");
713 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
716 /* delay in 0.1s increments up to 10s */
717 if (fail_count < 100)
719 delay = 100000 * fail_count;
720 debug("unlock failed, delaying %0.1lf seconds",
721 (double)delay/1000000);
724 explicit_bzero(passwdhash, sizeof(passwdhash));
725 } else if (!locked && lock) {
726 debug("agent locked");
728 arc4random_buf(lock_salt, sizeof(lock_salt));
729 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
730 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
731 fatal("bcrypt_pbkdf");
734 explicit_bzero(passwd, pwlen);
736 send_status(e, success);
740 no_identities(SocketEntry *e, u_int type)
745 if ((msg = sshbuf_new()) == NULL)
746 fatal("%s: sshbuf_new failed", __func__);
747 if ((r = sshbuf_put_u8(msg,
748 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
749 SSH_AGENT_RSA_IDENTITIES_ANSWER :
750 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
751 (r = sshbuf_put_u32(msg, 0)) != 0 ||
752 (r = sshbuf_put_stringb(e->output, msg)) != 0)
753 fatal("%s: buffer error: %s", __func__, ssh_err(r));
759 process_add_smartcard_key(SocketEntry *e)
761 char *provider = NULL, *pin;
762 int r, i, version, count = 0, success = 0, confirm = 0;
766 struct sshkey **keys = NULL, *k;
770 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
771 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
772 fatal("%s: buffer error: %s", __func__, ssh_err(r));
774 while (sshbuf_len(e->request)) {
775 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
776 fatal("%s: buffer error: %s", __func__, ssh_err(r));
778 case SSH_AGENT_CONSTRAIN_LIFETIME:
779 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
780 fatal("%s: buffer error: %s",
781 __func__, ssh_err(r));
782 death = monotime() + seconds;
784 case SSH_AGENT_CONSTRAIN_CONFIRM:
788 error("process_add_smartcard_key: "
789 "Unknown constraint type %d", type);
793 if (lifetime && !death)
794 death = monotime() + lifetime;
796 count = pkcs11_add_provider(provider, pin, &keys);
797 for (i = 0; i < count; i++) {
799 version = k->type == KEY_RSA1 ? 1 : 2;
800 tab = idtab_lookup(version);
801 if (lookup_identity(k, version) == NULL) {
802 id = xcalloc(1, sizeof(Identity));
804 id->provider = xstrdup(provider);
805 id->comment = xstrdup(provider); /* XXX */
807 id->confirm = confirm;
808 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
820 send_status(e, success);
824 process_remove_smartcard_key(SocketEntry *e)
826 char *provider = NULL, *pin = NULL;
827 int r, version, success = 0;
831 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
832 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
833 fatal("%s: buffer error: %s", __func__, ssh_err(r));
836 for (version = 1; version < 3; version++) {
837 tab = idtab_lookup(version);
838 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
839 nxt = TAILQ_NEXT(id, next);
840 /* Skip file--based keys */
841 if (id->provider == NULL)
843 if (!strcmp(provider, id->provider)) {
844 TAILQ_REMOVE(&tab->idlist, id, next);
850 if (pkcs11_del_provider(provider) == 0)
853 error("process_remove_smartcard_key:"
854 " pkcs11_del_provider failed");
856 send_status(e, success);
858 #endif /* ENABLE_PKCS11 */
860 /* dispatch incoming messages */
863 process_message(SocketEntry *e)
870 if (sshbuf_len(e->input) < 5)
871 return; /* Incomplete message. */
872 cp = sshbuf_ptr(e->input);
873 msg_len = PEEK_U32(cp);
874 if (msg_len > 256 * 1024) {
878 if (sshbuf_len(e->input) < msg_len + 4)
881 /* move the current input to e->request */
882 sshbuf_reset(e->request);
883 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
884 (r = sshbuf_get_u8(e->request, &type)) != 0)
885 fatal("%s: buffer error: %s", __func__, ssh_err(r));
887 /* check wheter agent is locked */
888 if (locked && type != SSH_AGENTC_UNLOCK) {
889 sshbuf_reset(e->request);
891 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
892 case SSH2_AGENTC_REQUEST_IDENTITIES:
893 /* send empty lists */
894 no_identities(e, type);
897 /* send a fail message for all other request types */
903 debug("type %d", type);
905 case SSH_AGENTC_LOCK:
906 case SSH_AGENTC_UNLOCK:
907 process_lock_agent(e, type == SSH_AGENTC_LOCK);
911 case SSH_AGENTC_RSA_CHALLENGE:
912 process_authentication_challenge1(e);
914 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
915 process_request_identities(e, 1);
917 case SSH_AGENTC_ADD_RSA_IDENTITY:
918 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
919 process_add_identity(e, 1);
921 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
922 process_remove_identity(e, 1);
925 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
926 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
929 case SSH2_AGENTC_SIGN_REQUEST:
930 process_sign_request2(e);
932 case SSH2_AGENTC_REQUEST_IDENTITIES:
933 process_request_identities(e, 2);
935 case SSH2_AGENTC_ADD_IDENTITY:
936 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
937 process_add_identity(e, 2);
939 case SSH2_AGENTC_REMOVE_IDENTITY:
940 process_remove_identity(e, 2);
942 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
943 process_remove_all_identities(e, 2);
946 case SSH_AGENTC_ADD_SMARTCARD_KEY:
947 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
948 process_add_smartcard_key(e);
950 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
951 process_remove_smartcard_key(e);
953 #endif /* ENABLE_PKCS11 */
955 /* Unknown message. Respond with failure. */
956 error("Unknown message %d", type);
957 sshbuf_reset(e->request);
964 new_socket(sock_type type, int fd)
966 u_int i, old_alloc, new_alloc;
968 if (type == AUTH_CONNECTION) {
969 debug("xcount %d -> %d", xcount, xcount + 1);
977 for (i = 0; i < sockets_alloc; i++)
978 if (sockets[i].type == AUTH_UNUSED) {
980 if ((sockets[i].input = sshbuf_new()) == NULL)
981 fatal("%s: sshbuf_new failed", __func__);
982 if ((sockets[i].output = sshbuf_new()) == NULL)
983 fatal("%s: sshbuf_new failed", __func__);
984 if ((sockets[i].request = sshbuf_new()) == NULL)
985 fatal("%s: sshbuf_new failed", __func__);
986 sockets[i].type = type;
989 old_alloc = sockets_alloc;
990 new_alloc = sockets_alloc + 10;
991 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
992 for (i = old_alloc; i < new_alloc; i++)
993 sockets[i].type = AUTH_UNUSED;
994 sockets_alloc = new_alloc;
995 sockets[old_alloc].fd = fd;
996 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
997 fatal("%s: sshbuf_new failed", __func__);
998 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
999 fatal("%s: sshbuf_new failed", __func__);
1000 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1001 fatal("%s: sshbuf_new failed", __func__);
1002 sockets[old_alloc].type = type;
1006 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1007 struct timeval **tvpp)
1011 static struct timeval tv;
1014 for (i = 0; i < sockets_alloc; i++) {
1015 switch (sockets[i].type) {
1017 case AUTH_CONNECTION:
1018 n = MAX(n, sockets[i].fd);
1023 fatal("Unknown socket type %d", sockets[i].type);
1028 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1029 if (*fdrp == NULL || sz > *nallocp) {
1032 *fdrp = xmalloc(sz);
1033 *fdwp = xmalloc(sz);
1037 debug("XXX shrink: %d < %d", n, *fdl);
1039 memset(*fdrp, 0, sz);
1040 memset(*fdwp, 0, sz);
1042 for (i = 0; i < sockets_alloc; i++) {
1043 switch (sockets[i].type) {
1045 case AUTH_CONNECTION:
1046 FD_SET(sockets[i].fd, *fdrp);
1047 if (sshbuf_len(sockets[i].output) > 0)
1048 FD_SET(sockets[i].fd, *fdwp);
1054 deadline = reaper();
1055 if (parent_alive_interval != 0)
1056 deadline = (deadline == 0) ? parent_alive_interval :
1057 MIN(deadline, parent_alive_interval);
1058 if (deadline == 0) {
1061 tv.tv_sec = deadline;
1069 after_select(fd_set *readset, fd_set *writeset)
1071 struct sockaddr_un sunaddr;
1075 u_int i, orig_alloc;
1079 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1080 switch (sockets[i].type) {
1084 if (FD_ISSET(sockets[i].fd, readset)) {
1085 slen = sizeof(sunaddr);
1086 sock = accept(sockets[i].fd,
1087 (struct sockaddr *)&sunaddr, &slen);
1089 error("accept from AUTH_SOCKET: %s",
1093 if (getpeereid(sock, &euid, &egid) < 0) {
1094 error("getpeereid %d failed: %s",
1095 sock, strerror(errno));
1099 if ((euid != 0) && (getuid() != euid)) {
1100 error("uid mismatch: "
1101 "peer euid %u != uid %u",
1102 (u_int) euid, (u_int) getuid());
1106 new_socket(AUTH_CONNECTION, sock);
1109 case AUTH_CONNECTION:
1110 if (sshbuf_len(sockets[i].output) > 0 &&
1111 FD_ISSET(sockets[i].fd, writeset)) {
1112 len = write(sockets[i].fd,
1113 sshbuf_ptr(sockets[i].output),
1114 sshbuf_len(sockets[i].output));
1115 if (len == -1 && (errno == EAGAIN ||
1116 errno == EWOULDBLOCK ||
1120 close_socket(&sockets[i]);
1123 if ((r = sshbuf_consume(sockets[i].output,
1125 fatal("%s: buffer error: %s",
1126 __func__, ssh_err(r));
1128 if (FD_ISSET(sockets[i].fd, readset)) {
1129 len = read(sockets[i].fd, buf, sizeof(buf));
1130 if (len == -1 && (errno == EAGAIN ||
1131 errno == EWOULDBLOCK ||
1135 close_socket(&sockets[i]);
1138 if ((r = sshbuf_put(sockets[i].input,
1140 fatal("%s: buffer error: %s",
1141 __func__, ssh_err(r));
1142 explicit_bzero(buf, sizeof(buf));
1143 process_message(&sockets[i]);
1147 fatal("Unknown type %d", sockets[i].type);
1152 cleanup_socket(void)
1154 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1156 debug("%s: cleanup", __func__);
1158 unlink(socket_name);
1172 cleanup_handler(int sig)
1175 #ifdef ENABLE_PKCS11
1182 check_parent_exists(void)
1185 * If our parent has exited then getppid() will return (pid_t)1,
1186 * so testing for that should be safe.
1188 if (parent_pid != -1 && getppid() != parent_pid) {
1189 /* printf("Parent has died - Authentication agent exiting.\n"); */
1199 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1200 " [-t life] [command [arg ...]]\n"
1201 " ssh-agent [-c | -s] -k\n");
1202 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1207 main(int ac, char **av)
1209 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1210 int sock, fd, ch, result, saved_errno;
1212 char *shell, *format, *pidstr, *agentsocket = NULL;
1213 fd_set *readsetp = NULL, *writesetp = NULL;
1214 #ifdef HAVE_SETRLIMIT
1218 extern char *optarg;
1220 char pidstrbuf[1 + 3 * sizeof pid];
1221 struct timeval *tvp = NULL;
1225 ssh_malloc_init(); /* must be called before any mallocs */
1226 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1234 platform_disable_tracing(0); /* strict=no */
1237 OpenSSL_add_all_algorithms();
1240 __progname = ssh_get_progname(av[0]);
1243 while ((ch = getopt(ac, av, "cDdksE:a:t:x")) != -1) {
1246 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1247 if (fingerprint_hash == -1)
1248 fatal("Invalid hash algorithm \"%s\"", optarg);
1264 if (d_flag || D_flag)
1269 if (d_flag || D_flag)
1274 agentsocket = optarg;
1277 if ((lifetime = convtime(optarg)) == -1) {
1278 fprintf(stderr, "Invalid lifetime\n");
1292 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1295 if (ac == 0 && !c_flag && !s_flag) {
1296 shell = getenv("SHELL");
1297 if (shell != NULL && (len = strlen(shell)) > 2 &&
1298 strncmp(shell + len - 3, "csh", 3) == 0)
1302 const char *errstr = NULL;
1304 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1305 if (pidstr == NULL) {
1306 fprintf(stderr, "%s not set, cannot kill agent\n",
1307 SSH_AGENTPID_ENV_NAME);
1310 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1313 "%s=\"%s\", which is not a good PID: %s\n",
1314 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1317 if (kill(pid, SIGTERM) == -1) {
1321 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1322 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1323 printf(format, SSH_AGENTPID_ENV_NAME);
1324 printf("echo Agent pid %ld killed;\n", (long)pid);
1327 parent_pid = getpid();
1329 if (agentsocket == NULL) {
1330 /* Create private directory for agent socket */
1331 mktemp_proto(socket_dir, sizeof(socket_dir));
1332 if (mkdtemp(socket_dir) == NULL) {
1333 perror("mkdtemp: private socket dir");
1336 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1339 /* Try to use specified agent socket */
1340 socket_dir[0] = '\0';
1341 strlcpy(socket_name, agentsocket, sizeof socket_name);
1345 * Create socket early so it will exist before command gets run from
1348 prev_mask = umask(0177);
1349 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1351 /* XXX - unix_listener() calls error() not perror() */
1352 *socket_name = '\0'; /* Don't unlink any existing file */
1358 * Fork, and have the parent execute the command, if any, or present
1359 * the socket data. The child continues as the authentication agent.
1361 if (D_flag || d_flag) {
1362 log_init(__progname,
1363 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1364 SYSLOG_FACILITY_AUTH, 1);
1365 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1366 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1367 SSH_AUTHSOCKET_ENV_NAME);
1368 printf("echo Agent pid %ld;\n", (long)parent_pid);
1377 if (pid != 0) { /* Parent - execute the given command. */
1379 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1381 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1382 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1383 SSH_AUTHSOCKET_ENV_NAME);
1384 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1385 SSH_AGENTPID_ENV_NAME);
1386 printf("echo Agent pid %ld;\n", (long)pid);
1389 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1390 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1399 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1401 if (setsid() == -1) {
1402 error("setsid: %s", strerror(errno));
1407 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1408 /* XXX might close listen socket */
1409 (void)dup2(fd, STDIN_FILENO);
1410 (void)dup2(fd, STDOUT_FILENO);
1411 (void)dup2(fd, STDERR_FILENO);
1416 #ifdef HAVE_SETRLIMIT
1417 /* deny core dumps, since memory contains unencrypted private keys */
1418 rlim.rlim_cur = rlim.rlim_max = 0;
1419 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1420 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1427 cleanup_pid = getpid();
1429 #ifdef ENABLE_PKCS11
1432 new_socket(AUTH_SOCKET, sock);
1434 parent_alive_interval = 10;
1436 signal(SIGPIPE, SIG_IGN);
1437 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1438 signal(SIGHUP, cleanup_handler);
1439 signal(SIGTERM, cleanup_handler);
1442 if (pledge("stdio cpath unix id proc exec", NULL) == -1)
1443 fatal("%s: pledge: %s", __progname, strerror(errno));
1444 platform_pledge_agent();
1447 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1448 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1449 saved_errno = errno;
1450 if (parent_alive_interval != 0)
1451 check_parent_exists();
1452 (void) reaper(); /* remove expired keys */
1454 if (saved_errno == EINTR)
1456 fatal("select: %s", strerror(saved_errno));
1457 } else if (result > 0)
1458 after_select(readsetp, writesetp);