1 /* $OpenBSD: ssh-agent.c,v 1.212 2016/02/15 09:47:49 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/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"
92 #if defined(HAVE_SYS_PRCTL_H)
93 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
105 struct sshbuf *input;
106 struct sshbuf *output;
107 struct sshbuf *request;
110 u_int sockets_alloc = 0;
111 SocketEntry *sockets = NULL;
113 typedef struct identity {
114 TAILQ_ENTRY(identity) next;
124 TAILQ_HEAD(idqueue, identity) idlist;
127 /* private key table, one per protocol version */
132 /* pid of shell == parent of agent */
133 pid_t parent_pid = -1;
134 time_t parent_alive_interval = 0;
136 /* pid of process for which cleanup_socket is applicable */
137 pid_t cleanup_pid = 0;
139 /* pathname and directory for AUTH_SOCKET */
140 char socket_name[PATH_MAX];
141 char socket_dir[PATH_MAX];
145 #define LOCK_SALT_SIZE 16
146 #define LOCK_ROUNDS 1
148 char lock_passwd[LOCK_SIZE];
149 char lock_salt[LOCK_SALT_SIZE];
151 extern char *__progname;
153 /* Default lifetime in seconds (0 == forever) */
154 static long lifetime = 0;
156 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
159 * Client connection count; incremented in new_socket() and decremented in
160 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
161 * normally initialized to 1, it will never reach 0. However, if the -x
162 * option is specified, it is initialized to 0 in main(); in that case,
163 * ssh-agent will exit as soon as it has had at least one client but no
166 static int xcount = 1;
169 close_socket(SocketEntry *e)
173 if (e->type == AUTH_CONNECTION) {
174 debug("xcount %d -> %d", xcount, xcount - 1);
180 e->type = AUTH_UNUSED;
181 sshbuf_free(e->input);
182 sshbuf_free(e->output);
183 sshbuf_free(e->request);
193 for (i = 0; i <=2; i++) {
194 TAILQ_INIT(&idtable[i].idlist);
195 idtable[i].nentries = 0;
199 /* return private key table for requested protocol version */
201 idtab_lookup(int version)
203 if (version < 1 || version > 2)
204 fatal("internal error, bad protocol version %d", version);
205 return &idtable[version];
209 free_identity(Identity *id)
211 sshkey_free(id->key);
217 /* return matching private key for given public key */
219 lookup_identity(struct sshkey *key, int version)
223 Idtab *tab = idtab_lookup(version);
224 TAILQ_FOREACH(id, &tab->idlist, next) {
225 if (sshkey_equal(key, id->key))
231 /* Check confirmation of keysign request */
233 confirm_key(Identity *id)
238 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
240 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
249 send_status(SocketEntry *e, int success)
253 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
254 (r = sshbuf_put_u8(e->output, success ?
255 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
256 fatal("%s: buffer error: %s", __func__, ssh_err(r));
259 /* send list of supported public keys to 'client' */
261 process_request_identities(SocketEntry *e, int version)
263 Idtab *tab = idtab_lookup(version);
268 if ((msg = sshbuf_new()) == NULL)
269 fatal("%s: sshbuf_new failed", __func__);
270 if ((r = sshbuf_put_u8(msg, (version == 1) ?
271 SSH_AGENT_RSA_IDENTITIES_ANSWER :
272 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
273 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
274 fatal("%s: buffer error: %s", __func__, ssh_err(r));
275 TAILQ_FOREACH(id, &tab->idlist, next) {
276 if (id->key->type == KEY_RSA1) {
278 if ((r = sshbuf_put_u32(msg,
279 BN_num_bits(id->key->rsa->n))) != 0 ||
280 (r = sshbuf_put_bignum1(msg,
281 id->key->rsa->e)) != 0 ||
282 (r = sshbuf_put_bignum1(msg,
283 id->key->rsa->n)) != 0)
284 fatal("%s: buffer error: %s",
285 __func__, ssh_err(r));
291 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
292 error("%s: sshkey_to_blob: %s", __func__,
296 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
297 fatal("%s: buffer error: %s",
298 __func__, ssh_err(r));
301 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
302 fatal("%s: buffer error: %s", __func__, ssh_err(r));
304 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
305 fatal("%s: buffer error: %s", __func__, ssh_err(r));
312 process_authentication_challenge1(SocketEntry *e)
314 u_char buf[32], mdbuf[16], session_id[16];
320 struct ssh_digest_ctx *md;
323 if ((msg = sshbuf_new()) == NULL)
324 fatal("%s: sshbuf_new failed", __func__);
325 if ((key = sshkey_new(KEY_RSA1)) == NULL)
326 fatal("%s: sshkey_new failed", __func__);
327 if ((challenge = BN_new()) == NULL)
328 fatal("%s: BN_new failed", __func__);
330 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
331 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
332 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
333 (r = sshbuf_get_bignum1(e->request, challenge)))
334 fatal("%s: buffer error: %s", __func__, ssh_err(r));
336 /* Only protocol 1.1 is supported */
337 if (sshbuf_len(e->request) == 0)
339 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
340 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
341 fatal("%s: buffer error: %s", __func__, ssh_err(r));
342 if (response_type != 1)
345 id = lookup_identity(key, 1);
346 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
347 struct sshkey *private = id->key;
348 /* Decrypt the challenge using the private key. */
349 if ((r = rsa_private_decrypt(challenge, challenge,
350 private->rsa) != 0)) {
351 fatal("%s: rsa_public_encrypt: %s", __func__,
353 goto failure; /* XXX ? */
356 /* The response is MD5 of decrypted challenge plus session id */
357 len = BN_num_bytes(challenge);
358 if (len <= 0 || len > 32) {
359 logit("%s: bad challenge length %d", __func__, len);
363 BN_bn2bin(challenge, buf + 32 - len);
364 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
365 ssh_digest_update(md, buf, 32) < 0 ||
366 ssh_digest_update(md, session_id, 16) < 0 ||
367 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
368 fatal("%s: md5 failed", __func__);
371 /* Send the response. */
372 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
373 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
374 fatal("%s: buffer error: %s", __func__, ssh_err(r));
379 /* Unknown identity or protocol error. Send failure. */
380 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
381 fatal("%s: buffer error: %s", __func__, ssh_err(r));
383 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
384 fatal("%s: buffer error: %s", __func__, ssh_err(r));
386 BN_clear_free(challenge);
392 agent_decode_alg(struct sshkey *key, u_int flags)
394 if (key->type == KEY_RSA) {
395 if (flags & SSH_AGENT_RSA_SHA2_256)
396 return "rsa-sha2-256";
397 else if (flags & SSH_AGENT_RSA_SHA2_512)
398 return "rsa-sha2-512";
405 process_sign_request2(SocketEntry *e)
407 u_char *blob, *data, *signature = NULL;
408 size_t blen, dlen, slen = 0;
409 u_int compat = 0, flags;
415 if ((msg = sshbuf_new()) == NULL)
416 fatal("%s: sshbuf_new failed", __func__);
417 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
418 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
419 (r = sshbuf_get_u32(e->request, &flags)) != 0)
420 fatal("%s: buffer error: %s", __func__, ssh_err(r));
421 if (flags & SSH_AGENT_OLD_SIGNATURE)
422 compat = SSH_BUG_SIGBLOB;
423 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
424 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
427 if ((id = lookup_identity(key, 2)) == NULL) {
428 verbose("%s: %s key not found", __func__, sshkey_type(key));
431 if (id->confirm && confirm_key(id) != 0) {
432 verbose("%s: user refused key", __func__);
435 if ((r = sshkey_sign(id->key, &signature, &slen,
436 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
437 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
445 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
446 (r = sshbuf_put_string(msg, signature, slen)) != 0)
447 fatal("%s: buffer error: %s", __func__, ssh_err(r));
448 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
449 fatal("%s: buffer error: %s", __func__, ssh_err(r));
451 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
452 fatal("%s: buffer error: %s", __func__, ssh_err(r));
462 process_remove_identity(SocketEntry *e, int version)
466 struct sshkey *key = NULL;
470 #endif /* WITH_SSH1 */
475 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
476 error("%s: sshkey_new failed", __func__);
479 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
480 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
481 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
482 fatal("%s: buffer error: %s", __func__, ssh_err(r));
484 if (bits != sshkey_size(key))
485 logit("Warning: identity keysize mismatch: "
486 "actual %u, announced %u",
487 sshkey_size(key), bits);
489 #endif /* WITH_SSH1 */
491 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
492 fatal("%s: buffer error: %s", __func__, ssh_err(r));
493 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
494 error("%s: sshkey_from_blob failed: %s",
495 __func__, ssh_err(r));
500 Identity *id = lookup_identity(key, version);
503 * We have this key. Free the old key. Since we
504 * don't want to leave empty slots in the middle of
505 * the array, we actually free the key there and move
506 * all the entries between the empty slot and the end
509 Idtab *tab = idtab_lookup(version);
510 if (tab->nentries < 1)
511 fatal("process_remove_identity: "
512 "internal error: tab->nentries %d",
514 TAILQ_REMOVE(&tab->idlist, id, next);
521 send_status(e, success);
525 process_remove_all_identities(SocketEntry *e, int version)
527 Idtab *tab = idtab_lookup(version);
530 /* Loop over all identities and clear the keys. */
531 for (id = TAILQ_FIRST(&tab->idlist); id;
532 id = TAILQ_FIRST(&tab->idlist)) {
533 TAILQ_REMOVE(&tab->idlist, id, next);
537 /* Mark that there are no identities. */
544 /* removes expired keys and returns number of seconds until the next expiry */
548 time_t deadline = 0, now = monotime();
553 for (version = 1; version < 3; version++) {
554 tab = idtab_lookup(version);
555 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
556 nxt = TAILQ_NEXT(id, next);
559 if (now >= id->death) {
560 debug("expiring key '%s'", id->comment);
561 TAILQ_REMOVE(&tab->idlist, id, next);
565 deadline = (deadline == 0) ? id->death :
566 MIN(deadline, id->death);
569 if (deadline == 0 || deadline <= now)
572 return (deadline - now);
576 * XXX this and the corresponding serialisation function probably belongs
581 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
583 struct sshkey *k = NULL;
584 int r = SSH_ERR_INTERNAL_ERROR;
587 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
588 return SSH_ERR_ALLOC_FAIL;
590 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
591 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
592 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
593 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
594 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
595 /* SSH1 and SSL have p and q swapped */
596 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
597 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
600 /* Generate additional parameters */
601 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
603 /* enable blinding */
604 if (RSA_blinding_on(k->rsa, NULL) != 1) {
605 r = SSH_ERR_LIBCRYPTO_ERROR;
617 #endif /* WITH_SSH1 */
620 process_add_identity(SocketEntry *e, int version)
622 Idtab *tab = idtab_lookup(version);
624 int success = 0, confirm = 0;
626 char *comment = NULL;
628 struct sshkey *k = NULL;
630 int r = SSH_ERR_INTERNAL_ERROR;
635 r = agent_decode_rsa1(e->request, &k);
637 #endif /* WITH_SSH1 */
639 r = sshkey_private_deserialize(e->request, &k);
642 if (r != 0 || k == NULL ||
643 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
644 error("%s: decode private key: %s", __func__, ssh_err(r));
648 while (sshbuf_len(e->request)) {
649 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
650 error("%s: buffer error: %s", __func__, ssh_err(r));
654 case SSH_AGENT_CONSTRAIN_LIFETIME:
655 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
656 error("%s: bad lifetime constraint: %s",
657 __func__, ssh_err(r));
660 death = monotime() + seconds;
662 case SSH_AGENT_CONSTRAIN_CONFIRM:
666 error("%s: Unknown constraint %d", __func__, ctype);
668 sshbuf_reset(e->request);
676 if (lifetime && !death)
677 death = monotime() + lifetime;
678 if ((id = lookup_identity(k, version)) == NULL) {
679 id = xcalloc(1, sizeof(Identity));
681 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
682 /* Increment the number of identities. */
688 id->comment = comment;
690 id->confirm = confirm;
692 send_status(e, success);
695 /* XXX todo: encrypt sensitive data with passphrase */
697 process_lock_agent(SocketEntry *e, int lock)
699 int r, success = 0, delay;
700 char *passwd, passwdhash[LOCK_SIZE];
701 static u_int fail_count = 0;
704 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
705 fatal("%s: buffer error: %s", __func__, ssh_err(r));
707 debug("empty password not supported");
708 } else if (locked && !lock) {
709 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
710 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
711 fatal("bcrypt_pbkdf");
712 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
713 debug("agent unlocked");
716 explicit_bzero(lock_passwd, sizeof(lock_passwd));
719 /* delay in 0.1s increments up to 10s */
720 if (fail_count < 100)
722 delay = 100000 * fail_count;
723 debug("unlock failed, delaying %0.1lf seconds",
724 (double)delay/1000000);
727 explicit_bzero(passwdhash, sizeof(passwdhash));
728 } else if (!locked && lock) {
729 debug("agent locked");
731 arc4random_buf(lock_salt, sizeof(lock_salt));
732 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
733 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
734 fatal("bcrypt_pbkdf");
737 explicit_bzero(passwd, pwlen);
739 send_status(e, success);
743 no_identities(SocketEntry *e, u_int type)
748 if ((msg = sshbuf_new()) == NULL)
749 fatal("%s: sshbuf_new failed", __func__);
750 if ((r = sshbuf_put_u8(msg,
751 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
752 SSH_AGENT_RSA_IDENTITIES_ANSWER :
753 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
754 (r = sshbuf_put_u32(msg, 0)) != 0 ||
755 (r = sshbuf_put_stringb(e->output, msg)) != 0)
756 fatal("%s: buffer error: %s", __func__, ssh_err(r));
762 process_add_smartcard_key(SocketEntry *e)
764 char *provider = NULL, *pin;
765 int r, i, version, count = 0, success = 0, confirm = 0;
769 struct sshkey **keys = NULL, *k;
773 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
774 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
775 fatal("%s: buffer error: %s", __func__, ssh_err(r));
777 while (sshbuf_len(e->request)) {
778 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
779 fatal("%s: buffer error: %s", __func__, ssh_err(r));
781 case SSH_AGENT_CONSTRAIN_LIFETIME:
782 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
783 fatal("%s: buffer error: %s",
784 __func__, ssh_err(r));
785 death = monotime() + seconds;
787 case SSH_AGENT_CONSTRAIN_CONFIRM:
791 error("process_add_smartcard_key: "
792 "Unknown constraint type %d", type);
796 if (lifetime && !death)
797 death = monotime() + lifetime;
799 count = pkcs11_add_provider(provider, pin, &keys);
800 for (i = 0; i < count; i++) {
802 version = k->type == KEY_RSA1 ? 1 : 2;
803 tab = idtab_lookup(version);
804 if (lookup_identity(k, version) == NULL) {
805 id = xcalloc(1, sizeof(Identity));
807 id->provider = xstrdup(provider);
808 id->comment = xstrdup(provider); /* XXX */
810 id->confirm = confirm;
811 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
823 send_status(e, success);
827 process_remove_smartcard_key(SocketEntry *e)
829 char *provider = NULL, *pin = NULL;
830 int r, version, success = 0;
834 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
835 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
836 fatal("%s: buffer error: %s", __func__, ssh_err(r));
839 for (version = 1; version < 3; version++) {
840 tab = idtab_lookup(version);
841 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
842 nxt = TAILQ_NEXT(id, next);
843 /* Skip file--based keys */
844 if (id->provider == NULL)
846 if (!strcmp(provider, id->provider)) {
847 TAILQ_REMOVE(&tab->idlist, id, next);
853 if (pkcs11_del_provider(provider) == 0)
856 error("process_remove_smartcard_key:"
857 " pkcs11_del_provider failed");
859 send_status(e, success);
861 #endif /* ENABLE_PKCS11 */
863 /* dispatch incoming messages */
866 process_message(SocketEntry *e)
873 if (sshbuf_len(e->input) < 5)
874 return; /* Incomplete message. */
875 cp = sshbuf_ptr(e->input);
876 msg_len = PEEK_U32(cp);
877 if (msg_len > 256 * 1024) {
881 if (sshbuf_len(e->input) < msg_len + 4)
884 /* move the current input to e->request */
885 sshbuf_reset(e->request);
886 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
887 (r = sshbuf_get_u8(e->request, &type)) != 0)
888 fatal("%s: buffer error: %s", __func__, ssh_err(r));
890 /* check wheter agent is locked */
891 if (locked && type != SSH_AGENTC_UNLOCK) {
892 sshbuf_reset(e->request);
894 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
895 case SSH2_AGENTC_REQUEST_IDENTITIES:
896 /* send empty lists */
897 no_identities(e, type);
900 /* send a fail message for all other request types */
906 debug("type %d", type);
908 case SSH_AGENTC_LOCK:
909 case SSH_AGENTC_UNLOCK:
910 process_lock_agent(e, type == SSH_AGENTC_LOCK);
914 case SSH_AGENTC_RSA_CHALLENGE:
915 process_authentication_challenge1(e);
917 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
918 process_request_identities(e, 1);
920 case SSH_AGENTC_ADD_RSA_IDENTITY:
921 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
922 process_add_identity(e, 1);
924 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
925 process_remove_identity(e, 1);
928 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
929 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
932 case SSH2_AGENTC_SIGN_REQUEST:
933 process_sign_request2(e);
935 case SSH2_AGENTC_REQUEST_IDENTITIES:
936 process_request_identities(e, 2);
938 case SSH2_AGENTC_ADD_IDENTITY:
939 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
940 process_add_identity(e, 2);
942 case SSH2_AGENTC_REMOVE_IDENTITY:
943 process_remove_identity(e, 2);
945 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
946 process_remove_all_identities(e, 2);
949 case SSH_AGENTC_ADD_SMARTCARD_KEY:
950 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
951 process_add_smartcard_key(e);
953 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
954 process_remove_smartcard_key(e);
956 #endif /* ENABLE_PKCS11 */
958 /* Unknown message. Respond with failure. */
959 error("Unknown message %d", type);
960 sshbuf_reset(e->request);
967 new_socket(sock_type type, int fd)
969 u_int i, old_alloc, new_alloc;
971 if (type == AUTH_CONNECTION) {
972 debug("xcount %d -> %d", xcount, xcount + 1);
980 for (i = 0; i < sockets_alloc; i++)
981 if (sockets[i].type == AUTH_UNUSED) {
983 if ((sockets[i].input = sshbuf_new()) == NULL)
984 fatal("%s: sshbuf_new failed", __func__);
985 if ((sockets[i].output = sshbuf_new()) == NULL)
986 fatal("%s: sshbuf_new failed", __func__);
987 if ((sockets[i].request = sshbuf_new()) == NULL)
988 fatal("%s: sshbuf_new failed", __func__);
989 sockets[i].type = type;
992 old_alloc = sockets_alloc;
993 new_alloc = sockets_alloc + 10;
994 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
995 for (i = old_alloc; i < new_alloc; i++)
996 sockets[i].type = AUTH_UNUSED;
997 sockets_alloc = new_alloc;
998 sockets[old_alloc].fd = fd;
999 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
1000 fatal("%s: sshbuf_new failed", __func__);
1001 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
1002 fatal("%s: sshbuf_new failed", __func__);
1003 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1004 fatal("%s: sshbuf_new failed", __func__);
1005 sockets[old_alloc].type = type;
1009 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1010 struct timeval **tvpp)
1014 static struct timeval tv;
1017 for (i = 0; i < sockets_alloc; i++) {
1018 switch (sockets[i].type) {
1020 case AUTH_CONNECTION:
1021 n = MAX(n, sockets[i].fd);
1026 fatal("Unknown socket type %d", sockets[i].type);
1031 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1032 if (*fdrp == NULL || sz > *nallocp) {
1035 *fdrp = xmalloc(sz);
1036 *fdwp = xmalloc(sz);
1040 debug("XXX shrink: %d < %d", n, *fdl);
1042 memset(*fdrp, 0, sz);
1043 memset(*fdwp, 0, sz);
1045 for (i = 0; i < sockets_alloc; i++) {
1046 switch (sockets[i].type) {
1048 case AUTH_CONNECTION:
1049 FD_SET(sockets[i].fd, *fdrp);
1050 if (sshbuf_len(sockets[i].output) > 0)
1051 FD_SET(sockets[i].fd, *fdwp);
1057 deadline = reaper();
1058 if (parent_alive_interval != 0)
1059 deadline = (deadline == 0) ? parent_alive_interval :
1060 MIN(deadline, parent_alive_interval);
1061 if (deadline == 0) {
1064 tv.tv_sec = deadline;
1072 after_select(fd_set *readset, fd_set *writeset)
1074 struct sockaddr_un sunaddr;
1078 u_int i, orig_alloc;
1082 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1083 switch (sockets[i].type) {
1087 if (FD_ISSET(sockets[i].fd, readset)) {
1088 slen = sizeof(sunaddr);
1089 sock = accept(sockets[i].fd,
1090 (struct sockaddr *)&sunaddr, &slen);
1092 error("accept from AUTH_SOCKET: %s",
1096 if (getpeereid(sock, &euid, &egid) < 0) {
1097 error("getpeereid %d failed: %s",
1098 sock, strerror(errno));
1102 if ((euid != 0) && (getuid() != euid)) {
1103 error("uid mismatch: "
1104 "peer euid %u != uid %u",
1105 (u_int) euid, (u_int) getuid());
1109 new_socket(AUTH_CONNECTION, sock);
1112 case AUTH_CONNECTION:
1113 if (sshbuf_len(sockets[i].output) > 0 &&
1114 FD_ISSET(sockets[i].fd, writeset)) {
1115 len = write(sockets[i].fd,
1116 sshbuf_ptr(sockets[i].output),
1117 sshbuf_len(sockets[i].output));
1118 if (len == -1 && (errno == EAGAIN ||
1119 errno == EWOULDBLOCK ||
1123 close_socket(&sockets[i]);
1126 if ((r = sshbuf_consume(sockets[i].output,
1128 fatal("%s: buffer error: %s",
1129 __func__, ssh_err(r));
1131 if (FD_ISSET(sockets[i].fd, readset)) {
1132 len = read(sockets[i].fd, buf, sizeof(buf));
1133 if (len == -1 && (errno == EAGAIN ||
1134 errno == EWOULDBLOCK ||
1138 close_socket(&sockets[i]);
1141 if ((r = sshbuf_put(sockets[i].input,
1143 fatal("%s: buffer error: %s",
1144 __func__, ssh_err(r));
1145 explicit_bzero(buf, sizeof(buf));
1146 process_message(&sockets[i]);
1150 fatal("Unknown type %d", sockets[i].type);
1155 cleanup_socket(void)
1157 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1159 debug("%s: cleanup", __func__);
1161 unlink(socket_name);
1175 cleanup_handler(int sig)
1178 #ifdef ENABLE_PKCS11
1185 check_parent_exists(void)
1188 * If our parent has exited then getppid() will return (pid_t)1,
1189 * so testing for that should be safe.
1191 if (parent_pid != -1 && getppid() != parent_pid) {
1192 /* printf("Parent has died - Authentication agent exiting.\n"); */
1202 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1203 " [-t life] [command [arg ...]]\n"
1204 " ssh-agent [-c | -s] -k\n");
1205 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1210 main(int ac, char **av)
1212 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1213 int sock, fd, ch, result, saved_errno;
1215 char *shell, *format, *pidstr, *agentsocket = NULL;
1216 fd_set *readsetp = NULL, *writesetp = NULL;
1217 #ifdef HAVE_SETRLIMIT
1221 extern char *optarg;
1223 char pidstrbuf[1 + 3 * sizeof pid];
1224 struct timeval *tvp = NULL;
1228 ssh_malloc_init(); /* must be called before any mallocs */
1229 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1237 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1238 /* Disable ptrace on Linux without sgid bit */
1239 prctl(PR_SET_DUMPABLE, 0);
1243 OpenSSL_add_all_algorithms();
1246 __progname = ssh_get_progname(av[0]);
1249 while ((ch = getopt(ac, av, "cDdksE:a:t:x")) != -1) {
1252 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1253 if (fingerprint_hash == -1)
1254 fatal("Invalid hash algorithm \"%s\"", optarg);
1270 if (d_flag || D_flag)
1275 if (d_flag || D_flag)
1280 agentsocket = optarg;
1283 if ((lifetime = convtime(optarg)) == -1) {
1284 fprintf(stderr, "Invalid lifetime\n");
1298 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1301 if (ac == 0 && !c_flag && !s_flag) {
1302 shell = getenv("SHELL");
1303 if (shell != NULL && (len = strlen(shell)) > 2 &&
1304 strncmp(shell + len - 3, "csh", 3) == 0)
1308 const char *errstr = NULL;
1310 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1311 if (pidstr == NULL) {
1312 fprintf(stderr, "%s not set, cannot kill agent\n",
1313 SSH_AGENTPID_ENV_NAME);
1316 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1319 "%s=\"%s\", which is not a good PID: %s\n",
1320 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1323 if (kill(pid, SIGTERM) == -1) {
1327 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1328 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1329 printf(format, SSH_AGENTPID_ENV_NAME);
1330 printf("echo Agent pid %ld killed;\n", (long)pid);
1333 parent_pid = getpid();
1335 if (agentsocket == NULL) {
1336 /* Create private directory for agent socket */
1337 mktemp_proto(socket_dir, sizeof(socket_dir));
1338 if (mkdtemp(socket_dir) == NULL) {
1339 perror("mkdtemp: private socket dir");
1342 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1345 /* Try to use specified agent socket */
1346 socket_dir[0] = '\0';
1347 strlcpy(socket_name, agentsocket, sizeof socket_name);
1351 * Create socket early so it will exist before command gets run from
1354 prev_mask = umask(0177);
1355 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1357 /* XXX - unix_listener() calls error() not perror() */
1358 *socket_name = '\0'; /* Don't unlink any existing file */
1364 * Fork, and have the parent execute the command, if any, or present
1365 * the socket data. The child continues as the authentication agent.
1367 if (D_flag || d_flag) {
1368 log_init(__progname,
1369 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1370 SYSLOG_FACILITY_AUTH, 1);
1371 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1372 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1373 SSH_AUTHSOCKET_ENV_NAME);
1374 printf("echo Agent pid %ld;\n", (long)parent_pid);
1383 if (pid != 0) { /* Parent - execute the given command. */
1385 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1387 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1388 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1389 SSH_AUTHSOCKET_ENV_NAME);
1390 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1391 SSH_AGENTPID_ENV_NAME);
1392 printf("echo Agent pid %ld;\n", (long)pid);
1395 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1396 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1405 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1407 if (setsid() == -1) {
1408 error("setsid: %s", strerror(errno));
1413 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1414 /* XXX might close listen socket */
1415 (void)dup2(fd, STDIN_FILENO);
1416 (void)dup2(fd, STDOUT_FILENO);
1417 (void)dup2(fd, STDERR_FILENO);
1422 #ifdef HAVE_SETRLIMIT
1423 /* deny core dumps, since memory contains unencrypted private keys */
1424 rlim.rlim_cur = rlim.rlim_max = 0;
1425 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1426 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1433 cleanup_pid = getpid();
1435 #ifdef ENABLE_PKCS11
1438 new_socket(AUTH_SOCKET, sock);
1440 parent_alive_interval = 10;
1442 signal(SIGPIPE, SIG_IGN);
1443 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1444 signal(SIGHUP, cleanup_handler);
1445 signal(SIGTERM, cleanup_handler);
1448 if (pledge("stdio cpath unix id proc exec", NULL) == -1)
1449 fatal("%s: pledge: %s", __progname, strerror(errno));
1450 platform_pledge_agent();
1453 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1454 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1455 saved_errno = errno;
1456 if (parent_alive_interval != 0)
1457 check_parent_exists();
1458 (void) reaper(); /* remove expired keys */
1460 if (saved_errno == EINTR)
1462 fatal("select: %s", strerror(saved_errno));
1463 } else if (result > 0)
1464 after_select(readsetp, writesetp);