1 /* $OpenBSD: ssh-agent.c,v 1.203 2015/05/15 05:44:21 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.
39 #include <sys/param.h> /* MIN MAX */
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"
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
75 #include "key.h" /* XXX for typedef */
76 #include "buffer.h" /* XXX for typedef */
91 #include "ssh-pkcs11.h"
94 #if defined(HAVE_SYS_PRCTL_H)
95 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
107 struct sshbuf *input;
108 struct sshbuf *output;
109 struct sshbuf *request;
112 u_int sockets_alloc = 0;
113 SocketEntry *sockets = NULL;
115 typedef struct identity {
116 TAILQ_ENTRY(identity) next;
126 TAILQ_HEAD(idqueue, identity) idlist;
129 /* private key table, one per protocol version */
134 /* pid of shell == parent of agent */
135 pid_t parent_pid = -1;
136 time_t parent_alive_interval = 0;
138 /* pid of process for which cleanup_socket is applicable */
139 pid_t cleanup_pid = 0;
141 /* pathname and directory for AUTH_SOCKET */
142 char socket_name[PATH_MAX];
143 char socket_dir[PATH_MAX];
147 #define LOCK_SALT_SIZE 16
148 #define LOCK_ROUNDS 1
150 char lock_passwd[LOCK_SIZE];
151 char lock_salt[LOCK_SALT_SIZE];
153 extern char *__progname;
155 /* Default lifetime in seconds (0 == forever) */
156 static long lifetime = 0;
158 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
161 close_socket(SocketEntry *e)
165 e->type = AUTH_UNUSED;
166 sshbuf_free(e->input);
167 sshbuf_free(e->output);
168 sshbuf_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)
194 sshkey_free(id->key);
200 /* return matching private key for given public key */
202 lookup_identity(struct sshkey *key, int version)
206 Idtab *tab = idtab_lookup(version);
207 TAILQ_FOREACH(id, &tab->idlist, next) {
208 if (sshkey_equal(key, id->key))
214 /* Check confirmation of keysign request */
216 confirm_key(Identity *id)
221 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
223 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
232 send_status(SocketEntry *e, int success)
236 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
237 (r = sshbuf_put_u8(e->output, success ?
238 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
239 fatal("%s: buffer error: %s", __func__, ssh_err(r));
242 /* send list of supported public keys to 'client' */
244 process_request_identities(SocketEntry *e, int version)
246 Idtab *tab = idtab_lookup(version);
251 if ((msg = sshbuf_new()) == NULL)
252 fatal("%s: sshbuf_new failed", __func__);
253 if ((r = sshbuf_put_u8(msg, (version == 1) ?
254 SSH_AGENT_RSA_IDENTITIES_ANSWER :
255 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
256 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
257 fatal("%s: buffer error: %s", __func__, ssh_err(r));
258 TAILQ_FOREACH(id, &tab->idlist, next) {
259 if (id->key->type == KEY_RSA1) {
261 if ((r = sshbuf_put_u32(msg,
262 BN_num_bits(id->key->rsa->n))) != 0 ||
263 (r = sshbuf_put_bignum1(msg,
264 id->key->rsa->e)) != 0 ||
265 (r = sshbuf_put_bignum1(msg,
266 id->key->rsa->n)) != 0)
267 fatal("%s: buffer error: %s",
268 __func__, ssh_err(r));
274 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
275 error("%s: sshkey_to_blob: %s", __func__,
279 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
280 fatal("%s: buffer error: %s",
281 __func__, ssh_err(r));
284 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
285 fatal("%s: buffer error: %s", __func__, ssh_err(r));
287 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
288 fatal("%s: buffer error: %s", __func__, ssh_err(r));
295 process_authentication_challenge1(SocketEntry *e)
297 u_char buf[32], mdbuf[16], session_id[16];
303 struct ssh_digest_ctx *md;
306 if ((msg = sshbuf_new()) == NULL)
307 fatal("%s: sshbuf_new failed", __func__);
308 if ((key = sshkey_new(KEY_RSA1)) == NULL)
309 fatal("%s: sshkey_new failed", __func__);
310 if ((challenge = BN_new()) == NULL)
311 fatal("%s: BN_new failed", __func__);
313 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
314 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
315 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
316 (r = sshbuf_get_bignum1(e->request, challenge)))
317 fatal("%s: buffer error: %s", __func__, ssh_err(r));
319 /* Only protocol 1.1 is supported */
320 if (sshbuf_len(e->request) == 0)
322 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
323 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
324 fatal("%s: buffer error: %s", __func__, ssh_err(r));
325 if (response_type != 1)
328 id = lookup_identity(key, 1);
329 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
330 struct sshkey *private = id->key;
331 /* Decrypt the challenge using the private key. */
332 if ((r = rsa_private_decrypt(challenge, challenge,
333 private->rsa) != 0)) {
334 fatal("%s: rsa_public_encrypt: %s", __func__,
336 goto failure; /* XXX ? */
339 /* The response is MD5 of decrypted challenge plus session id */
340 len = BN_num_bytes(challenge);
341 if (len <= 0 || len > 32) {
342 logit("%s: bad challenge length %d", __func__, len);
346 BN_bn2bin(challenge, buf + 32 - len);
347 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
348 ssh_digest_update(md, buf, 32) < 0 ||
349 ssh_digest_update(md, session_id, 16) < 0 ||
350 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
351 fatal("%s: md5 failed", __func__);
354 /* Send the response. */
355 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
356 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
357 fatal("%s: buffer error: %s", __func__, ssh_err(r));
362 /* Unknown identity or protocol error. Send failure. */
363 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
364 fatal("%s: buffer error: %s", __func__, ssh_err(r));
366 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
367 fatal("%s: buffer error: %s", __func__, ssh_err(r));
369 BN_clear_free(challenge);
376 process_sign_request2(SocketEntry *e)
378 u_char *blob, *data, *signature = NULL;
379 size_t blen, dlen, slen = 0;
380 u_int compat = 0, flags;
386 if ((msg = sshbuf_new()) == NULL)
387 fatal("%s: sshbuf_new failed", __func__);
388 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
389 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
390 (r = sshbuf_get_u32(e->request, &flags)) != 0)
391 fatal("%s: buffer error: %s", __func__, ssh_err(r));
392 if (flags & SSH_AGENT_OLD_SIGNATURE)
393 compat = SSH_BUG_SIGBLOB;
394 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
395 error("%s: cannot parse key blob: %s", __func__, ssh_err(ok));
398 if ((id = lookup_identity(key, 2)) == NULL) {
399 verbose("%s: %s key not found", __func__, sshkey_type(key));
402 if (id->confirm && confirm_key(id) != 0) {
403 verbose("%s: user refused key", __func__);
406 if ((r = sshkey_sign(id->key, &signature, &slen,
407 data, dlen, compat)) != 0) {
408 error("%s: sshkey_sign: %s", __func__, ssh_err(ok));
416 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
417 (r = sshbuf_put_string(msg, signature, slen)) != 0)
418 fatal("%s: buffer error: %s", __func__, ssh_err(r));
419 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
420 fatal("%s: buffer error: %s", __func__, ssh_err(r));
422 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
423 fatal("%s: buffer error: %s", __func__, ssh_err(r));
433 process_remove_identity(SocketEntry *e, int version)
437 struct sshkey *key = NULL;
441 #endif /* WITH_SSH1 */
446 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
447 error("%s: sshkey_new failed", __func__);
450 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
451 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
452 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
453 fatal("%s: buffer error: %s", __func__, ssh_err(r));
455 if (bits != sshkey_size(key))
456 logit("Warning: identity keysize mismatch: "
457 "actual %u, announced %u",
458 sshkey_size(key), bits);
460 #endif /* WITH_SSH1 */
462 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
463 fatal("%s: buffer error: %s", __func__, ssh_err(r));
464 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
465 error("%s: sshkey_from_blob failed: %s",
466 __func__, ssh_err(r));
471 Identity *id = lookup_identity(key, version);
474 * We have this key. Free the old key. Since we
475 * don't want to leave empty slots in the middle of
476 * the array, we actually free the key there and move
477 * all the entries between the empty slot and the end
480 Idtab *tab = idtab_lookup(version);
481 if (tab->nentries < 1)
482 fatal("process_remove_identity: "
483 "internal error: tab->nentries %d",
485 TAILQ_REMOVE(&tab->idlist, id, next);
492 send_status(e, success);
496 process_remove_all_identities(SocketEntry *e, int version)
498 Idtab *tab = idtab_lookup(version);
501 /* Loop over all identities and clear the keys. */
502 for (id = TAILQ_FIRST(&tab->idlist); id;
503 id = TAILQ_FIRST(&tab->idlist)) {
504 TAILQ_REMOVE(&tab->idlist, id, next);
508 /* Mark that there are no identities. */
515 /* removes expired keys and returns number of seconds until the next expiry */
519 time_t deadline = 0, now = monotime();
524 for (version = 1; version < 3; version++) {
525 tab = idtab_lookup(version);
526 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
527 nxt = TAILQ_NEXT(id, next);
530 if (now >= id->death) {
531 debug("expiring key '%s'", id->comment);
532 TAILQ_REMOVE(&tab->idlist, id, next);
536 deadline = (deadline == 0) ? id->death :
537 MIN(deadline, id->death);
540 if (deadline == 0 || deadline <= now)
543 return (deadline - now);
547 * XXX this and the corresponding serialisation function probably belongs
552 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
554 struct sshkey *k = NULL;
555 int r = SSH_ERR_INTERNAL_ERROR;
558 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
559 return SSH_ERR_ALLOC_FAIL;
561 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
562 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
563 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
564 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
565 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
566 /* SSH1 and SSL have p and q swapped */
567 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
568 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
571 /* Generate additional parameters */
572 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
574 /* enable blinding */
575 if (RSA_blinding_on(k->rsa, NULL) != 1) {
576 r = SSH_ERR_LIBCRYPTO_ERROR;
588 #endif /* WITH_SSH1 */
591 process_add_identity(SocketEntry *e, int version)
593 Idtab *tab = idtab_lookup(version);
595 int success = 0, confirm = 0;
597 char *comment = NULL;
599 struct sshkey *k = NULL;
601 int r = SSH_ERR_INTERNAL_ERROR;
606 r = agent_decode_rsa1(e->request, &k);
608 #endif /* WITH_SSH1 */
610 r = sshkey_private_deserialize(e->request, &k);
613 if (r != 0 || k == NULL ||
614 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
615 error("%s: decode private key: %s", __func__, ssh_err(r));
619 while (sshbuf_len(e->request)) {
620 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
621 error("%s: buffer error: %s", __func__, ssh_err(r));
625 case SSH_AGENT_CONSTRAIN_LIFETIME:
626 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
627 error("%s: bad lifetime constraint: %s",
628 __func__, ssh_err(r));
631 death = monotime() + seconds;
633 case SSH_AGENT_CONSTRAIN_CONFIRM:
637 error("%s: Unknown constraint %d", __func__, ctype);
639 sshbuf_reset(e->request);
647 if (lifetime && !death)
648 death = monotime() + lifetime;
649 if ((id = lookup_identity(k, version)) == NULL) {
650 id = xcalloc(1, sizeof(Identity));
652 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
653 /* Increment the number of identities. */
659 id->comment = comment;
661 id->confirm = confirm;
663 send_status(e, success);
666 /* XXX todo: encrypt sensitive data with passphrase */
668 process_lock_agent(SocketEntry *e, int lock)
670 int r, success = 0, delay;
671 char *passwd, passwdhash[LOCK_SIZE];
672 static u_int fail_count = 0;
675 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
676 fatal("%s: buffer error: %s", __func__, ssh_err(r));
678 debug("empty password not supported");
679 } else if (locked && !lock) {
680 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
681 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
682 fatal("bcrypt_pbkdf");
683 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
684 debug("agent unlocked");
687 explicit_bzero(lock_passwd, sizeof(lock_passwd));
690 /* delay in 0.1s increments up to 10s */
691 if (fail_count < 100)
693 delay = 100000 * fail_count;
694 debug("unlock failed, delaying %0.1lf seconds",
695 (double)delay/1000000);
698 explicit_bzero(passwdhash, sizeof(passwdhash));
699 } else if (!locked && lock) {
700 debug("agent locked");
702 arc4random_buf(lock_salt, sizeof(lock_salt));
703 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
704 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
705 fatal("bcrypt_pbkdf");
708 explicit_bzero(passwd, pwlen);
710 send_status(e, success);
714 no_identities(SocketEntry *e, u_int type)
719 if ((msg = sshbuf_new()) == NULL)
720 fatal("%s: sshbuf_new failed", __func__);
721 if ((r = sshbuf_put_u8(msg,
722 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
723 SSH_AGENT_RSA_IDENTITIES_ANSWER :
724 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
725 (r = sshbuf_put_u32(msg, 0)) != 0 ||
726 (r = sshbuf_put_stringb(e->output, msg)) != 0)
727 fatal("%s: buffer error: %s", __func__, ssh_err(r));
733 process_add_smartcard_key(SocketEntry *e)
735 char *provider = NULL, *pin;
736 int r, i, version, count = 0, success = 0, confirm = 0;
740 struct sshkey **keys = NULL, *k;
744 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
745 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
746 fatal("%s: buffer error: %s", __func__, ssh_err(r));
748 while (sshbuf_len(e->request)) {
749 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
750 fatal("%s: buffer error: %s", __func__, ssh_err(r));
752 case SSH_AGENT_CONSTRAIN_LIFETIME:
753 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
754 fatal("%s: buffer error: %s",
755 __func__, ssh_err(r));
756 death = monotime() + seconds;
758 case SSH_AGENT_CONSTRAIN_CONFIRM:
762 error("process_add_smartcard_key: "
763 "Unknown constraint type %d", type);
767 if (lifetime && !death)
768 death = monotime() + lifetime;
770 count = pkcs11_add_provider(provider, pin, &keys);
771 for (i = 0; i < count; i++) {
773 version = k->type == KEY_RSA1 ? 1 : 2;
774 tab = idtab_lookup(version);
775 if (lookup_identity(k, version) == NULL) {
776 id = xcalloc(1, sizeof(Identity));
778 id->provider = xstrdup(provider);
779 id->comment = xstrdup(provider); /* XXX */
781 id->confirm = confirm;
782 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
794 send_status(e, success);
798 process_remove_smartcard_key(SocketEntry *e)
800 char *provider = NULL, *pin = NULL;
801 int r, version, success = 0;
805 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
806 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
807 fatal("%s: buffer error: %s", __func__, ssh_err(r));
810 for (version = 1; version < 3; version++) {
811 tab = idtab_lookup(version);
812 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
813 nxt = TAILQ_NEXT(id, next);
814 /* Skip file--based keys */
815 if (id->provider == NULL)
817 if (!strcmp(provider, id->provider)) {
818 TAILQ_REMOVE(&tab->idlist, id, next);
824 if (pkcs11_del_provider(provider) == 0)
827 error("process_remove_smartcard_key:"
828 " pkcs11_del_provider failed");
830 send_status(e, success);
832 #endif /* ENABLE_PKCS11 */
834 /* dispatch incoming messages */
837 process_message(SocketEntry *e)
844 if (sshbuf_len(e->input) < 5)
845 return; /* Incomplete message. */
846 cp = sshbuf_ptr(e->input);
847 msg_len = PEEK_U32(cp);
848 if (msg_len > 256 * 1024) {
852 if (sshbuf_len(e->input) < msg_len + 4)
855 /* move the current input to e->request */
856 sshbuf_reset(e->request);
857 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
858 (r = sshbuf_get_u8(e->request, &type)) != 0)
859 fatal("%s: buffer error: %s", __func__, ssh_err(r));
861 /* check wheter agent is locked */
862 if (locked && type != SSH_AGENTC_UNLOCK) {
863 sshbuf_reset(e->request);
865 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
866 case SSH2_AGENTC_REQUEST_IDENTITIES:
867 /* send empty lists */
868 no_identities(e, type);
871 /* send a fail message for all other request types */
877 debug("type %d", type);
879 case SSH_AGENTC_LOCK:
880 case SSH_AGENTC_UNLOCK:
881 process_lock_agent(e, type == SSH_AGENTC_LOCK);
885 case SSH_AGENTC_RSA_CHALLENGE:
886 process_authentication_challenge1(e);
888 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
889 process_request_identities(e, 1);
891 case SSH_AGENTC_ADD_RSA_IDENTITY:
892 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
893 process_add_identity(e, 1);
895 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
896 process_remove_identity(e, 1);
899 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
900 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
903 case SSH2_AGENTC_SIGN_REQUEST:
904 process_sign_request2(e);
906 case SSH2_AGENTC_REQUEST_IDENTITIES:
907 process_request_identities(e, 2);
909 case SSH2_AGENTC_ADD_IDENTITY:
910 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
911 process_add_identity(e, 2);
913 case SSH2_AGENTC_REMOVE_IDENTITY:
914 process_remove_identity(e, 2);
916 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
917 process_remove_all_identities(e, 2);
920 case SSH_AGENTC_ADD_SMARTCARD_KEY:
921 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
922 process_add_smartcard_key(e);
924 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
925 process_remove_smartcard_key(e);
927 #endif /* ENABLE_PKCS11 */
929 /* Unknown message. Respond with failure. */
930 error("Unknown message %d", type);
931 sshbuf_reset(e->request);
938 new_socket(sock_type type, int fd)
940 u_int i, old_alloc, new_alloc;
947 for (i = 0; i < sockets_alloc; i++)
948 if (sockets[i].type == AUTH_UNUSED) {
950 if ((sockets[i].input = sshbuf_new()) == NULL)
951 fatal("%s: sshbuf_new failed", __func__);
952 if ((sockets[i].output = sshbuf_new()) == NULL)
953 fatal("%s: sshbuf_new failed", __func__);
954 if ((sockets[i].request = sshbuf_new()) == NULL)
955 fatal("%s: sshbuf_new failed", __func__);
956 sockets[i].type = type;
959 old_alloc = sockets_alloc;
960 new_alloc = sockets_alloc + 10;
961 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
962 for (i = old_alloc; i < new_alloc; i++)
963 sockets[i].type = AUTH_UNUSED;
964 sockets_alloc = new_alloc;
965 sockets[old_alloc].fd = fd;
966 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
967 fatal("%s: sshbuf_new failed", __func__);
968 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
969 fatal("%s: sshbuf_new failed", __func__);
970 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
971 fatal("%s: sshbuf_new failed", __func__);
972 sockets[old_alloc].type = type;
976 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
977 struct timeval **tvpp)
981 static struct timeval tv;
984 for (i = 0; i < sockets_alloc; i++) {
985 switch (sockets[i].type) {
987 case AUTH_CONNECTION:
988 n = MAX(n, sockets[i].fd);
993 fatal("Unknown socket type %d", sockets[i].type);
998 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
999 if (*fdrp == NULL || sz > *nallocp) {
1002 *fdrp = xmalloc(sz);
1003 *fdwp = xmalloc(sz);
1007 debug("XXX shrink: %d < %d", n, *fdl);
1009 memset(*fdrp, 0, sz);
1010 memset(*fdwp, 0, sz);
1012 for (i = 0; i < sockets_alloc; i++) {
1013 switch (sockets[i].type) {
1015 case AUTH_CONNECTION:
1016 FD_SET(sockets[i].fd, *fdrp);
1017 if (sshbuf_len(sockets[i].output) > 0)
1018 FD_SET(sockets[i].fd, *fdwp);
1024 deadline = reaper();
1025 if (parent_alive_interval != 0)
1026 deadline = (deadline == 0) ? parent_alive_interval :
1027 MIN(deadline, parent_alive_interval);
1028 if (deadline == 0) {
1031 tv.tv_sec = deadline;
1039 after_select(fd_set *readset, fd_set *writeset)
1041 struct sockaddr_un sunaddr;
1045 u_int i, orig_alloc;
1049 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1050 switch (sockets[i].type) {
1054 if (FD_ISSET(sockets[i].fd, readset)) {
1055 slen = sizeof(sunaddr);
1056 sock = accept(sockets[i].fd,
1057 (struct sockaddr *)&sunaddr, &slen);
1059 error("accept from AUTH_SOCKET: %s",
1063 if (getpeereid(sock, &euid, &egid) < 0) {
1064 error("getpeereid %d failed: %s",
1065 sock, strerror(errno));
1069 if ((euid != 0) && (getuid() != euid)) {
1070 error("uid mismatch: "
1071 "peer euid %u != uid %u",
1072 (u_int) euid, (u_int) getuid());
1076 new_socket(AUTH_CONNECTION, sock);
1079 case AUTH_CONNECTION:
1080 if (sshbuf_len(sockets[i].output) > 0 &&
1081 FD_ISSET(sockets[i].fd, writeset)) {
1082 len = write(sockets[i].fd,
1083 sshbuf_ptr(sockets[i].output),
1084 sshbuf_len(sockets[i].output));
1085 if (len == -1 && (errno == EAGAIN ||
1086 errno == EWOULDBLOCK ||
1090 close_socket(&sockets[i]);
1093 if ((r = sshbuf_consume(sockets[i].output,
1095 fatal("%s: buffer error: %s",
1096 __func__, ssh_err(r));
1098 if (FD_ISSET(sockets[i].fd, readset)) {
1099 len = read(sockets[i].fd, buf, sizeof(buf));
1100 if (len == -1 && (errno == EAGAIN ||
1101 errno == EWOULDBLOCK ||
1105 close_socket(&sockets[i]);
1108 if ((r = sshbuf_put(sockets[i].input,
1110 fatal("%s: buffer error: %s",
1111 __func__, ssh_err(r));
1112 explicit_bzero(buf, sizeof(buf));
1113 process_message(&sockets[i]);
1117 fatal("Unknown type %d", sockets[i].type);
1122 cleanup_socket(void)
1124 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1126 debug("%s: cleanup", __func__);
1128 unlink(socket_name);
1142 cleanup_handler(int sig)
1145 #ifdef ENABLE_PKCS11
1152 check_parent_exists(void)
1155 * If our parent has exited then getppid() will return (pid_t)1,
1156 * so testing for that should be safe.
1158 if (parent_pid != -1 && getppid() != parent_pid) {
1159 /* printf("Parent has died - Authentication agent exiting.\n"); */
1169 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1170 " [-t life] [command [arg ...]]\n"
1171 " ssh-agent [-c | -s] -k\n");
1176 main(int ac, char **av)
1178 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1179 int sock, fd, ch, result, saved_errno;
1181 char *shell, *format, *pidstr, *agentsocket = NULL;
1182 fd_set *readsetp = NULL, *writesetp = NULL;
1183 #ifdef HAVE_SETRLIMIT
1187 extern char *optarg;
1189 char pidstrbuf[1 + 3 * sizeof pid];
1190 struct timeval *tvp = NULL;
1194 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1201 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1202 /* Disable ptrace on Linux without sgid bit */
1203 prctl(PR_SET_DUMPABLE, 0);
1207 OpenSSL_add_all_algorithms();
1210 __progname = ssh_get_progname(av[0]);
1213 while ((ch = getopt(ac, av, "cDdksE:a:t:")) != -1) {
1216 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1217 if (fingerprint_hash == -1)
1218 fatal("Invalid hash algorithm \"%s\"", optarg);
1234 if (d_flag || D_flag)
1239 if (d_flag || D_flag)
1244 agentsocket = optarg;
1247 if ((lifetime = convtime(optarg)) == -1) {
1248 fprintf(stderr, "Invalid lifetime\n");
1259 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1262 if (ac == 0 && !c_flag && !s_flag) {
1263 shell = getenv("SHELL");
1264 if (shell != NULL && (len = strlen(shell)) > 2 &&
1265 strncmp(shell + len - 3, "csh", 3) == 0)
1269 const char *errstr = NULL;
1271 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1272 if (pidstr == NULL) {
1273 fprintf(stderr, "%s not set, cannot kill agent\n",
1274 SSH_AGENTPID_ENV_NAME);
1277 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1280 "%s=\"%s\", which is not a good PID: %s\n",
1281 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1284 if (kill(pid, SIGTERM) == -1) {
1288 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1289 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1290 printf(format, SSH_AGENTPID_ENV_NAME);
1291 printf("echo Agent pid %ld killed;\n", (long)pid);
1294 parent_pid = getpid();
1296 if (agentsocket == NULL) {
1297 /* Create private directory for agent socket */
1298 mktemp_proto(socket_dir, sizeof(socket_dir));
1299 if (mkdtemp(socket_dir) == NULL) {
1300 perror("mkdtemp: private socket dir");
1303 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1306 /* Try to use specified agent socket */
1307 socket_dir[0] = '\0';
1308 strlcpy(socket_name, agentsocket, sizeof socket_name);
1312 * Create socket early so it will exist before command gets run from
1315 prev_mask = umask(0177);
1316 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1318 /* XXX - unix_listener() calls error() not perror() */
1319 *socket_name = '\0'; /* Don't unlink any existing file */
1325 * Fork, and have the parent execute the command, if any, or present
1326 * the socket data. The child continues as the authentication agent.
1328 if (D_flag || d_flag) {
1329 log_init(__progname,
1330 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1331 SYSLOG_FACILITY_AUTH, 1);
1332 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1333 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1334 SSH_AUTHSOCKET_ENV_NAME);
1335 printf("echo Agent pid %ld;\n", (long)parent_pid);
1343 if (pid != 0) { /* Parent - execute the given command. */
1345 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1347 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1348 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1349 SSH_AUTHSOCKET_ENV_NAME);
1350 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1351 SSH_AGENTPID_ENV_NAME);
1352 printf("echo Agent pid %ld;\n", (long)pid);
1355 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1356 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1365 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1367 if (setsid() == -1) {
1368 error("setsid: %s", strerror(errno));
1373 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1374 /* XXX might close listen socket */
1375 (void)dup2(fd, STDIN_FILENO);
1376 (void)dup2(fd, STDOUT_FILENO);
1377 (void)dup2(fd, STDERR_FILENO);
1382 #ifdef HAVE_SETRLIMIT
1383 /* deny core dumps, since memory contains unencrypted private keys */
1384 rlim.rlim_cur = rlim.rlim_max = 0;
1385 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1386 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1393 cleanup_pid = getpid();
1395 #ifdef ENABLE_PKCS11
1398 new_socket(AUTH_SOCKET, sock);
1400 parent_alive_interval = 10;
1402 signal(SIGPIPE, SIG_IGN);
1403 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1404 signal(SIGHUP, cleanup_handler);
1405 signal(SIGTERM, cleanup_handler);
1409 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1410 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1411 saved_errno = errno;
1412 if (parent_alive_interval != 0)
1413 check_parent_exists();
1414 (void) reaper(); /* remove expired keys */
1416 if (saved_errno == EINTR)
1418 fatal("select: %s", strerror(saved_errno));
1419 } else if (result > 0)
1420 after_select(readsetp, writesetp);