1 /* $OpenBSD: ssh-agent.c,v 1.215 2016/11/30 03:07:37 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.
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
50 #include "openbsd-compat/sys-queue.h"
53 #include <openssl/evp.h>
54 #include "openbsd-compat/openssl-compat.h"
88 #include "ssh-pkcs11.h"
91 #ifndef DEFAULT_PKCS11_WHITELIST
92 # define DEFAULT_PKCS11_WHITELIST "/usr/lib/*,/usr/local/lib/*"
104 struct sshbuf *input;
105 struct sshbuf *output;
106 struct sshbuf *request;
109 u_int sockets_alloc = 0;
110 SocketEntry *sockets = NULL;
112 typedef struct identity {
113 TAILQ_ENTRY(identity) next;
123 TAILQ_HEAD(idqueue, identity) idlist;
126 /* private key table, one per protocol version */
131 /* pid of shell == parent of agent */
132 pid_t parent_pid = -1;
133 time_t parent_alive_interval = 0;
135 /* pid of process for which cleanup_socket is applicable */
136 pid_t cleanup_pid = 0;
138 /* pathname and directory for AUTH_SOCKET */
139 char socket_name[PATH_MAX];
140 char socket_dir[PATH_MAX];
142 /* PKCS#11 path whitelist */
143 static char *pkcs11_whitelist;
147 #define LOCK_SALT_SIZE 16
148 #define LOCK_ROUNDS 1
150 u_char lock_pwhash[LOCK_SIZE];
151 u_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);
375 agent_decode_alg(struct sshkey *key, u_int flags)
377 if (key->type == KEY_RSA) {
378 if (flags & SSH_AGENT_RSA_SHA2_256)
379 return "rsa-sha2-256";
380 else if (flags & SSH_AGENT_RSA_SHA2_512)
381 return "rsa-sha2-512";
388 process_sign_request2(SocketEntry *e)
390 u_char *blob, *data, *signature = NULL;
391 size_t blen, dlen, slen = 0;
392 u_int compat = 0, flags;
398 if ((msg = sshbuf_new()) == NULL)
399 fatal("%s: sshbuf_new failed", __func__);
400 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
401 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
402 (r = sshbuf_get_u32(e->request, &flags)) != 0)
403 fatal("%s: buffer error: %s", __func__, ssh_err(r));
404 if (flags & SSH_AGENT_OLD_SIGNATURE)
405 compat = SSH_BUG_SIGBLOB;
406 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
407 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
410 if ((id = lookup_identity(key, 2)) == NULL) {
411 verbose("%s: %s key not found", __func__, sshkey_type(key));
414 if (id->confirm && confirm_key(id) != 0) {
415 verbose("%s: user refused key", __func__);
418 if ((r = sshkey_sign(id->key, &signature, &slen,
419 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
420 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
428 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
429 (r = sshbuf_put_string(msg, signature, slen)) != 0)
430 fatal("%s: buffer error: %s", __func__, ssh_err(r));
431 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
432 fatal("%s: buffer error: %s", __func__, ssh_err(r));
434 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
435 fatal("%s: buffer error: %s", __func__, ssh_err(r));
445 process_remove_identity(SocketEntry *e, int version)
449 struct sshkey *key = NULL;
453 #endif /* WITH_SSH1 */
458 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
459 error("%s: sshkey_new failed", __func__);
462 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
463 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
464 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
465 fatal("%s: buffer error: %s", __func__, ssh_err(r));
467 if (bits != sshkey_size(key))
468 logit("Warning: identity keysize mismatch: "
469 "actual %u, announced %u",
470 sshkey_size(key), bits);
472 #endif /* WITH_SSH1 */
474 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
475 fatal("%s: buffer error: %s", __func__, ssh_err(r));
476 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
477 error("%s: sshkey_from_blob failed: %s",
478 __func__, ssh_err(r));
483 Identity *id = lookup_identity(key, version);
486 * We have this key. Free the old key. Since we
487 * don't want to leave empty slots in the middle of
488 * the array, we actually free the key there and move
489 * all the entries between the empty slot and the end
492 Idtab *tab = idtab_lookup(version);
493 if (tab->nentries < 1)
494 fatal("process_remove_identity: "
495 "internal error: tab->nentries %d",
497 TAILQ_REMOVE(&tab->idlist, id, next);
504 send_status(e, success);
508 process_remove_all_identities(SocketEntry *e, int version)
510 Idtab *tab = idtab_lookup(version);
513 /* Loop over all identities and clear the keys. */
514 for (id = TAILQ_FIRST(&tab->idlist); id;
515 id = TAILQ_FIRST(&tab->idlist)) {
516 TAILQ_REMOVE(&tab->idlist, id, next);
520 /* Mark that there are no identities. */
527 /* removes expired keys and returns number of seconds until the next expiry */
531 time_t deadline = 0, now = monotime();
536 for (version = 1; version < 3; version++) {
537 tab = idtab_lookup(version);
538 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
539 nxt = TAILQ_NEXT(id, next);
542 if (now >= id->death) {
543 debug("expiring key '%s'", id->comment);
544 TAILQ_REMOVE(&tab->idlist, id, next);
548 deadline = (deadline == 0) ? id->death :
549 MINIMUM(deadline, id->death);
552 if (deadline == 0 || deadline <= now)
555 return (deadline - now);
559 * XXX this and the corresponding serialisation function probably belongs
564 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
566 struct sshkey *k = NULL;
567 int r = SSH_ERR_INTERNAL_ERROR;
570 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
571 return SSH_ERR_ALLOC_FAIL;
573 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
574 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
575 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
576 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
577 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
578 /* SSH1 and SSL have p and q swapped */
579 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
580 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
583 /* Generate additional parameters */
584 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
586 /* enable blinding */
587 if (RSA_blinding_on(k->rsa, NULL) != 1) {
588 r = SSH_ERR_LIBCRYPTO_ERROR;
600 #endif /* WITH_SSH1 */
603 process_add_identity(SocketEntry *e, int version)
605 Idtab *tab = idtab_lookup(version);
607 int success = 0, confirm = 0;
609 char *comment = NULL;
611 struct sshkey *k = NULL;
613 int r = SSH_ERR_INTERNAL_ERROR;
618 r = agent_decode_rsa1(e->request, &k);
620 #endif /* WITH_SSH1 */
622 r = sshkey_private_deserialize(e->request, &k);
625 if (r != 0 || k == NULL ||
626 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
627 error("%s: decode private key: %s", __func__, ssh_err(r));
631 while (sshbuf_len(e->request)) {
632 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
633 error("%s: buffer error: %s", __func__, ssh_err(r));
637 case SSH_AGENT_CONSTRAIN_LIFETIME:
638 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
639 error("%s: bad lifetime constraint: %s",
640 __func__, ssh_err(r));
643 death = monotime() + seconds;
645 case SSH_AGENT_CONSTRAIN_CONFIRM:
649 error("%s: Unknown constraint %d", __func__, ctype);
651 sshbuf_reset(e->request);
659 if (lifetime && !death)
660 death = monotime() + lifetime;
661 if ((id = lookup_identity(k, version)) == NULL) {
662 id = xcalloc(1, sizeof(Identity));
664 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
665 /* Increment the number of identities. */
671 id->comment = comment;
673 id->confirm = confirm;
675 send_status(e, success);
678 /* XXX todo: encrypt sensitive data with passphrase */
680 process_lock_agent(SocketEntry *e, int lock)
682 int r, success = 0, delay;
684 u_char passwdhash[LOCK_SIZE];
685 static u_int fail_count = 0;
688 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
689 fatal("%s: buffer error: %s", __func__, ssh_err(r));
691 debug("empty password not supported");
692 } else if (locked && !lock) {
693 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
694 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
695 fatal("bcrypt_pbkdf");
696 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
697 debug("agent unlocked");
700 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
703 /* delay in 0.1s increments up to 10s */
704 if (fail_count < 100)
706 delay = 100000 * fail_count;
707 debug("unlock failed, delaying %0.1lf seconds",
708 (double)delay/1000000);
711 explicit_bzero(passwdhash, sizeof(passwdhash));
712 } else if (!locked && lock) {
713 debug("agent locked");
715 arc4random_buf(lock_salt, sizeof(lock_salt));
716 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
717 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
718 fatal("bcrypt_pbkdf");
721 explicit_bzero(passwd, pwlen);
723 send_status(e, success);
727 no_identities(SocketEntry *e, u_int type)
732 if ((msg = sshbuf_new()) == NULL)
733 fatal("%s: sshbuf_new failed", __func__);
734 if ((r = sshbuf_put_u8(msg,
735 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
736 SSH_AGENT_RSA_IDENTITIES_ANSWER :
737 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
738 (r = sshbuf_put_u32(msg, 0)) != 0 ||
739 (r = sshbuf_put_stringb(e->output, msg)) != 0)
740 fatal("%s: buffer error: %s", __func__, ssh_err(r));
746 process_add_smartcard_key(SocketEntry *e)
748 char *provider = NULL, *pin, canonical_provider[PATH_MAX];
749 int r, i, version, count = 0, success = 0, confirm = 0;
753 struct sshkey **keys = NULL, *k;
757 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
758 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
759 fatal("%s: buffer error: %s", __func__, ssh_err(r));
761 while (sshbuf_len(e->request)) {
762 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
763 fatal("%s: buffer error: %s", __func__, ssh_err(r));
765 case SSH_AGENT_CONSTRAIN_LIFETIME:
766 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
767 fatal("%s: buffer error: %s",
768 __func__, ssh_err(r));
769 death = monotime() + seconds;
771 case SSH_AGENT_CONSTRAIN_CONFIRM:
775 error("process_add_smartcard_key: "
776 "Unknown constraint type %d", type);
780 if (realpath(provider, canonical_provider) == NULL) {
781 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
782 provider, strerror(errno));
785 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
786 verbose("refusing PKCS#11 add of \"%.100s\": "
787 "provider not whitelisted", canonical_provider);
790 debug("%s: add %.100s", __func__, canonical_provider);
791 if (lifetime && !death)
792 death = monotime() + lifetime;
794 count = pkcs11_add_provider(canonical_provider, pin, &keys);
795 for (i = 0; i < count; i++) {
797 version = k->type == KEY_RSA1 ? 1 : 2;
798 tab = idtab_lookup(version);
799 if (lookup_identity(k, version) == NULL) {
800 id = xcalloc(1, sizeof(Identity));
802 id->provider = xstrdup(canonical_provider);
803 id->comment = xstrdup(canonical_provider); /* XXX */
805 id->confirm = confirm;
806 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
818 send_status(e, success);
822 process_remove_smartcard_key(SocketEntry *e)
824 char *provider = NULL, *pin = NULL;
825 int r, version, success = 0;
829 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
830 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
831 fatal("%s: buffer error: %s", __func__, ssh_err(r));
834 for (version = 1; version < 3; version++) {
835 tab = idtab_lookup(version);
836 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
837 nxt = TAILQ_NEXT(id, next);
838 /* Skip file--based keys */
839 if (id->provider == NULL)
841 if (!strcmp(provider, id->provider)) {
842 TAILQ_REMOVE(&tab->idlist, id, next);
848 if (pkcs11_del_provider(provider) == 0)
851 error("process_remove_smartcard_key:"
852 " pkcs11_del_provider failed");
854 send_status(e, success);
856 #endif /* ENABLE_PKCS11 */
858 /* dispatch incoming messages */
861 process_message(SocketEntry *e)
868 if (sshbuf_len(e->input) < 5)
869 return; /* Incomplete message. */
870 cp = sshbuf_ptr(e->input);
871 msg_len = PEEK_U32(cp);
872 if (msg_len > 256 * 1024) {
876 if (sshbuf_len(e->input) < msg_len + 4)
879 /* move the current input to e->request */
880 sshbuf_reset(e->request);
881 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
882 (r = sshbuf_get_u8(e->request, &type)) != 0)
883 fatal("%s: buffer error: %s", __func__, ssh_err(r));
885 /* check wheter agent is locked */
886 if (locked && type != SSH_AGENTC_UNLOCK) {
887 sshbuf_reset(e->request);
889 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
890 case SSH2_AGENTC_REQUEST_IDENTITIES:
891 /* send empty lists */
892 no_identities(e, type);
895 /* send a fail message for all other request types */
901 debug("type %d", type);
903 case SSH_AGENTC_LOCK:
904 case SSH_AGENTC_UNLOCK:
905 process_lock_agent(e, type == SSH_AGENTC_LOCK);
909 case SSH_AGENTC_RSA_CHALLENGE:
910 process_authentication_challenge1(e);
912 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
913 process_request_identities(e, 1);
915 case SSH_AGENTC_ADD_RSA_IDENTITY:
916 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
917 process_add_identity(e, 1);
919 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
920 process_remove_identity(e, 1);
923 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
924 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
927 case SSH2_AGENTC_SIGN_REQUEST:
928 process_sign_request2(e);
930 case SSH2_AGENTC_REQUEST_IDENTITIES:
931 process_request_identities(e, 2);
933 case SSH2_AGENTC_ADD_IDENTITY:
934 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
935 process_add_identity(e, 2);
937 case SSH2_AGENTC_REMOVE_IDENTITY:
938 process_remove_identity(e, 2);
940 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
941 process_remove_all_identities(e, 2);
944 case SSH_AGENTC_ADD_SMARTCARD_KEY:
945 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
946 process_add_smartcard_key(e);
948 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
949 process_remove_smartcard_key(e);
951 #endif /* ENABLE_PKCS11 */
953 /* Unknown message. Respond with failure. */
954 error("Unknown message %d", type);
955 sshbuf_reset(e->request);
962 new_socket(sock_type type, int fd)
964 u_int i, old_alloc, new_alloc;
971 for (i = 0; i < sockets_alloc; i++)
972 if (sockets[i].type == AUTH_UNUSED) {
974 if ((sockets[i].input = sshbuf_new()) == NULL)
975 fatal("%s: sshbuf_new failed", __func__);
976 if ((sockets[i].output = sshbuf_new()) == NULL)
977 fatal("%s: sshbuf_new failed", __func__);
978 if ((sockets[i].request = sshbuf_new()) == NULL)
979 fatal("%s: sshbuf_new failed", __func__);
980 sockets[i].type = type;
983 old_alloc = sockets_alloc;
984 new_alloc = sockets_alloc + 10;
985 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
986 for (i = old_alloc; i < new_alloc; i++)
987 sockets[i].type = AUTH_UNUSED;
988 sockets_alloc = new_alloc;
989 sockets[old_alloc].fd = fd;
990 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
991 fatal("%s: sshbuf_new failed", __func__);
992 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
993 fatal("%s: sshbuf_new failed", __func__);
994 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
995 fatal("%s: sshbuf_new failed", __func__);
996 sockets[old_alloc].type = type;
1000 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1001 struct timeval **tvpp)
1005 static struct timeval tv;
1008 for (i = 0; i < sockets_alloc; i++) {
1009 switch (sockets[i].type) {
1011 case AUTH_CONNECTION:
1012 n = MAXIMUM(n, sockets[i].fd);
1017 fatal("Unknown socket type %d", sockets[i].type);
1022 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1023 if (*fdrp == NULL || sz > *nallocp) {
1026 *fdrp = xmalloc(sz);
1027 *fdwp = xmalloc(sz);
1031 debug("XXX shrink: %d < %d", n, *fdl);
1033 memset(*fdrp, 0, sz);
1034 memset(*fdwp, 0, sz);
1036 for (i = 0; i < sockets_alloc; i++) {
1037 switch (sockets[i].type) {
1039 case AUTH_CONNECTION:
1040 FD_SET(sockets[i].fd, *fdrp);
1041 if (sshbuf_len(sockets[i].output) > 0)
1042 FD_SET(sockets[i].fd, *fdwp);
1048 deadline = reaper();
1049 if (parent_alive_interval != 0)
1050 deadline = (deadline == 0) ? parent_alive_interval :
1051 MINIMUM(deadline, parent_alive_interval);
1052 if (deadline == 0) {
1055 tv.tv_sec = deadline;
1063 after_select(fd_set *readset, fd_set *writeset)
1065 struct sockaddr_un sunaddr;
1069 u_int i, orig_alloc;
1073 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1074 switch (sockets[i].type) {
1078 if (FD_ISSET(sockets[i].fd, readset)) {
1079 slen = sizeof(sunaddr);
1080 sock = accept(sockets[i].fd,
1081 (struct sockaddr *)&sunaddr, &slen);
1083 error("accept from AUTH_SOCKET: %s",
1087 if (getpeereid(sock, &euid, &egid) < 0) {
1088 error("getpeereid %d failed: %s",
1089 sock, strerror(errno));
1093 if ((euid != 0) && (getuid() != euid)) {
1094 error("uid mismatch: "
1095 "peer euid %u != uid %u",
1096 (u_int) euid, (u_int) getuid());
1100 new_socket(AUTH_CONNECTION, sock);
1103 case AUTH_CONNECTION:
1104 if (sshbuf_len(sockets[i].output) > 0 &&
1105 FD_ISSET(sockets[i].fd, writeset)) {
1106 len = write(sockets[i].fd,
1107 sshbuf_ptr(sockets[i].output),
1108 sshbuf_len(sockets[i].output));
1109 if (len == -1 && (errno == EAGAIN ||
1110 errno == EWOULDBLOCK ||
1114 close_socket(&sockets[i]);
1117 if ((r = sshbuf_consume(sockets[i].output,
1119 fatal("%s: buffer error: %s",
1120 __func__, ssh_err(r));
1122 if (FD_ISSET(sockets[i].fd, readset)) {
1123 len = read(sockets[i].fd, buf, sizeof(buf));
1124 if (len == -1 && (errno == EAGAIN ||
1125 errno == EWOULDBLOCK ||
1129 close_socket(&sockets[i]);
1132 if ((r = sshbuf_put(sockets[i].input,
1134 fatal("%s: buffer error: %s",
1135 __func__, ssh_err(r));
1136 explicit_bzero(buf, sizeof(buf));
1137 process_message(&sockets[i]);
1141 fatal("Unknown type %d", sockets[i].type);
1146 cleanup_socket(void)
1148 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1150 debug("%s: cleanup", __func__);
1152 unlink(socket_name);
1166 cleanup_handler(int sig)
1169 #ifdef ENABLE_PKCS11
1176 check_parent_exists(void)
1179 * If our parent has exited then getppid() will return (pid_t)1,
1180 * so testing for that should be safe.
1182 if (parent_pid != -1 && getppid() != parent_pid) {
1183 /* printf("Parent has died - Authentication agent exiting.\n"); */
1193 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1194 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1195 " ssh-agent [-c | -s] -k\n");
1200 main(int ac, char **av)
1202 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1203 int sock, fd, ch, result, saved_errno;
1205 char *shell, *format, *pidstr, *agentsocket = NULL;
1206 fd_set *readsetp = NULL, *writesetp = NULL;
1207 #ifdef HAVE_SETRLIMIT
1211 extern char *optarg;
1213 char pidstrbuf[1 + 3 * sizeof pid];
1214 struct timeval *tvp = NULL;
1218 ssh_malloc_init(); /* must be called before any mallocs */
1219 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1226 platform_disable_tracing(0); /* strict=no */
1229 OpenSSL_add_all_algorithms();
1232 __progname = ssh_get_progname(av[0]);
1235 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1238 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1239 if (fingerprint_hash == -1)
1240 fatal("Invalid hash algorithm \"%s\"", optarg);
1251 if (pkcs11_whitelist != NULL)
1252 fatal("-P option already specified");
1253 pkcs11_whitelist = xstrdup(optarg);
1261 if (d_flag || D_flag)
1266 if (d_flag || D_flag)
1271 agentsocket = optarg;
1274 if ((lifetime = convtime(optarg)) == -1) {
1275 fprintf(stderr, "Invalid lifetime\n");
1286 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1289 if (pkcs11_whitelist == NULL)
1290 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1292 if (ac == 0 && !c_flag && !s_flag) {
1293 shell = getenv("SHELL");
1294 if (shell != NULL && (len = strlen(shell)) > 2 &&
1295 strncmp(shell + len - 3, "csh", 3) == 0)
1299 const char *errstr = NULL;
1301 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1302 if (pidstr == NULL) {
1303 fprintf(stderr, "%s not set, cannot kill agent\n",
1304 SSH_AGENTPID_ENV_NAME);
1307 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1310 "%s=\"%s\", which is not a good PID: %s\n",
1311 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1314 if (kill(pid, SIGTERM) == -1) {
1318 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1319 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1320 printf(format, SSH_AGENTPID_ENV_NAME);
1321 printf("echo Agent pid %ld killed;\n", (long)pid);
1324 parent_pid = getpid();
1326 if (agentsocket == NULL) {
1327 /* Create private directory for agent socket */
1328 mktemp_proto(socket_dir, sizeof(socket_dir));
1329 if (mkdtemp(socket_dir) == NULL) {
1330 perror("mkdtemp: private socket dir");
1333 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1336 /* Try to use specified agent socket */
1337 socket_dir[0] = '\0';
1338 strlcpy(socket_name, agentsocket, sizeof socket_name);
1342 * Create socket early so it will exist before command gets run from
1345 prev_mask = umask(0177);
1346 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1348 /* XXX - unix_listener() calls error() not perror() */
1349 *socket_name = '\0'; /* Don't unlink any existing file */
1355 * Fork, and have the parent execute the command, if any, or present
1356 * the socket data. The child continues as the authentication agent.
1358 if (D_flag || d_flag) {
1359 log_init(__progname,
1360 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1361 SYSLOG_FACILITY_AUTH, 1);
1362 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1363 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1364 SSH_AUTHSOCKET_ENV_NAME);
1365 printf("echo Agent pid %ld;\n", (long)parent_pid);
1374 if (pid != 0) { /* Parent - execute the given command. */
1376 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1378 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1379 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1380 SSH_AUTHSOCKET_ENV_NAME);
1381 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1382 SSH_AGENTPID_ENV_NAME);
1383 printf("echo Agent pid %ld;\n", (long)pid);
1386 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1387 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1396 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1398 if (setsid() == -1) {
1399 error("setsid: %s", strerror(errno));
1404 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1405 /* XXX might close listen socket */
1406 (void)dup2(fd, STDIN_FILENO);
1407 (void)dup2(fd, STDOUT_FILENO);
1408 (void)dup2(fd, STDERR_FILENO);
1413 #ifdef HAVE_SETRLIMIT
1414 /* deny core dumps, since memory contains unencrypted private keys */
1415 rlim.rlim_cur = rlim.rlim_max = 0;
1416 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1417 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1424 cleanup_pid = getpid();
1426 #ifdef ENABLE_PKCS11
1429 new_socket(AUTH_SOCKET, sock);
1431 parent_alive_interval = 10;
1433 signal(SIGPIPE, SIG_IGN);
1434 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1435 signal(SIGHUP, cleanup_handler);
1436 signal(SIGTERM, cleanup_handler);
1439 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1440 fatal("%s: pledge: %s", __progname, strerror(errno));
1441 platform_pledge_agent();
1444 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1445 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1446 saved_errno = errno;
1447 if (parent_alive_interval != 0)
1448 check_parent_exists();
1449 (void) reaper(); /* remove expired keys */
1451 if (saved_errno == EINTR)
1453 fatal("select: %s", strerror(saved_errno));
1454 } else if (result > 0)
1455 after_select(readsetp, writesetp);