1 /* $OpenBSD: ssh-agent.c,v 1.212 2016/02/15 09:47:49 dtucker Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include <sys/param.h> /* MIN MAX */
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
52 #include "openbsd-compat/sys-queue.h"
55 #include <openssl/evp.h>
56 #include "openbsd-compat/openssl-compat.h"
90 #include "ssh-pkcs11.h"
93 #ifndef DEFAULT_PKCS11_WHITELIST
94 # define DEFAULT_PKCS11_WHITELIST "/usr/lib/*,/usr/local/lib/*"
97 #if defined(HAVE_SYS_PRCTL_H)
98 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
110 struct sshbuf *input;
111 struct sshbuf *output;
112 struct sshbuf *request;
115 u_int sockets_alloc = 0;
116 SocketEntry *sockets = NULL;
118 typedef struct identity {
119 TAILQ_ENTRY(identity) next;
129 TAILQ_HEAD(idqueue, identity) idlist;
132 /* private key table, one per protocol version */
137 /* pid of shell == parent of agent */
138 pid_t parent_pid = -1;
139 time_t parent_alive_interval = 0;
141 /* pid of process for which cleanup_socket is applicable */
142 pid_t cleanup_pid = 0;
144 /* pathname and directory for AUTH_SOCKET */
145 char socket_name[PATH_MAX];
146 char socket_dir[PATH_MAX];
148 /* PKCS#11 path whitelist */
149 static char *pkcs11_whitelist;
153 #define LOCK_SALT_SIZE 16
154 #define LOCK_ROUNDS 1
156 char lock_passwd[LOCK_SIZE];
157 char lock_salt[LOCK_SALT_SIZE];
159 extern char *__progname;
161 /* Default lifetime in seconds (0 == forever) */
162 static long lifetime = 0;
164 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
167 * Client connection count; incremented in new_socket() and decremented in
168 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
169 * normally initialized to 1, it will never reach 0. However, if the -x
170 * option is specified, it is initialized to 0 in main(); in that case,
171 * ssh-agent will exit as soon as it has had at least one client but no
174 static int xcount = 1;
177 close_socket(SocketEntry *e)
181 if (e->type == AUTH_CONNECTION) {
182 debug("xcount %d -> %d", xcount, xcount - 1);
188 e->type = AUTH_UNUSED;
189 sshbuf_free(e->input);
190 sshbuf_free(e->output);
191 sshbuf_free(e->request);
201 for (i = 0; i <=2; i++) {
202 TAILQ_INIT(&idtable[i].idlist);
203 idtable[i].nentries = 0;
207 /* return private key table for requested protocol version */
209 idtab_lookup(int version)
211 if (version < 1 || version > 2)
212 fatal("internal error, bad protocol version %d", version);
213 return &idtable[version];
217 free_identity(Identity *id)
219 sshkey_free(id->key);
225 /* return matching private key for given public key */
227 lookup_identity(struct sshkey *key, int version)
231 Idtab *tab = idtab_lookup(version);
232 TAILQ_FOREACH(id, &tab->idlist, next) {
233 if (sshkey_equal(key, id->key))
239 /* Check confirmation of keysign request */
241 confirm_key(Identity *id)
246 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
248 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
257 send_status(SocketEntry *e, int success)
261 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
262 (r = sshbuf_put_u8(e->output, success ?
263 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
264 fatal("%s: buffer error: %s", __func__, ssh_err(r));
267 /* send list of supported public keys to 'client' */
269 process_request_identities(SocketEntry *e, int version)
271 Idtab *tab = idtab_lookup(version);
276 if ((msg = sshbuf_new()) == NULL)
277 fatal("%s: sshbuf_new failed", __func__);
278 if ((r = sshbuf_put_u8(msg, (version == 1) ?
279 SSH_AGENT_RSA_IDENTITIES_ANSWER :
280 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
281 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
282 fatal("%s: buffer error: %s", __func__, ssh_err(r));
283 TAILQ_FOREACH(id, &tab->idlist, next) {
284 if (id->key->type == KEY_RSA1) {
286 if ((r = sshbuf_put_u32(msg,
287 BN_num_bits(id->key->rsa->n))) != 0 ||
288 (r = sshbuf_put_bignum1(msg,
289 id->key->rsa->e)) != 0 ||
290 (r = sshbuf_put_bignum1(msg,
291 id->key->rsa->n)) != 0)
292 fatal("%s: buffer error: %s",
293 __func__, ssh_err(r));
299 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
300 error("%s: sshkey_to_blob: %s", __func__,
304 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
305 fatal("%s: buffer error: %s",
306 __func__, ssh_err(r));
309 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
310 fatal("%s: buffer error: %s", __func__, ssh_err(r));
312 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
313 fatal("%s: buffer error: %s", __func__, ssh_err(r));
320 process_authentication_challenge1(SocketEntry *e)
322 u_char buf[32], mdbuf[16], session_id[16];
328 struct ssh_digest_ctx *md;
331 if ((msg = sshbuf_new()) == NULL)
332 fatal("%s: sshbuf_new failed", __func__);
333 if ((key = sshkey_new(KEY_RSA1)) == NULL)
334 fatal("%s: sshkey_new failed", __func__);
335 if ((challenge = BN_new()) == NULL)
336 fatal("%s: BN_new failed", __func__);
338 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
339 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
340 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
341 (r = sshbuf_get_bignum1(e->request, challenge)))
342 fatal("%s: buffer error: %s", __func__, ssh_err(r));
344 /* Only protocol 1.1 is supported */
345 if (sshbuf_len(e->request) == 0)
347 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
348 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
349 fatal("%s: buffer error: %s", __func__, ssh_err(r));
350 if (response_type != 1)
353 id = lookup_identity(key, 1);
354 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
355 struct sshkey *private = id->key;
356 /* Decrypt the challenge using the private key. */
357 if ((r = rsa_private_decrypt(challenge, challenge,
358 private->rsa) != 0)) {
359 fatal("%s: rsa_public_encrypt: %s", __func__,
361 goto failure; /* XXX ? */
364 /* The response is MD5 of decrypted challenge plus session id */
365 len = BN_num_bytes(challenge);
366 if (len <= 0 || len > 32) {
367 logit("%s: bad challenge length %d", __func__, len);
371 BN_bn2bin(challenge, buf + 32 - len);
372 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
373 ssh_digest_update(md, buf, 32) < 0 ||
374 ssh_digest_update(md, session_id, 16) < 0 ||
375 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
376 fatal("%s: md5 failed", __func__);
379 /* Send the response. */
380 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
381 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
382 fatal("%s: buffer error: %s", __func__, ssh_err(r));
387 /* Unknown identity or protocol error. Send failure. */
388 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
389 fatal("%s: buffer error: %s", __func__, ssh_err(r));
391 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
392 fatal("%s: buffer error: %s", __func__, ssh_err(r));
394 BN_clear_free(challenge);
400 agent_decode_alg(struct sshkey *key, u_int flags)
402 if (key->type == KEY_RSA) {
403 if (flags & SSH_AGENT_RSA_SHA2_256)
404 return "rsa-sha2-256";
405 else if (flags & SSH_AGENT_RSA_SHA2_512)
406 return "rsa-sha2-512";
413 process_sign_request2(SocketEntry *e)
415 u_char *blob, *data, *signature = NULL;
416 size_t blen, dlen, slen = 0;
417 u_int compat = 0, flags;
423 if ((msg = sshbuf_new()) == NULL)
424 fatal("%s: sshbuf_new failed", __func__);
425 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
426 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
427 (r = sshbuf_get_u32(e->request, &flags)) != 0)
428 fatal("%s: buffer error: %s", __func__, ssh_err(r));
429 if (flags & SSH_AGENT_OLD_SIGNATURE)
430 compat = SSH_BUG_SIGBLOB;
431 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
432 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
435 if ((id = lookup_identity(key, 2)) == NULL) {
436 verbose("%s: %s key not found", __func__, sshkey_type(key));
439 if (id->confirm && confirm_key(id) != 0) {
440 verbose("%s: user refused key", __func__);
443 if ((r = sshkey_sign(id->key, &signature, &slen,
444 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
445 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
453 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
454 (r = sshbuf_put_string(msg, signature, slen)) != 0)
455 fatal("%s: buffer error: %s", __func__, ssh_err(r));
456 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
457 fatal("%s: buffer error: %s", __func__, ssh_err(r));
459 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
460 fatal("%s: buffer error: %s", __func__, ssh_err(r));
470 process_remove_identity(SocketEntry *e, int version)
474 struct sshkey *key = NULL;
478 #endif /* WITH_SSH1 */
483 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
484 error("%s: sshkey_new failed", __func__);
487 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
488 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
489 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
490 fatal("%s: buffer error: %s", __func__, ssh_err(r));
492 if (bits != sshkey_size(key))
493 logit("Warning: identity keysize mismatch: "
494 "actual %u, announced %u",
495 sshkey_size(key), bits);
497 #endif /* WITH_SSH1 */
499 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
500 fatal("%s: buffer error: %s", __func__, ssh_err(r));
501 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
502 error("%s: sshkey_from_blob failed: %s",
503 __func__, ssh_err(r));
508 Identity *id = lookup_identity(key, version);
511 * We have this key. Free the old key. Since we
512 * don't want to leave empty slots in the middle of
513 * the array, we actually free the key there and move
514 * all the entries between the empty slot and the end
517 Idtab *tab = idtab_lookup(version);
518 if (tab->nentries < 1)
519 fatal("process_remove_identity: "
520 "internal error: tab->nentries %d",
522 TAILQ_REMOVE(&tab->idlist, id, next);
529 send_status(e, success);
533 process_remove_all_identities(SocketEntry *e, int version)
535 Idtab *tab = idtab_lookup(version);
538 /* Loop over all identities and clear the keys. */
539 for (id = TAILQ_FIRST(&tab->idlist); id;
540 id = TAILQ_FIRST(&tab->idlist)) {
541 TAILQ_REMOVE(&tab->idlist, id, next);
545 /* Mark that there are no identities. */
552 /* removes expired keys and returns number of seconds until the next expiry */
556 time_t deadline = 0, now = monotime();
561 for (version = 1; version < 3; version++) {
562 tab = idtab_lookup(version);
563 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
564 nxt = TAILQ_NEXT(id, next);
567 if (now >= id->death) {
568 debug("expiring key '%s'", id->comment);
569 TAILQ_REMOVE(&tab->idlist, id, next);
573 deadline = (deadline == 0) ? id->death :
574 MIN(deadline, id->death);
577 if (deadline == 0 || deadline <= now)
580 return (deadline - now);
584 * XXX this and the corresponding serialisation function probably belongs
589 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
591 struct sshkey *k = NULL;
592 int r = SSH_ERR_INTERNAL_ERROR;
595 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
596 return SSH_ERR_ALLOC_FAIL;
598 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
599 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
600 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
601 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
602 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
603 /* SSH1 and SSL have p and q swapped */
604 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
605 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
608 /* Generate additional parameters */
609 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
611 /* enable blinding */
612 if (RSA_blinding_on(k->rsa, NULL) != 1) {
613 r = SSH_ERR_LIBCRYPTO_ERROR;
625 #endif /* WITH_SSH1 */
628 process_add_identity(SocketEntry *e, int version)
630 Idtab *tab = idtab_lookup(version);
632 int success = 0, confirm = 0;
634 char *comment = NULL;
636 struct sshkey *k = NULL;
638 int r = SSH_ERR_INTERNAL_ERROR;
643 r = agent_decode_rsa1(e->request, &k);
645 #endif /* WITH_SSH1 */
647 r = sshkey_private_deserialize(e->request, &k);
650 if (r != 0 || k == NULL ||
651 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
652 error("%s: decode private key: %s", __func__, ssh_err(r));
656 while (sshbuf_len(e->request)) {
657 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
658 error("%s: buffer error: %s", __func__, ssh_err(r));
662 case SSH_AGENT_CONSTRAIN_LIFETIME:
663 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
664 error("%s: bad lifetime constraint: %s",
665 __func__, ssh_err(r));
668 death = monotime() + seconds;
670 case SSH_AGENT_CONSTRAIN_CONFIRM:
674 error("%s: Unknown constraint %d", __func__, ctype);
676 sshbuf_reset(e->request);
684 if (lifetime && !death)
685 death = monotime() + lifetime;
686 if ((id = lookup_identity(k, version)) == NULL) {
687 id = xcalloc(1, sizeof(Identity));
689 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
690 /* Increment the number of identities. */
696 id->comment = comment;
698 id->confirm = confirm;
700 send_status(e, success);
703 /* XXX todo: encrypt sensitive data with passphrase */
705 process_lock_agent(SocketEntry *e, int lock)
707 int r, success = 0, delay;
708 char *passwd, passwdhash[LOCK_SIZE];
709 static u_int fail_count = 0;
712 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
713 fatal("%s: buffer error: %s", __func__, ssh_err(r));
715 debug("empty password not supported");
716 } else if (locked && !lock) {
717 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
718 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
719 fatal("bcrypt_pbkdf");
720 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
721 debug("agent unlocked");
724 explicit_bzero(lock_passwd, sizeof(lock_passwd));
727 /* delay in 0.1s increments up to 10s */
728 if (fail_count < 100)
730 delay = 100000 * fail_count;
731 debug("unlock failed, delaying %0.1lf seconds",
732 (double)delay/1000000);
735 explicit_bzero(passwdhash, sizeof(passwdhash));
736 } else if (!locked && lock) {
737 debug("agent locked");
739 arc4random_buf(lock_salt, sizeof(lock_salt));
740 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
741 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
742 fatal("bcrypt_pbkdf");
745 explicit_bzero(passwd, pwlen);
747 send_status(e, success);
751 no_identities(SocketEntry *e, u_int type)
756 if ((msg = sshbuf_new()) == NULL)
757 fatal("%s: sshbuf_new failed", __func__);
758 if ((r = sshbuf_put_u8(msg,
759 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
760 SSH_AGENT_RSA_IDENTITIES_ANSWER :
761 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
762 (r = sshbuf_put_u32(msg, 0)) != 0 ||
763 (r = sshbuf_put_stringb(e->output, msg)) != 0)
764 fatal("%s: buffer error: %s", __func__, ssh_err(r));
770 process_add_smartcard_key(SocketEntry *e)
772 char *provider = NULL, *pin, canonical_provider[PATH_MAX];
773 int r, i, version, count = 0, success = 0, confirm = 0;
777 struct sshkey **keys = NULL, *k;
781 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
782 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
783 fatal("%s: buffer error: %s", __func__, ssh_err(r));
785 while (sshbuf_len(e->request)) {
786 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
787 fatal("%s: buffer error: %s", __func__, ssh_err(r));
789 case SSH_AGENT_CONSTRAIN_LIFETIME:
790 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
791 fatal("%s: buffer error: %s",
792 __func__, ssh_err(r));
793 death = monotime() + seconds;
795 case SSH_AGENT_CONSTRAIN_CONFIRM:
799 error("process_add_smartcard_key: "
800 "Unknown constraint type %d", type);
804 if (realpath(provider, canonical_provider) == NULL) {
805 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
806 provider, strerror(errno));
809 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
810 verbose("refusing PKCS#11 add of \"%.100s\": "
811 "provider not whitelisted", canonical_provider);
814 debug("%s: add %.100s", __func__, canonical_provider);
815 if (lifetime && !death)
816 death = monotime() + lifetime;
818 count = pkcs11_add_provider(canonical_provider, pin, &keys);
819 for (i = 0; i < count; i++) {
821 version = k->type == KEY_RSA1 ? 1 : 2;
822 tab = idtab_lookup(version);
823 if (lookup_identity(k, version) == NULL) {
824 id = xcalloc(1, sizeof(Identity));
826 id->provider = xstrdup(canonical_provider);
827 id->comment = xstrdup(canonical_provider); /* XXX */
829 id->confirm = confirm;
830 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
842 send_status(e, success);
846 process_remove_smartcard_key(SocketEntry *e)
848 char *provider = NULL, *pin = NULL;
849 int r, version, success = 0;
853 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
854 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
855 fatal("%s: buffer error: %s", __func__, ssh_err(r));
858 for (version = 1; version < 3; version++) {
859 tab = idtab_lookup(version);
860 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
861 nxt = TAILQ_NEXT(id, next);
862 /* Skip file--based keys */
863 if (id->provider == NULL)
865 if (!strcmp(provider, id->provider)) {
866 TAILQ_REMOVE(&tab->idlist, id, next);
872 if (pkcs11_del_provider(provider) == 0)
875 error("process_remove_smartcard_key:"
876 " pkcs11_del_provider failed");
878 send_status(e, success);
880 #endif /* ENABLE_PKCS11 */
882 /* dispatch incoming messages */
885 process_message(SocketEntry *e)
892 if (sshbuf_len(e->input) < 5)
893 return; /* Incomplete message. */
894 cp = sshbuf_ptr(e->input);
895 msg_len = PEEK_U32(cp);
896 if (msg_len > 256 * 1024) {
900 if (sshbuf_len(e->input) < msg_len + 4)
903 /* move the current input to e->request */
904 sshbuf_reset(e->request);
905 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
906 (r = sshbuf_get_u8(e->request, &type)) != 0)
907 fatal("%s: buffer error: %s", __func__, ssh_err(r));
909 /* check wheter agent is locked */
910 if (locked && type != SSH_AGENTC_UNLOCK) {
911 sshbuf_reset(e->request);
913 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
914 case SSH2_AGENTC_REQUEST_IDENTITIES:
915 /* send empty lists */
916 no_identities(e, type);
919 /* send a fail message for all other request types */
925 debug("type %d", type);
927 case SSH_AGENTC_LOCK:
928 case SSH_AGENTC_UNLOCK:
929 process_lock_agent(e, type == SSH_AGENTC_LOCK);
933 case SSH_AGENTC_RSA_CHALLENGE:
934 process_authentication_challenge1(e);
936 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
937 process_request_identities(e, 1);
939 case SSH_AGENTC_ADD_RSA_IDENTITY:
940 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
941 process_add_identity(e, 1);
943 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
944 process_remove_identity(e, 1);
947 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
948 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
951 case SSH2_AGENTC_SIGN_REQUEST:
952 process_sign_request2(e);
954 case SSH2_AGENTC_REQUEST_IDENTITIES:
955 process_request_identities(e, 2);
957 case SSH2_AGENTC_ADD_IDENTITY:
958 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
959 process_add_identity(e, 2);
961 case SSH2_AGENTC_REMOVE_IDENTITY:
962 process_remove_identity(e, 2);
964 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
965 process_remove_all_identities(e, 2);
968 case SSH_AGENTC_ADD_SMARTCARD_KEY:
969 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
970 process_add_smartcard_key(e);
972 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
973 process_remove_smartcard_key(e);
975 #endif /* ENABLE_PKCS11 */
977 /* Unknown message. Respond with failure. */
978 error("Unknown message %d", type);
979 sshbuf_reset(e->request);
986 new_socket(sock_type type, int fd)
988 u_int i, old_alloc, new_alloc;
990 if (type == AUTH_CONNECTION) {
991 debug("xcount %d -> %d", xcount, xcount + 1);
999 for (i = 0; i < sockets_alloc; i++)
1000 if (sockets[i].type == AUTH_UNUSED) {
1002 if ((sockets[i].input = sshbuf_new()) == NULL)
1003 fatal("%s: sshbuf_new failed", __func__);
1004 if ((sockets[i].output = sshbuf_new()) == NULL)
1005 fatal("%s: sshbuf_new failed", __func__);
1006 if ((sockets[i].request = sshbuf_new()) == NULL)
1007 fatal("%s: sshbuf_new failed", __func__);
1008 sockets[i].type = type;
1011 old_alloc = sockets_alloc;
1012 new_alloc = sockets_alloc + 10;
1013 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
1014 for (i = old_alloc; i < new_alloc; i++)
1015 sockets[i].type = AUTH_UNUSED;
1016 sockets_alloc = new_alloc;
1017 sockets[old_alloc].fd = fd;
1018 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
1019 fatal("%s: sshbuf_new failed", __func__);
1020 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
1021 fatal("%s: sshbuf_new failed", __func__);
1022 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1023 fatal("%s: sshbuf_new failed", __func__);
1024 sockets[old_alloc].type = type;
1028 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1029 struct timeval **tvpp)
1033 static struct timeval tv;
1036 for (i = 0; i < sockets_alloc; i++) {
1037 switch (sockets[i].type) {
1039 case AUTH_CONNECTION:
1040 n = MAX(n, sockets[i].fd);
1045 fatal("Unknown socket type %d", sockets[i].type);
1050 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1051 if (*fdrp == NULL || sz > *nallocp) {
1054 *fdrp = xmalloc(sz);
1055 *fdwp = xmalloc(sz);
1059 debug("XXX shrink: %d < %d", n, *fdl);
1061 memset(*fdrp, 0, sz);
1062 memset(*fdwp, 0, sz);
1064 for (i = 0; i < sockets_alloc; i++) {
1065 switch (sockets[i].type) {
1067 case AUTH_CONNECTION:
1068 FD_SET(sockets[i].fd, *fdrp);
1069 if (sshbuf_len(sockets[i].output) > 0)
1070 FD_SET(sockets[i].fd, *fdwp);
1076 deadline = reaper();
1077 if (parent_alive_interval != 0)
1078 deadline = (deadline == 0) ? parent_alive_interval :
1079 MIN(deadline, parent_alive_interval);
1080 if (deadline == 0) {
1083 tv.tv_sec = deadline;
1091 after_select(fd_set *readset, fd_set *writeset)
1093 struct sockaddr_un sunaddr;
1097 u_int i, orig_alloc;
1101 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1102 switch (sockets[i].type) {
1106 if (FD_ISSET(sockets[i].fd, readset)) {
1107 slen = sizeof(sunaddr);
1108 sock = accept(sockets[i].fd,
1109 (struct sockaddr *)&sunaddr, &slen);
1111 error("accept from AUTH_SOCKET: %s",
1115 if (getpeereid(sock, &euid, &egid) < 0) {
1116 error("getpeereid %d failed: %s",
1117 sock, strerror(errno));
1121 if ((euid != 0) && (getuid() != euid)) {
1122 error("uid mismatch: "
1123 "peer euid %u != uid %u",
1124 (u_int) euid, (u_int) getuid());
1128 new_socket(AUTH_CONNECTION, sock);
1131 case AUTH_CONNECTION:
1132 if (sshbuf_len(sockets[i].output) > 0 &&
1133 FD_ISSET(sockets[i].fd, writeset)) {
1134 len = write(sockets[i].fd,
1135 sshbuf_ptr(sockets[i].output),
1136 sshbuf_len(sockets[i].output));
1137 if (len == -1 && (errno == EAGAIN ||
1138 errno == EWOULDBLOCK ||
1142 close_socket(&sockets[i]);
1145 if ((r = sshbuf_consume(sockets[i].output,
1147 fatal("%s: buffer error: %s",
1148 __func__, ssh_err(r));
1150 if (FD_ISSET(sockets[i].fd, readset)) {
1151 len = read(sockets[i].fd, buf, sizeof(buf));
1152 if (len == -1 && (errno == EAGAIN ||
1153 errno == EWOULDBLOCK ||
1157 close_socket(&sockets[i]);
1160 if ((r = sshbuf_put(sockets[i].input,
1162 fatal("%s: buffer error: %s",
1163 __func__, ssh_err(r));
1164 explicit_bzero(buf, sizeof(buf));
1165 process_message(&sockets[i]);
1169 fatal("Unknown type %d", sockets[i].type);
1174 cleanup_socket(void)
1176 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1178 debug("%s: cleanup", __func__);
1180 unlink(socket_name);
1194 cleanup_handler(int sig)
1197 #ifdef ENABLE_PKCS11
1204 check_parent_exists(void)
1207 * If our parent has exited then getppid() will return (pid_t)1,
1208 * so testing for that should be safe.
1210 if (parent_pid != -1 && getppid() != parent_pid) {
1211 /* printf("Parent has died - Authentication agent exiting.\n"); */
1221 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1222 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1223 " ssh-agent [-c | -s] -k\n");
1224 fprintf(stderr, " -x Exit when the last client disconnects.\n");
1229 main(int ac, char **av)
1231 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1232 int sock, fd, ch, result, saved_errno;
1234 char *shell, *format, *pidstr, *agentsocket = NULL;
1235 fd_set *readsetp = NULL, *writesetp = NULL;
1236 #ifdef HAVE_SETRLIMIT
1240 extern char *optarg;
1242 char pidstrbuf[1 + 3 * sizeof pid];
1243 struct timeval *tvp = NULL;
1247 ssh_malloc_init(); /* must be called before any mallocs */
1248 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1256 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1257 /* Disable ptrace on Linux without sgid bit */
1258 prctl(PR_SET_DUMPABLE, 0);
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);