1 /* $OpenBSD: ssh-agent.c,v 1.218 2017/03/15 03:52:30 deraadt 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/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"
89 #include "ssh-pkcs11.h"
92 #ifndef DEFAULT_PKCS11_WHITELIST
93 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
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];
143 /* PKCS#11 path whitelist */
144 static char *pkcs11_whitelist;
148 #define LOCK_SALT_SIZE 16
149 #define LOCK_ROUNDS 1
151 u_char lock_pwhash[LOCK_SIZE];
152 u_char lock_salt[LOCK_SALT_SIZE];
154 extern char *__progname;
156 /* Default lifetime in seconds (0 == forever) */
157 static long lifetime = 0;
159 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
162 * Client connection count; incremented in new_socket() and decremented in
163 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
164 * normally initialized to 1, it will never reach 0. However, if the -x
165 * option is specified, it is initialized to 0 in main(); in that case,
166 * ssh-agent will exit as soon as it has had at least one client but no
169 static int xcount = 1;
172 close_socket(SocketEntry *e)
176 if (e->type == AUTH_CONNECTION) {
177 debug("xcount %d -> %d", xcount, xcount - 1);
183 e->type = AUTH_UNUSED;
184 sshbuf_free(e->input);
185 sshbuf_free(e->output);
186 sshbuf_free(e->request);
196 for (i = 0; i <=2; i++) {
197 TAILQ_INIT(&idtable[i].idlist);
198 idtable[i].nentries = 0;
202 /* return private key table for requested protocol version */
204 idtab_lookup(int version)
206 if (version < 1 || version > 2)
207 fatal("internal error, bad protocol version %d", version);
208 return &idtable[version];
212 free_identity(Identity *id)
214 sshkey_free(id->key);
220 /* return matching private key for given public key */
222 lookup_identity(struct sshkey *key, int version)
226 Idtab *tab = idtab_lookup(version);
227 TAILQ_FOREACH(id, &tab->idlist, next) {
228 if (sshkey_equal(key, id->key))
234 /* Check confirmation of keysign request */
236 confirm_key(Identity *id)
241 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
243 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
252 send_status(SocketEntry *e, int success)
256 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
257 (r = sshbuf_put_u8(e->output, success ?
258 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
259 fatal("%s: buffer error: %s", __func__, ssh_err(r));
262 /* send list of supported public keys to 'client' */
264 process_request_identities(SocketEntry *e, int version)
266 Idtab *tab = idtab_lookup(version);
271 if ((msg = sshbuf_new()) == NULL)
272 fatal("%s: sshbuf_new failed", __func__);
273 if ((r = sshbuf_put_u8(msg, (version == 1) ?
274 SSH_AGENT_RSA_IDENTITIES_ANSWER :
275 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
276 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
277 fatal("%s: buffer error: %s", __func__, ssh_err(r));
278 TAILQ_FOREACH(id, &tab->idlist, next) {
279 if (id->key->type == KEY_RSA1) {
281 if ((r = sshbuf_put_u32(msg,
282 BN_num_bits(id->key->rsa->n))) != 0 ||
283 (r = sshbuf_put_bignum1(msg,
284 id->key->rsa->e)) != 0 ||
285 (r = sshbuf_put_bignum1(msg,
286 id->key->rsa->n)) != 0)
287 fatal("%s: buffer error: %s",
288 __func__, ssh_err(r));
294 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
295 error("%s: sshkey_to_blob: %s", __func__,
299 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
300 fatal("%s: buffer error: %s",
301 __func__, ssh_err(r));
304 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
305 fatal("%s: buffer error: %s", __func__, ssh_err(r));
307 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
308 fatal("%s: buffer error: %s", __func__, ssh_err(r));
315 process_authentication_challenge1(SocketEntry *e)
317 u_char buf[32], mdbuf[16], session_id[16];
323 struct ssh_digest_ctx *md;
326 if ((msg = sshbuf_new()) == NULL)
327 fatal("%s: sshbuf_new failed", __func__);
328 if ((key = sshkey_new(KEY_RSA1)) == NULL)
329 fatal("%s: sshkey_new failed", __func__);
330 if ((challenge = BN_new()) == NULL)
331 fatal("%s: BN_new failed", __func__);
333 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
334 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
335 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
336 (r = sshbuf_get_bignum1(e->request, challenge)))
337 fatal("%s: buffer error: %s", __func__, ssh_err(r));
339 /* Only protocol 1.1 is supported */
340 if (sshbuf_len(e->request) == 0)
342 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
343 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
344 fatal("%s: buffer error: %s", __func__, ssh_err(r));
345 if (response_type != 1)
348 id = lookup_identity(key, 1);
349 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
350 struct sshkey *private = id->key;
351 /* Decrypt the challenge using the private key. */
352 if ((r = rsa_private_decrypt(challenge, challenge,
353 private->rsa) != 0)) {
354 fatal("%s: rsa_public_encrypt: %s", __func__,
356 goto failure; /* XXX ? */
359 /* The response is MD5 of decrypted challenge plus session id */
360 len = BN_num_bytes(challenge);
361 if (len <= 0 || len > 32) {
362 logit("%s: bad challenge length %d", __func__, len);
366 BN_bn2bin(challenge, buf + 32 - len);
367 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
368 ssh_digest_update(md, buf, 32) < 0 ||
369 ssh_digest_update(md, session_id, 16) < 0 ||
370 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
371 fatal("%s: md5 failed", __func__);
374 /* Send the response. */
375 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
376 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
377 fatal("%s: buffer error: %s", __func__, ssh_err(r));
382 /* Unknown identity or protocol error. Send failure. */
383 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
384 fatal("%s: buffer error: %s", __func__, ssh_err(r));
386 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
387 fatal("%s: buffer error: %s", __func__, ssh_err(r));
389 BN_clear_free(challenge);
395 agent_decode_alg(struct sshkey *key, u_int flags)
397 if (key->type == KEY_RSA) {
398 if (flags & SSH_AGENT_RSA_SHA2_256)
399 return "rsa-sha2-256";
400 else if (flags & SSH_AGENT_RSA_SHA2_512)
401 return "rsa-sha2-512";
408 process_sign_request2(SocketEntry *e)
410 u_char *blob, *data, *signature = NULL;
411 size_t blen, dlen, slen = 0;
412 u_int compat = 0, flags;
418 if ((msg = sshbuf_new()) == NULL)
419 fatal("%s: sshbuf_new failed", __func__);
420 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
421 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
422 (r = sshbuf_get_u32(e->request, &flags)) != 0)
423 fatal("%s: buffer error: %s", __func__, ssh_err(r));
424 if (flags & SSH_AGENT_OLD_SIGNATURE)
425 compat = SSH_BUG_SIGBLOB;
426 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
427 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
430 if ((id = lookup_identity(key, 2)) == NULL) {
431 verbose("%s: %s key not found", __func__, sshkey_type(key));
434 if (id->confirm && confirm_key(id) != 0) {
435 verbose("%s: user refused key", __func__);
438 if ((r = sshkey_sign(id->key, &signature, &slen,
439 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
440 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
448 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
449 (r = sshbuf_put_string(msg, signature, slen)) != 0)
450 fatal("%s: buffer error: %s", __func__, ssh_err(r));
451 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
452 fatal("%s: buffer error: %s", __func__, ssh_err(r));
454 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
455 fatal("%s: buffer error: %s", __func__, ssh_err(r));
465 process_remove_identity(SocketEntry *e, int version)
469 struct sshkey *key = NULL;
473 #endif /* WITH_SSH1 */
478 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
479 error("%s: sshkey_new failed", __func__);
482 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
483 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
484 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
485 fatal("%s: buffer error: %s", __func__, ssh_err(r));
487 if (bits != sshkey_size(key))
488 logit("Warning: identity keysize mismatch: "
489 "actual %u, announced %u",
490 sshkey_size(key), bits);
492 #endif /* WITH_SSH1 */
494 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
495 fatal("%s: buffer error: %s", __func__, ssh_err(r));
496 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
497 error("%s: sshkey_from_blob failed: %s",
498 __func__, ssh_err(r));
503 Identity *id = lookup_identity(key, version);
506 * We have this key. Free the old key. Since we
507 * don't want to leave empty slots in the middle of
508 * the array, we actually free the key there and move
509 * all the entries between the empty slot and the end
512 Idtab *tab = idtab_lookup(version);
513 if (tab->nentries < 1)
514 fatal("process_remove_identity: "
515 "internal error: tab->nentries %d",
517 TAILQ_REMOVE(&tab->idlist, id, next);
524 send_status(e, success);
528 process_remove_all_identities(SocketEntry *e, int version)
530 Idtab *tab = idtab_lookup(version);
533 /* Loop over all identities and clear the keys. */
534 for (id = TAILQ_FIRST(&tab->idlist); id;
535 id = TAILQ_FIRST(&tab->idlist)) {
536 TAILQ_REMOVE(&tab->idlist, id, next);
540 /* Mark that there are no identities. */
547 /* removes expired keys and returns number of seconds until the next expiry */
551 time_t deadline = 0, now = monotime();
556 for (version = 1; version < 3; version++) {
557 tab = idtab_lookup(version);
558 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
559 nxt = TAILQ_NEXT(id, next);
562 if (now >= id->death) {
563 debug("expiring key '%s'", id->comment);
564 TAILQ_REMOVE(&tab->idlist, id, next);
568 deadline = (deadline == 0) ? id->death :
569 MINIMUM(deadline, id->death);
572 if (deadline == 0 || deadline <= now)
575 return (deadline - now);
579 * XXX this and the corresponding serialisation function probably belongs
584 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
586 struct sshkey *k = NULL;
587 int r = SSH_ERR_INTERNAL_ERROR;
590 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
591 return SSH_ERR_ALLOC_FAIL;
593 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
594 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
595 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
596 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
597 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
598 /* SSH1 and SSL have p and q swapped */
599 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
600 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
603 /* Generate additional parameters */
604 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
606 /* enable blinding */
607 if (RSA_blinding_on(k->rsa, NULL) != 1) {
608 r = SSH_ERR_LIBCRYPTO_ERROR;
620 #endif /* WITH_SSH1 */
623 process_add_identity(SocketEntry *e, int version)
625 Idtab *tab = idtab_lookup(version);
627 int success = 0, confirm = 0;
629 char *comment = NULL;
631 struct sshkey *k = NULL;
633 int r = SSH_ERR_INTERNAL_ERROR;
638 r = agent_decode_rsa1(e->request, &k);
640 #endif /* WITH_SSH1 */
642 r = sshkey_private_deserialize(e->request, &k);
645 if (r != 0 || k == NULL ||
646 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
647 error("%s: decode private key: %s", __func__, ssh_err(r));
651 while (sshbuf_len(e->request)) {
652 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
653 error("%s: buffer error: %s", __func__, ssh_err(r));
657 case SSH_AGENT_CONSTRAIN_LIFETIME:
658 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
659 error("%s: bad lifetime constraint: %s",
660 __func__, ssh_err(r));
663 death = monotime() + seconds;
665 case SSH_AGENT_CONSTRAIN_CONFIRM:
669 error("%s: Unknown constraint %d", __func__, ctype);
671 sshbuf_reset(e->request);
679 if (lifetime && !death)
680 death = monotime() + lifetime;
681 if ((id = lookup_identity(k, version)) == NULL) {
682 id = xcalloc(1, sizeof(Identity));
684 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
685 /* Increment the number of identities. */
691 id->comment = comment;
693 id->confirm = confirm;
695 send_status(e, success);
698 /* XXX todo: encrypt sensitive data with passphrase */
700 process_lock_agent(SocketEntry *e, int lock)
702 int r, success = 0, delay;
704 u_char passwdhash[LOCK_SIZE];
705 static u_int fail_count = 0;
708 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
709 fatal("%s: buffer error: %s", __func__, ssh_err(r));
711 debug("empty password not supported");
712 } else if (locked && !lock) {
713 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
714 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
715 fatal("bcrypt_pbkdf");
716 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
717 debug("agent unlocked");
720 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
723 /* delay in 0.1s increments up to 10s */
724 if (fail_count < 100)
726 delay = 100000 * fail_count;
727 debug("unlock failed, delaying %0.1lf seconds",
728 (double)delay/1000000);
731 explicit_bzero(passwdhash, sizeof(passwdhash));
732 } else if (!locked && lock) {
733 debug("agent locked");
735 arc4random_buf(lock_salt, sizeof(lock_salt));
736 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
737 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
738 fatal("bcrypt_pbkdf");
741 explicit_bzero(passwd, pwlen);
743 send_status(e, success);
747 no_identities(SocketEntry *e, u_int type)
752 if ((msg = sshbuf_new()) == NULL)
753 fatal("%s: sshbuf_new failed", __func__);
754 if ((r = sshbuf_put_u8(msg,
755 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
756 SSH_AGENT_RSA_IDENTITIES_ANSWER :
757 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
758 (r = sshbuf_put_u32(msg, 0)) != 0 ||
759 (r = sshbuf_put_stringb(e->output, msg)) != 0)
760 fatal("%s: buffer error: %s", __func__, ssh_err(r));
766 process_add_smartcard_key(SocketEntry *e)
768 char *provider = NULL, *pin, canonical_provider[PATH_MAX];
769 int r, i, version, count = 0, success = 0, confirm = 0;
773 struct sshkey **keys = NULL, *k;
777 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
778 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
779 fatal("%s: buffer error: %s", __func__, ssh_err(r));
781 while (sshbuf_len(e->request)) {
782 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
783 fatal("%s: buffer error: %s", __func__, ssh_err(r));
785 case SSH_AGENT_CONSTRAIN_LIFETIME:
786 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
787 fatal("%s: buffer error: %s",
788 __func__, ssh_err(r));
789 death = monotime() + seconds;
791 case SSH_AGENT_CONSTRAIN_CONFIRM:
795 error("process_add_smartcard_key: "
796 "Unknown constraint type %d", type);
800 if (realpath(provider, canonical_provider) == NULL) {
801 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
802 provider, strerror(errno));
805 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
806 verbose("refusing PKCS#11 add of \"%.100s\": "
807 "provider not whitelisted", canonical_provider);
810 debug("%s: add %.100s", __func__, canonical_provider);
811 if (lifetime && !death)
812 death = monotime() + lifetime;
814 count = pkcs11_add_provider(canonical_provider, pin, &keys);
815 for (i = 0; i < count; i++) {
817 version = k->type == KEY_RSA1 ? 1 : 2;
818 tab = idtab_lookup(version);
819 if (lookup_identity(k, version) == NULL) {
820 id = xcalloc(1, sizeof(Identity));
822 id->provider = xstrdup(canonical_provider);
823 id->comment = xstrdup(canonical_provider); /* XXX */
825 id->confirm = confirm;
826 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
838 send_status(e, success);
842 process_remove_smartcard_key(SocketEntry *e)
844 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
845 int r, version, success = 0;
849 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
850 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
851 fatal("%s: buffer error: %s", __func__, ssh_err(r));
854 if (realpath(provider, canonical_provider) == NULL) {
855 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
856 provider, strerror(errno));
860 debug("%s: remove %.100s", __func__, canonical_provider);
861 for (version = 1; version < 3; version++) {
862 tab = idtab_lookup(version);
863 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
864 nxt = TAILQ_NEXT(id, next);
865 /* Skip file--based keys */
866 if (id->provider == NULL)
868 if (!strcmp(canonical_provider, id->provider)) {
869 TAILQ_REMOVE(&tab->idlist, id, next);
875 if (pkcs11_del_provider(canonical_provider) == 0)
878 error("process_remove_smartcard_key:"
879 " pkcs11_del_provider failed");
882 send_status(e, success);
884 #endif /* ENABLE_PKCS11 */
886 /* dispatch incoming messages */
889 process_message(SocketEntry *e)
896 if (sshbuf_len(e->input) < 5)
897 return; /* Incomplete message. */
898 cp = sshbuf_ptr(e->input);
899 msg_len = PEEK_U32(cp);
900 if (msg_len > 256 * 1024) {
904 if (sshbuf_len(e->input) < msg_len + 4)
907 /* move the current input to e->request */
908 sshbuf_reset(e->request);
909 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
910 (r = sshbuf_get_u8(e->request, &type)) != 0)
911 fatal("%s: buffer error: %s", __func__, ssh_err(r));
913 /* check wheter agent is locked */
914 if (locked && type != SSH_AGENTC_UNLOCK) {
915 sshbuf_reset(e->request);
917 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
918 case SSH2_AGENTC_REQUEST_IDENTITIES:
919 /* send empty lists */
920 no_identities(e, type);
923 /* send a fail message for all other request types */
929 debug("type %d", type);
931 case SSH_AGENTC_LOCK:
932 case SSH_AGENTC_UNLOCK:
933 process_lock_agent(e, type == SSH_AGENTC_LOCK);
937 case SSH_AGENTC_RSA_CHALLENGE:
938 process_authentication_challenge1(e);
940 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
941 process_request_identities(e, 1);
943 case SSH_AGENTC_ADD_RSA_IDENTITY:
944 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
945 process_add_identity(e, 1);
947 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
948 process_remove_identity(e, 1);
951 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
952 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
955 case SSH2_AGENTC_SIGN_REQUEST:
956 process_sign_request2(e);
958 case SSH2_AGENTC_REQUEST_IDENTITIES:
959 process_request_identities(e, 2);
961 case SSH2_AGENTC_ADD_IDENTITY:
962 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
963 process_add_identity(e, 2);
965 case SSH2_AGENTC_REMOVE_IDENTITY:
966 process_remove_identity(e, 2);
968 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
969 process_remove_all_identities(e, 2);
972 case SSH_AGENTC_ADD_SMARTCARD_KEY:
973 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
974 process_add_smartcard_key(e);
976 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
977 process_remove_smartcard_key(e);
979 #endif /* ENABLE_PKCS11 */
981 /* Unknown message. Respond with failure. */
982 error("Unknown message %d", type);
983 sshbuf_reset(e->request);
990 new_socket(sock_type type, int fd)
992 u_int i, old_alloc, new_alloc;
994 if (type == AUTH_CONNECTION) {
995 debug("xcount %d -> %d", xcount, xcount + 1);
1003 for (i = 0; i < sockets_alloc; i++)
1004 if (sockets[i].type == AUTH_UNUSED) {
1006 if ((sockets[i].input = sshbuf_new()) == NULL)
1007 fatal("%s: sshbuf_new failed", __func__);
1008 if ((sockets[i].output = sshbuf_new()) == NULL)
1009 fatal("%s: sshbuf_new failed", __func__);
1010 if ((sockets[i].request = sshbuf_new()) == NULL)
1011 fatal("%s: sshbuf_new failed", __func__);
1012 sockets[i].type = type;
1015 old_alloc = sockets_alloc;
1016 new_alloc = sockets_alloc + 10;
1017 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
1018 for (i = old_alloc; i < new_alloc; i++)
1019 sockets[i].type = AUTH_UNUSED;
1020 sockets_alloc = new_alloc;
1021 sockets[old_alloc].fd = fd;
1022 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
1023 fatal("%s: sshbuf_new failed", __func__);
1024 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
1025 fatal("%s: sshbuf_new failed", __func__);
1026 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1027 fatal("%s: sshbuf_new failed", __func__);
1028 sockets[old_alloc].type = type;
1032 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1033 struct timeval **tvpp)
1037 static struct timeval tv;
1040 for (i = 0; i < sockets_alloc; i++) {
1041 switch (sockets[i].type) {
1043 case AUTH_CONNECTION:
1044 n = MAXIMUM(n, sockets[i].fd);
1049 fatal("Unknown socket type %d", sockets[i].type);
1054 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1055 if (*fdrp == NULL || sz > *nallocp) {
1058 *fdrp = xmalloc(sz);
1059 *fdwp = xmalloc(sz);
1063 debug("XXX shrink: %d < %d", n, *fdl);
1065 memset(*fdrp, 0, sz);
1066 memset(*fdwp, 0, sz);
1068 for (i = 0; i < sockets_alloc; i++) {
1069 switch (sockets[i].type) {
1071 case AUTH_CONNECTION:
1072 FD_SET(sockets[i].fd, *fdrp);
1073 if (sshbuf_len(sockets[i].output) > 0)
1074 FD_SET(sockets[i].fd, *fdwp);
1080 deadline = reaper();
1081 if (parent_alive_interval != 0)
1082 deadline = (deadline == 0) ? parent_alive_interval :
1083 MINIMUM(deadline, parent_alive_interval);
1084 if (deadline == 0) {
1087 tv.tv_sec = deadline;
1095 after_select(fd_set *readset, fd_set *writeset)
1097 struct sockaddr_un sunaddr;
1101 u_int i, orig_alloc;
1105 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1106 switch (sockets[i].type) {
1110 if (FD_ISSET(sockets[i].fd, readset)) {
1111 slen = sizeof(sunaddr);
1112 sock = accept(sockets[i].fd,
1113 (struct sockaddr *)&sunaddr, &slen);
1115 error("accept from AUTH_SOCKET: %s",
1119 if (getpeereid(sock, &euid, &egid) < 0) {
1120 error("getpeereid %d failed: %s",
1121 sock, strerror(errno));
1125 if ((euid != 0) && (getuid() != euid)) {
1126 error("uid mismatch: "
1127 "peer euid %u != uid %u",
1128 (u_int) euid, (u_int) getuid());
1132 new_socket(AUTH_CONNECTION, sock);
1135 case AUTH_CONNECTION:
1136 if (sshbuf_len(sockets[i].output) > 0 &&
1137 FD_ISSET(sockets[i].fd, writeset)) {
1138 len = write(sockets[i].fd,
1139 sshbuf_ptr(sockets[i].output),
1140 sshbuf_len(sockets[i].output));
1141 if (len == -1 && (errno == EAGAIN ||
1142 errno == EWOULDBLOCK ||
1146 close_socket(&sockets[i]);
1149 if ((r = sshbuf_consume(sockets[i].output,
1151 fatal("%s: buffer error: %s",
1152 __func__, ssh_err(r));
1154 if (FD_ISSET(sockets[i].fd, readset)) {
1155 len = read(sockets[i].fd, buf, sizeof(buf));
1156 if (len == -1 && (errno == EAGAIN ||
1157 errno == EWOULDBLOCK ||
1161 close_socket(&sockets[i]);
1164 if ((r = sshbuf_put(sockets[i].input,
1166 fatal("%s: buffer error: %s",
1167 __func__, ssh_err(r));
1168 explicit_bzero(buf, sizeof(buf));
1169 process_message(&sockets[i]);
1173 fatal("Unknown type %d", sockets[i].type);
1178 cleanup_socket(void)
1180 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1182 debug("%s: cleanup", __func__);
1184 unlink(socket_name);
1198 cleanup_handler(int sig)
1201 #ifdef ENABLE_PKCS11
1208 check_parent_exists(void)
1211 * If our parent has exited then getppid() will return (pid_t)1,
1212 * so testing for that should be safe.
1214 if (parent_pid != -1 && getppid() != parent_pid) {
1215 /* printf("Parent has died - Authentication agent exiting.\n"); */
1225 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1226 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1227 " ssh-agent [-c | -s] -k\n");
1232 main(int ac, char **av)
1234 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1235 int sock, fd, ch, result, saved_errno;
1237 char *shell, *format, *pidstr, *agentsocket = NULL;
1238 fd_set *readsetp = NULL, *writesetp = NULL;
1239 #ifdef HAVE_SETRLIMIT
1243 extern char *optarg;
1245 char pidstrbuf[1 + 3 * sizeof pid];
1246 struct timeval *tvp = NULL;
1250 ssh_malloc_init(); /* must be called before any mallocs */
1251 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1259 platform_disable_tracing(0); /* strict=no */
1262 OpenSSL_add_all_algorithms();
1265 __progname = ssh_get_progname(av[0]);
1268 while ((ch = getopt(ac, av, "cDdksE:a:P:t:x")) != -1) {
1271 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1272 if (fingerprint_hash == -1)
1273 fatal("Invalid hash algorithm \"%s\"", optarg);
1284 if (pkcs11_whitelist != NULL)
1285 fatal("-P option already specified");
1286 pkcs11_whitelist = xstrdup(optarg);
1294 if (d_flag || D_flag)
1299 if (d_flag || D_flag)
1304 agentsocket = optarg;
1307 if ((lifetime = convtime(optarg)) == -1) {
1308 fprintf(stderr, "Invalid lifetime\n");
1322 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1325 if (pkcs11_whitelist == NULL)
1326 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1328 if (ac == 0 && !c_flag && !s_flag) {
1329 shell = getenv("SHELL");
1330 if (shell != NULL && (len = strlen(shell)) > 2 &&
1331 strncmp(shell + len - 3, "csh", 3) == 0)
1335 const char *errstr = NULL;
1337 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1338 if (pidstr == NULL) {
1339 fprintf(stderr, "%s not set, cannot kill agent\n",
1340 SSH_AGENTPID_ENV_NAME);
1343 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1346 "%s=\"%s\", which is not a good PID: %s\n",
1347 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1350 if (kill(pid, SIGTERM) == -1) {
1354 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1355 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1356 printf(format, SSH_AGENTPID_ENV_NAME);
1357 printf("echo Agent pid %ld killed;\n", (long)pid);
1360 parent_pid = getpid();
1362 if (agentsocket == NULL) {
1363 /* Create private directory for agent socket */
1364 mktemp_proto(socket_dir, sizeof(socket_dir));
1365 if (mkdtemp(socket_dir) == NULL) {
1366 perror("mkdtemp: private socket dir");
1369 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1372 /* Try to use specified agent socket */
1373 socket_dir[0] = '\0';
1374 strlcpy(socket_name, agentsocket, sizeof socket_name);
1378 * Create socket early so it will exist before command gets run from
1381 prev_mask = umask(0177);
1382 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1384 /* XXX - unix_listener() calls error() not perror() */
1385 *socket_name = '\0'; /* Don't unlink any existing file */
1391 * Fork, and have the parent execute the command, if any, or present
1392 * the socket data. The child continues as the authentication agent.
1394 if (D_flag || d_flag) {
1395 log_init(__progname,
1396 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1397 SYSLOG_FACILITY_AUTH, 1);
1398 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1399 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1400 SSH_AUTHSOCKET_ENV_NAME);
1401 printf("echo Agent pid %ld;\n", (long)parent_pid);
1410 if (pid != 0) { /* Parent - execute the given command. */
1412 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1414 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1415 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1416 SSH_AUTHSOCKET_ENV_NAME);
1417 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1418 SSH_AGENTPID_ENV_NAME);
1419 printf("echo Agent pid %ld;\n", (long)pid);
1422 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1423 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1432 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1434 if (setsid() == -1) {
1435 error("setsid: %s", strerror(errno));
1440 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1441 /* XXX might close listen socket */
1442 (void)dup2(fd, STDIN_FILENO);
1443 (void)dup2(fd, STDOUT_FILENO);
1444 (void)dup2(fd, STDERR_FILENO);
1449 #ifdef HAVE_SETRLIMIT
1450 /* deny core dumps, since memory contains unencrypted private keys */
1451 rlim.rlim_cur = rlim.rlim_max = 0;
1452 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1453 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1460 cleanup_pid = getpid();
1462 #ifdef ENABLE_PKCS11
1465 new_socket(AUTH_SOCKET, sock);
1467 parent_alive_interval = 10;
1469 signal(SIGPIPE, SIG_IGN);
1470 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1471 signal(SIGHUP, cleanup_handler);
1472 signal(SIGTERM, cleanup_handler);
1475 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1476 fatal("%s: pledge: %s", __progname, strerror(errno));
1477 platform_pledge_agent();
1480 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1481 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1482 saved_errno = errno;
1483 if (parent_alive_interval != 0)
1484 check_parent_exists();
1485 (void) reaper(); /* remove expired keys */
1487 if (saved_errno == EINTR)
1489 fatal("select: %s", strerror(saved_errno));
1490 } else if (result > 0)
1491 after_select(readsetp, writesetp);