1 /* $OpenBSD: ssh-agent.c,v 1.204 2015/07/08 20:24:02 markus 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);
393 process_sign_request2(SocketEntry *e)
395 u_char *blob, *data, *signature = NULL;
396 size_t blen, dlen, slen = 0;
397 u_int compat = 0, flags;
403 if ((msg = sshbuf_new()) == NULL)
404 fatal("%s: sshbuf_new failed", __func__);
405 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
406 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
407 (r = sshbuf_get_u32(e->request, &flags)) != 0)
408 fatal("%s: buffer error: %s", __func__, ssh_err(r));
409 if (flags & SSH_AGENT_OLD_SIGNATURE)
410 compat = SSH_BUG_SIGBLOB;
411 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
412 error("%s: cannot parse key blob: %s", __func__, ssh_err(ok));
415 if ((id = lookup_identity(key, 2)) == NULL) {
416 verbose("%s: %s key not found", __func__, sshkey_type(key));
419 if (id->confirm && confirm_key(id) != 0) {
420 verbose("%s: user refused key", __func__);
423 if ((r = sshkey_sign(id->key, &signature, &slen,
424 data, dlen, compat)) != 0) {
425 error("%s: sshkey_sign: %s", __func__, ssh_err(ok));
433 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
434 (r = sshbuf_put_string(msg, signature, slen)) != 0)
435 fatal("%s: buffer error: %s", __func__, ssh_err(r));
436 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
437 fatal("%s: buffer error: %s", __func__, ssh_err(r));
439 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
440 fatal("%s: buffer error: %s", __func__, ssh_err(r));
450 process_remove_identity(SocketEntry *e, int version)
454 struct sshkey *key = NULL;
458 #endif /* WITH_SSH1 */
463 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
464 error("%s: sshkey_new failed", __func__);
467 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
468 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
469 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
470 fatal("%s: buffer error: %s", __func__, ssh_err(r));
472 if (bits != sshkey_size(key))
473 logit("Warning: identity keysize mismatch: "
474 "actual %u, announced %u",
475 sshkey_size(key), bits);
477 #endif /* WITH_SSH1 */
479 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
480 fatal("%s: buffer error: %s", __func__, ssh_err(r));
481 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
482 error("%s: sshkey_from_blob failed: %s",
483 __func__, ssh_err(r));
488 Identity *id = lookup_identity(key, version);
491 * We have this key. Free the old key. Since we
492 * don't want to leave empty slots in the middle of
493 * the array, we actually free the key there and move
494 * all the entries between the empty slot and the end
497 Idtab *tab = idtab_lookup(version);
498 if (tab->nentries < 1)
499 fatal("process_remove_identity: "
500 "internal error: tab->nentries %d",
502 TAILQ_REMOVE(&tab->idlist, id, next);
509 send_status(e, success);
513 process_remove_all_identities(SocketEntry *e, int version)
515 Idtab *tab = idtab_lookup(version);
518 /* Loop over all identities and clear the keys. */
519 for (id = TAILQ_FIRST(&tab->idlist); id;
520 id = TAILQ_FIRST(&tab->idlist)) {
521 TAILQ_REMOVE(&tab->idlist, id, next);
525 /* Mark that there are no identities. */
532 /* removes expired keys and returns number of seconds until the next expiry */
536 time_t deadline = 0, now = monotime();
541 for (version = 1; version < 3; version++) {
542 tab = idtab_lookup(version);
543 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
544 nxt = TAILQ_NEXT(id, next);
547 if (now >= id->death) {
548 debug("expiring key '%s'", id->comment);
549 TAILQ_REMOVE(&tab->idlist, id, next);
553 deadline = (deadline == 0) ? id->death :
554 MIN(deadline, id->death);
557 if (deadline == 0 || deadline <= now)
560 return (deadline - now);
564 * XXX this and the corresponding serialisation function probably belongs
569 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
571 struct sshkey *k = NULL;
572 int r = SSH_ERR_INTERNAL_ERROR;
575 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
576 return SSH_ERR_ALLOC_FAIL;
578 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
579 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
580 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
581 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
582 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
583 /* SSH1 and SSL have p and q swapped */
584 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
585 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
588 /* Generate additional parameters */
589 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
591 /* enable blinding */
592 if (RSA_blinding_on(k->rsa, NULL) != 1) {
593 r = SSH_ERR_LIBCRYPTO_ERROR;
605 #endif /* WITH_SSH1 */
608 process_add_identity(SocketEntry *e, int version)
610 Idtab *tab = idtab_lookup(version);
612 int success = 0, confirm = 0;
614 char *comment = NULL;
616 struct sshkey *k = NULL;
618 int r = SSH_ERR_INTERNAL_ERROR;
623 r = agent_decode_rsa1(e->request, &k);
625 #endif /* WITH_SSH1 */
627 r = sshkey_private_deserialize(e->request, &k);
630 if (r != 0 || k == NULL ||
631 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
632 error("%s: decode private key: %s", __func__, ssh_err(r));
636 while (sshbuf_len(e->request)) {
637 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
638 error("%s: buffer error: %s", __func__, ssh_err(r));
642 case SSH_AGENT_CONSTRAIN_LIFETIME:
643 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
644 error("%s: bad lifetime constraint: %s",
645 __func__, ssh_err(r));
648 death = monotime() + seconds;
650 case SSH_AGENT_CONSTRAIN_CONFIRM:
654 error("%s: Unknown constraint %d", __func__, ctype);
656 sshbuf_reset(e->request);
664 if (lifetime && !death)
665 death = monotime() + lifetime;
666 if ((id = lookup_identity(k, version)) == NULL) {
667 id = xcalloc(1, sizeof(Identity));
669 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
670 /* Increment the number of identities. */
676 id->comment = comment;
678 id->confirm = confirm;
680 send_status(e, success);
683 /* XXX todo: encrypt sensitive data with passphrase */
685 process_lock_agent(SocketEntry *e, int lock)
687 int r, success = 0, delay;
688 char *passwd, passwdhash[LOCK_SIZE];
689 static u_int fail_count = 0;
692 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
693 fatal("%s: buffer error: %s", __func__, ssh_err(r));
695 debug("empty password not supported");
696 } else if (locked && !lock) {
697 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
698 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
699 fatal("bcrypt_pbkdf");
700 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
701 debug("agent unlocked");
704 explicit_bzero(lock_passwd, sizeof(lock_passwd));
707 /* delay in 0.1s increments up to 10s */
708 if (fail_count < 100)
710 delay = 100000 * fail_count;
711 debug("unlock failed, delaying %0.1lf seconds",
712 (double)delay/1000000);
715 explicit_bzero(passwdhash, sizeof(passwdhash));
716 } else if (!locked && lock) {
717 debug("agent locked");
719 arc4random_buf(lock_salt, sizeof(lock_salt));
720 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
721 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
722 fatal("bcrypt_pbkdf");
725 explicit_bzero(passwd, pwlen);
727 send_status(e, success);
731 no_identities(SocketEntry *e, u_int type)
736 if ((msg = sshbuf_new()) == NULL)
737 fatal("%s: sshbuf_new failed", __func__);
738 if ((r = sshbuf_put_u8(msg,
739 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
740 SSH_AGENT_RSA_IDENTITIES_ANSWER :
741 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
742 (r = sshbuf_put_u32(msg, 0)) != 0 ||
743 (r = sshbuf_put_stringb(e->output, msg)) != 0)
744 fatal("%s: buffer error: %s", __func__, ssh_err(r));
750 process_add_smartcard_key(SocketEntry *e)
752 char *provider = NULL, *pin;
753 int r, i, version, count = 0, success = 0, confirm = 0;
757 struct sshkey **keys = NULL, *k;
761 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
762 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
763 fatal("%s: buffer error: %s", __func__, ssh_err(r));
765 while (sshbuf_len(e->request)) {
766 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
767 fatal("%s: buffer error: %s", __func__, ssh_err(r));
769 case SSH_AGENT_CONSTRAIN_LIFETIME:
770 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
771 fatal("%s: buffer error: %s",
772 __func__, ssh_err(r));
773 death = monotime() + seconds;
775 case SSH_AGENT_CONSTRAIN_CONFIRM:
779 error("process_add_smartcard_key: "
780 "Unknown constraint type %d", type);
784 if (lifetime && !death)
785 death = monotime() + lifetime;
787 count = pkcs11_add_provider(provider, pin, &keys);
788 for (i = 0; i < count; i++) {
790 version = k->type == KEY_RSA1 ? 1 : 2;
791 tab = idtab_lookup(version);
792 if (lookup_identity(k, version) == NULL) {
793 id = xcalloc(1, sizeof(Identity));
795 id->provider = xstrdup(provider);
796 id->comment = xstrdup(provider); /* XXX */
798 id->confirm = confirm;
799 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
811 send_status(e, success);
815 process_remove_smartcard_key(SocketEntry *e)
817 char *provider = NULL, *pin = NULL;
818 int r, version, success = 0;
822 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
823 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
824 fatal("%s: buffer error: %s", __func__, ssh_err(r));
827 for (version = 1; version < 3; version++) {
828 tab = idtab_lookup(version);
829 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
830 nxt = TAILQ_NEXT(id, next);
831 /* Skip file--based keys */
832 if (id->provider == NULL)
834 if (!strcmp(provider, id->provider)) {
835 TAILQ_REMOVE(&tab->idlist, id, next);
841 if (pkcs11_del_provider(provider) == 0)
844 error("process_remove_smartcard_key:"
845 " pkcs11_del_provider failed");
847 send_status(e, success);
849 #endif /* ENABLE_PKCS11 */
851 /* dispatch incoming messages */
854 process_message(SocketEntry *e)
861 if (sshbuf_len(e->input) < 5)
862 return; /* Incomplete message. */
863 cp = sshbuf_ptr(e->input);
864 msg_len = PEEK_U32(cp);
865 if (msg_len > 256 * 1024) {
869 if (sshbuf_len(e->input) < msg_len + 4)
872 /* move the current input to e->request */
873 sshbuf_reset(e->request);
874 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
875 (r = sshbuf_get_u8(e->request, &type)) != 0)
876 fatal("%s: buffer error: %s", __func__, ssh_err(r));
878 /* check wheter agent is locked */
879 if (locked && type != SSH_AGENTC_UNLOCK) {
880 sshbuf_reset(e->request);
882 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
883 case SSH2_AGENTC_REQUEST_IDENTITIES:
884 /* send empty lists */
885 no_identities(e, type);
888 /* send a fail message for all other request types */
894 debug("type %d", type);
896 case SSH_AGENTC_LOCK:
897 case SSH_AGENTC_UNLOCK:
898 process_lock_agent(e, type == SSH_AGENTC_LOCK);
902 case SSH_AGENTC_RSA_CHALLENGE:
903 process_authentication_challenge1(e);
905 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
906 process_request_identities(e, 1);
908 case SSH_AGENTC_ADD_RSA_IDENTITY:
909 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
910 process_add_identity(e, 1);
912 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
913 process_remove_identity(e, 1);
916 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
917 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
920 case SSH2_AGENTC_SIGN_REQUEST:
921 process_sign_request2(e);
923 case SSH2_AGENTC_REQUEST_IDENTITIES:
924 process_request_identities(e, 2);
926 case SSH2_AGENTC_ADD_IDENTITY:
927 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
928 process_add_identity(e, 2);
930 case SSH2_AGENTC_REMOVE_IDENTITY:
931 process_remove_identity(e, 2);
933 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
934 process_remove_all_identities(e, 2);
937 case SSH_AGENTC_ADD_SMARTCARD_KEY:
938 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
939 process_add_smartcard_key(e);
941 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
942 process_remove_smartcard_key(e);
944 #endif /* ENABLE_PKCS11 */
946 /* Unknown message. Respond with failure. */
947 error("Unknown message %d", type);
948 sshbuf_reset(e->request);
955 new_socket(sock_type type, int fd)
957 u_int i, old_alloc, new_alloc;
959 if (type == AUTH_CONNECTION) {
960 debug("xcount %d -> %d", xcount, xcount + 1);
968 for (i = 0; i < sockets_alloc; i++)
969 if (sockets[i].type == AUTH_UNUSED) {
971 if ((sockets[i].input = sshbuf_new()) == NULL)
972 fatal("%s: sshbuf_new failed", __func__);
973 if ((sockets[i].output = sshbuf_new()) == NULL)
974 fatal("%s: sshbuf_new failed", __func__);
975 if ((sockets[i].request = sshbuf_new()) == NULL)
976 fatal("%s: sshbuf_new failed", __func__);
977 sockets[i].type = type;
980 old_alloc = sockets_alloc;
981 new_alloc = sockets_alloc + 10;
982 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
983 for (i = old_alloc; i < new_alloc; i++)
984 sockets[i].type = AUTH_UNUSED;
985 sockets_alloc = new_alloc;
986 sockets[old_alloc].fd = fd;
987 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
988 fatal("%s: sshbuf_new failed", __func__);
989 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
990 fatal("%s: sshbuf_new failed", __func__);
991 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
992 fatal("%s: sshbuf_new failed", __func__);
993 sockets[old_alloc].type = type;
997 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
998 struct timeval **tvpp)
1002 static struct timeval tv;
1005 for (i = 0; i < sockets_alloc; i++) {
1006 switch (sockets[i].type) {
1008 case AUTH_CONNECTION:
1009 n = MAX(n, sockets[i].fd);
1014 fatal("Unknown socket type %d", sockets[i].type);
1019 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1020 if (*fdrp == NULL || sz > *nallocp) {
1023 *fdrp = xmalloc(sz);
1024 *fdwp = xmalloc(sz);
1028 debug("XXX shrink: %d < %d", n, *fdl);
1030 memset(*fdrp, 0, sz);
1031 memset(*fdwp, 0, sz);
1033 for (i = 0; i < sockets_alloc; i++) {
1034 switch (sockets[i].type) {
1036 case AUTH_CONNECTION:
1037 FD_SET(sockets[i].fd, *fdrp);
1038 if (sshbuf_len(sockets[i].output) > 0)
1039 FD_SET(sockets[i].fd, *fdwp);
1045 deadline = reaper();
1046 if (parent_alive_interval != 0)
1047 deadline = (deadline == 0) ? parent_alive_interval :
1048 MIN(deadline, parent_alive_interval);
1049 if (deadline == 0) {
1052 tv.tv_sec = deadline;
1060 after_select(fd_set *readset, fd_set *writeset)
1062 struct sockaddr_un sunaddr;
1066 u_int i, orig_alloc;
1070 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1071 switch (sockets[i].type) {
1075 if (FD_ISSET(sockets[i].fd, readset)) {
1076 slen = sizeof(sunaddr);
1077 sock = accept(sockets[i].fd,
1078 (struct sockaddr *)&sunaddr, &slen);
1080 error("accept from AUTH_SOCKET: %s",
1084 if (getpeereid(sock, &euid, &egid) < 0) {
1085 error("getpeereid %d failed: %s",
1086 sock, strerror(errno));
1090 if ((euid != 0) && (getuid() != euid)) {
1091 error("uid mismatch: "
1092 "peer euid %u != uid %u",
1093 (u_int) euid, (u_int) getuid());
1097 new_socket(AUTH_CONNECTION, sock);
1100 case AUTH_CONNECTION:
1101 if (sshbuf_len(sockets[i].output) > 0 &&
1102 FD_ISSET(sockets[i].fd, writeset)) {
1103 len = write(sockets[i].fd,
1104 sshbuf_ptr(sockets[i].output),
1105 sshbuf_len(sockets[i].output));
1106 if (len == -1 && (errno == EAGAIN ||
1107 errno == EWOULDBLOCK ||
1111 close_socket(&sockets[i]);
1114 if ((r = sshbuf_consume(sockets[i].output,
1116 fatal("%s: buffer error: %s",
1117 __func__, ssh_err(r));
1119 if (FD_ISSET(sockets[i].fd, readset)) {
1120 len = read(sockets[i].fd, buf, sizeof(buf));
1121 if (len == -1 && (errno == EAGAIN ||
1122 errno == EWOULDBLOCK ||
1126 close_socket(&sockets[i]);
1129 if ((r = sshbuf_put(sockets[i].input,
1131 fatal("%s: buffer error: %s",
1132 __func__, ssh_err(r));
1133 explicit_bzero(buf, sizeof(buf));
1134 process_message(&sockets[i]);
1138 fatal("Unknown type %d", sockets[i].type);
1143 cleanup_socket(void)
1145 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1147 debug("%s: cleanup", __func__);
1149 unlink(socket_name);
1163 cleanup_handler(int sig)
1166 #ifdef ENABLE_PKCS11
1173 check_parent_exists(void)
1176 * If our parent has exited then getppid() will return (pid_t)1,
1177 * so testing for that should be safe.
1179 if (parent_pid != -1 && getppid() != parent_pid) {
1180 /* printf("Parent has died - Authentication agent exiting.\n"); */
1190 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1191 " [-t life] [command [arg ...]]\n"
1192 " ssh-agent [-c | -s] -k\n");
1193 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1198 main(int ac, char **av)
1200 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1201 int sock, fd, ch, result, saved_errno;
1203 char *shell, *format, *pidstr, *agentsocket = NULL;
1204 fd_set *readsetp = NULL, *writesetp = NULL;
1205 #ifdef HAVE_SETRLIMIT
1209 extern char *optarg;
1211 char pidstrbuf[1 + 3 * sizeof pid];
1212 struct timeval *tvp = NULL;
1216 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1224 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1225 /* Disable ptrace on Linux without sgid bit */
1226 prctl(PR_SET_DUMPABLE, 0);
1230 OpenSSL_add_all_algorithms();
1233 __progname = ssh_get_progname(av[0]);
1236 while ((ch = getopt(ac, av, "cDdksE:a:t:x")) != -1) {
1239 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1240 if (fingerprint_hash == -1)
1241 fatal("Invalid hash algorithm \"%s\"", optarg);
1257 if (d_flag || D_flag)
1262 if (d_flag || D_flag)
1267 agentsocket = optarg;
1270 if ((lifetime = convtime(optarg)) == -1) {
1271 fprintf(stderr, "Invalid lifetime\n");
1285 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1288 if (ac == 0 && !c_flag && !s_flag) {
1289 shell = getenv("SHELL");
1290 if (shell != NULL && (len = strlen(shell)) > 2 &&
1291 strncmp(shell + len - 3, "csh", 3) == 0)
1295 const char *errstr = NULL;
1297 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1298 if (pidstr == NULL) {
1299 fprintf(stderr, "%s not set, cannot kill agent\n",
1300 SSH_AGENTPID_ENV_NAME);
1303 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1306 "%s=\"%s\", which is not a good PID: %s\n",
1307 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1310 if (kill(pid, SIGTERM) == -1) {
1314 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1315 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1316 printf(format, SSH_AGENTPID_ENV_NAME);
1317 printf("echo Agent pid %ld killed;\n", (long)pid);
1320 parent_pid = getpid();
1322 if (agentsocket == NULL) {
1323 /* Create private directory for agent socket */
1324 mktemp_proto(socket_dir, sizeof(socket_dir));
1325 if (mkdtemp(socket_dir) == NULL) {
1326 perror("mkdtemp: private socket dir");
1329 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1332 /* Try to use specified agent socket */
1333 socket_dir[0] = '\0';
1334 strlcpy(socket_name, agentsocket, sizeof socket_name);
1338 * Create socket early so it will exist before command gets run from
1341 prev_mask = umask(0177);
1342 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1344 /* XXX - unix_listener() calls error() not perror() */
1345 *socket_name = '\0'; /* Don't unlink any existing file */
1351 * Fork, and have the parent execute the command, if any, or present
1352 * the socket data. The child continues as the authentication agent.
1354 if (D_flag || d_flag) {
1355 log_init(__progname,
1356 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1357 SYSLOG_FACILITY_AUTH, 1);
1358 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1359 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1360 SSH_AUTHSOCKET_ENV_NAME);
1361 printf("echo Agent pid %ld;\n", (long)parent_pid);
1369 if (pid != 0) { /* Parent - execute the given command. */
1371 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1373 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1374 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1375 SSH_AUTHSOCKET_ENV_NAME);
1376 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1377 SSH_AGENTPID_ENV_NAME);
1378 printf("echo Agent pid %ld;\n", (long)pid);
1381 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1382 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1391 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1393 if (setsid() == -1) {
1394 error("setsid: %s", strerror(errno));
1399 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1400 /* XXX might close listen socket */
1401 (void)dup2(fd, STDIN_FILENO);
1402 (void)dup2(fd, STDOUT_FILENO);
1403 (void)dup2(fd, STDERR_FILENO);
1408 #ifdef HAVE_SETRLIMIT
1409 /* deny core dumps, since memory contains unencrypted private keys */
1410 rlim.rlim_cur = rlim.rlim_max = 0;
1411 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1412 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1419 cleanup_pid = getpid();
1421 #ifdef ENABLE_PKCS11
1424 new_socket(AUTH_SOCKET, sock);
1426 parent_alive_interval = 10;
1428 signal(SIGPIPE, SIG_IGN);
1429 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1430 signal(SIGHUP, cleanup_handler);
1431 signal(SIGTERM, cleanup_handler);
1435 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1436 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1437 saved_errno = errno;
1438 if (parent_alive_interval != 0)
1439 check_parent_exists();
1440 (void) reaper(); /* remove expired keys */
1442 if (saved_errno == EINTR)
1444 fatal("select: %s", strerror(saved_errno));
1445 } else if (result > 0)
1446 after_select(readsetp, writesetp);