1 /* $OpenBSD: ssh-agent.c,v 1.204 2015/07/08 20:24:02 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #include <sys/param.h> /* MIN MAX */
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
51 #include "openbsd-compat/sys-queue.h"
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
88 #include "ssh-pkcs11.h"
91 #if defined(HAVE_SYS_PRCTL_H)
92 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
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];
144 #define LOCK_SALT_SIZE 16
145 #define LOCK_ROUNDS 1
147 char lock_passwd[LOCK_SIZE];
148 char lock_salt[LOCK_SALT_SIZE];
150 extern char *__progname;
152 /* Default lifetime in seconds (0 == forever) */
153 static long lifetime = 0;
155 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
158 close_socket(SocketEntry *e)
162 e->type = AUTH_UNUSED;
163 sshbuf_free(e->input);
164 sshbuf_free(e->output);
165 sshbuf_free(e->request);
173 for (i = 0; i <=2; i++) {
174 TAILQ_INIT(&idtable[i].idlist);
175 idtable[i].nentries = 0;
179 /* return private key table for requested protocol version */
181 idtab_lookup(int version)
183 if (version < 1 || version > 2)
184 fatal("internal error, bad protocol version %d", version);
185 return &idtable[version];
189 free_identity(Identity *id)
191 sshkey_free(id->key);
197 /* return matching private key for given public key */
199 lookup_identity(struct sshkey *key, int version)
203 Idtab *tab = idtab_lookup(version);
204 TAILQ_FOREACH(id, &tab->idlist, next) {
205 if (sshkey_equal(key, id->key))
211 /* Check confirmation of keysign request */
213 confirm_key(Identity *id)
218 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
220 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
229 send_status(SocketEntry *e, int success)
233 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
234 (r = sshbuf_put_u8(e->output, success ?
235 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
236 fatal("%s: buffer error: %s", __func__, ssh_err(r));
239 /* send list of supported public keys to 'client' */
241 process_request_identities(SocketEntry *e, int version)
243 Idtab *tab = idtab_lookup(version);
248 if ((msg = sshbuf_new()) == NULL)
249 fatal("%s: sshbuf_new failed", __func__);
250 if ((r = sshbuf_put_u8(msg, (version == 1) ?
251 SSH_AGENT_RSA_IDENTITIES_ANSWER :
252 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
253 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
254 fatal("%s: buffer error: %s", __func__, ssh_err(r));
255 TAILQ_FOREACH(id, &tab->idlist, next) {
256 if (id->key->type == KEY_RSA1) {
258 if ((r = sshbuf_put_u32(msg,
259 BN_num_bits(id->key->rsa->n))) != 0 ||
260 (r = sshbuf_put_bignum1(msg,
261 id->key->rsa->e)) != 0 ||
262 (r = sshbuf_put_bignum1(msg,
263 id->key->rsa->n)) != 0)
264 fatal("%s: buffer error: %s",
265 __func__, ssh_err(r));
271 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
272 error("%s: sshkey_to_blob: %s", __func__,
276 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
277 fatal("%s: buffer error: %s",
278 __func__, ssh_err(r));
281 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
282 fatal("%s: buffer error: %s", __func__, ssh_err(r));
284 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
285 fatal("%s: buffer error: %s", __func__, ssh_err(r));
292 process_authentication_challenge1(SocketEntry *e)
294 u_char buf[32], mdbuf[16], session_id[16];
300 struct ssh_digest_ctx *md;
303 if ((msg = sshbuf_new()) == NULL)
304 fatal("%s: sshbuf_new failed", __func__);
305 if ((key = sshkey_new(KEY_RSA1)) == NULL)
306 fatal("%s: sshkey_new failed", __func__);
307 if ((challenge = BN_new()) == NULL)
308 fatal("%s: BN_new failed", __func__);
310 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
311 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
312 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
313 (r = sshbuf_get_bignum1(e->request, challenge)))
314 fatal("%s: buffer error: %s", __func__, ssh_err(r));
316 /* Only protocol 1.1 is supported */
317 if (sshbuf_len(e->request) == 0)
319 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
320 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
321 fatal("%s: buffer error: %s", __func__, ssh_err(r));
322 if (response_type != 1)
325 id = lookup_identity(key, 1);
326 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
327 struct sshkey *private = id->key;
328 /* Decrypt the challenge using the private key. */
329 if ((r = rsa_private_decrypt(challenge, challenge,
330 private->rsa) != 0)) {
331 fatal("%s: rsa_public_encrypt: %s", __func__,
333 goto failure; /* XXX ? */
336 /* The response is MD5 of decrypted challenge plus session id */
337 len = BN_num_bytes(challenge);
338 if (len <= 0 || len > 32) {
339 logit("%s: bad challenge length %d", __func__, len);
343 BN_bn2bin(challenge, buf + 32 - len);
344 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
345 ssh_digest_update(md, buf, 32) < 0 ||
346 ssh_digest_update(md, session_id, 16) < 0 ||
347 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
348 fatal("%s: md5 failed", __func__);
351 /* Send the response. */
352 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
353 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
354 fatal("%s: buffer error: %s", __func__, ssh_err(r));
359 /* Unknown identity or protocol error. Send failure. */
360 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
361 fatal("%s: buffer error: %s", __func__, ssh_err(r));
363 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
364 fatal("%s: buffer error: %s", __func__, ssh_err(r));
366 BN_clear_free(challenge);
373 process_sign_request2(SocketEntry *e)
375 u_char *blob, *data, *signature = NULL;
376 size_t blen, dlen, slen = 0;
377 u_int compat = 0, flags;
383 if ((msg = sshbuf_new()) == NULL)
384 fatal("%s: sshbuf_new failed", __func__);
385 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
386 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
387 (r = sshbuf_get_u32(e->request, &flags)) != 0)
388 fatal("%s: buffer error: %s", __func__, ssh_err(r));
389 if (flags & SSH_AGENT_OLD_SIGNATURE)
390 compat = SSH_BUG_SIGBLOB;
391 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
392 error("%s: cannot parse key blob: %s", __func__, ssh_err(ok));
395 if ((id = lookup_identity(key, 2)) == NULL) {
396 verbose("%s: %s key not found", __func__, sshkey_type(key));
399 if (id->confirm && confirm_key(id) != 0) {
400 verbose("%s: user refused key", __func__);
403 if ((r = sshkey_sign(id->key, &signature, &slen,
404 data, dlen, compat)) != 0) {
405 error("%s: sshkey_sign: %s", __func__, ssh_err(ok));
413 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
414 (r = sshbuf_put_string(msg, signature, slen)) != 0)
415 fatal("%s: buffer error: %s", __func__, ssh_err(r));
416 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
417 fatal("%s: buffer error: %s", __func__, ssh_err(r));
419 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
420 fatal("%s: buffer error: %s", __func__, ssh_err(r));
430 process_remove_identity(SocketEntry *e, int version)
434 struct sshkey *key = NULL;
438 #endif /* WITH_SSH1 */
443 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
444 error("%s: sshkey_new failed", __func__);
447 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
448 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
449 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
450 fatal("%s: buffer error: %s", __func__, ssh_err(r));
452 if (bits != sshkey_size(key))
453 logit("Warning: identity keysize mismatch: "
454 "actual %u, announced %u",
455 sshkey_size(key), bits);
457 #endif /* WITH_SSH1 */
459 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
460 fatal("%s: buffer error: %s", __func__, ssh_err(r));
461 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
462 error("%s: sshkey_from_blob failed: %s",
463 __func__, ssh_err(r));
468 Identity *id = lookup_identity(key, version);
471 * We have this key. Free the old key. Since we
472 * don't want to leave empty slots in the middle of
473 * the array, we actually free the key there and move
474 * all the entries between the empty slot and the end
477 Idtab *tab = idtab_lookup(version);
478 if (tab->nentries < 1)
479 fatal("process_remove_identity: "
480 "internal error: tab->nentries %d",
482 TAILQ_REMOVE(&tab->idlist, id, next);
489 send_status(e, success);
493 process_remove_all_identities(SocketEntry *e, int version)
495 Idtab *tab = idtab_lookup(version);
498 /* Loop over all identities and clear the keys. */
499 for (id = TAILQ_FIRST(&tab->idlist); id;
500 id = TAILQ_FIRST(&tab->idlist)) {
501 TAILQ_REMOVE(&tab->idlist, id, next);
505 /* Mark that there are no identities. */
512 /* removes expired keys and returns number of seconds until the next expiry */
516 time_t deadline = 0, now = monotime();
521 for (version = 1; version < 3; version++) {
522 tab = idtab_lookup(version);
523 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
524 nxt = TAILQ_NEXT(id, next);
527 if (now >= id->death) {
528 debug("expiring key '%s'", id->comment);
529 TAILQ_REMOVE(&tab->idlist, id, next);
533 deadline = (deadline == 0) ? id->death :
534 MIN(deadline, id->death);
537 if (deadline == 0 || deadline <= now)
540 return (deadline - now);
544 * XXX this and the corresponding serialisation function probably belongs
549 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
551 struct sshkey *k = NULL;
552 int r = SSH_ERR_INTERNAL_ERROR;
555 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
556 return SSH_ERR_ALLOC_FAIL;
558 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
559 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
560 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
561 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
562 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
563 /* SSH1 and SSL have p and q swapped */
564 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
565 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
568 /* Generate additional parameters */
569 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
571 /* enable blinding */
572 if (RSA_blinding_on(k->rsa, NULL) != 1) {
573 r = SSH_ERR_LIBCRYPTO_ERROR;
585 #endif /* WITH_SSH1 */
588 process_add_identity(SocketEntry *e, int version)
590 Idtab *tab = idtab_lookup(version);
592 int success = 0, confirm = 0;
594 char *comment = NULL;
596 struct sshkey *k = NULL;
598 int r = SSH_ERR_INTERNAL_ERROR;
603 r = agent_decode_rsa1(e->request, &k);
605 #endif /* WITH_SSH1 */
607 r = sshkey_private_deserialize(e->request, &k);
610 if (r != 0 || k == NULL ||
611 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
612 error("%s: decode private key: %s", __func__, ssh_err(r));
616 while (sshbuf_len(e->request)) {
617 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
618 error("%s: buffer error: %s", __func__, ssh_err(r));
622 case SSH_AGENT_CONSTRAIN_LIFETIME:
623 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
624 error("%s: bad lifetime constraint: %s",
625 __func__, ssh_err(r));
628 death = monotime() + seconds;
630 case SSH_AGENT_CONSTRAIN_CONFIRM:
634 error("%s: Unknown constraint %d", __func__, ctype);
636 sshbuf_reset(e->request);
644 if (lifetime && !death)
645 death = monotime() + lifetime;
646 if ((id = lookup_identity(k, version)) == NULL) {
647 id = xcalloc(1, sizeof(Identity));
649 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
650 /* Increment the number of identities. */
656 id->comment = comment;
658 id->confirm = confirm;
660 send_status(e, success);
663 /* XXX todo: encrypt sensitive data with passphrase */
665 process_lock_agent(SocketEntry *e, int lock)
667 int r, success = 0, delay;
668 char *passwd, passwdhash[LOCK_SIZE];
669 static u_int fail_count = 0;
672 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
673 fatal("%s: buffer error: %s", __func__, ssh_err(r));
675 debug("empty password not supported");
676 } else if (locked && !lock) {
677 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
678 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
679 fatal("bcrypt_pbkdf");
680 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
681 debug("agent unlocked");
684 explicit_bzero(lock_passwd, sizeof(lock_passwd));
687 /* delay in 0.1s increments up to 10s */
688 if (fail_count < 100)
690 delay = 100000 * fail_count;
691 debug("unlock failed, delaying %0.1lf seconds",
692 (double)delay/1000000);
695 explicit_bzero(passwdhash, sizeof(passwdhash));
696 } else if (!locked && lock) {
697 debug("agent locked");
699 arc4random_buf(lock_salt, sizeof(lock_salt));
700 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
701 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
702 fatal("bcrypt_pbkdf");
705 explicit_bzero(passwd, pwlen);
707 send_status(e, success);
711 no_identities(SocketEntry *e, u_int type)
716 if ((msg = sshbuf_new()) == NULL)
717 fatal("%s: sshbuf_new failed", __func__);
718 if ((r = sshbuf_put_u8(msg,
719 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
720 SSH_AGENT_RSA_IDENTITIES_ANSWER :
721 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
722 (r = sshbuf_put_u32(msg, 0)) != 0 ||
723 (r = sshbuf_put_stringb(e->output, msg)) != 0)
724 fatal("%s: buffer error: %s", __func__, ssh_err(r));
730 process_add_smartcard_key(SocketEntry *e)
732 char *provider = NULL, *pin;
733 int r, i, version, count = 0, success = 0, confirm = 0;
737 struct sshkey **keys = NULL, *k;
741 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
742 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
743 fatal("%s: buffer error: %s", __func__, ssh_err(r));
745 while (sshbuf_len(e->request)) {
746 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
747 fatal("%s: buffer error: %s", __func__, ssh_err(r));
749 case SSH_AGENT_CONSTRAIN_LIFETIME:
750 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
751 fatal("%s: buffer error: %s",
752 __func__, ssh_err(r));
753 death = monotime() + seconds;
755 case SSH_AGENT_CONSTRAIN_CONFIRM:
759 error("process_add_smartcard_key: "
760 "Unknown constraint type %d", type);
764 if (lifetime && !death)
765 death = monotime() + lifetime;
767 count = pkcs11_add_provider(provider, pin, &keys);
768 for (i = 0; i < count; i++) {
770 version = k->type == KEY_RSA1 ? 1 : 2;
771 tab = idtab_lookup(version);
772 if (lookup_identity(k, version) == NULL) {
773 id = xcalloc(1, sizeof(Identity));
775 id->provider = xstrdup(provider);
776 id->comment = xstrdup(provider); /* XXX */
778 id->confirm = confirm;
779 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
791 send_status(e, success);
795 process_remove_smartcard_key(SocketEntry *e)
797 char *provider = NULL, *pin = NULL;
798 int r, version, success = 0;
802 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
803 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
804 fatal("%s: buffer error: %s", __func__, ssh_err(r));
807 for (version = 1; version < 3; version++) {
808 tab = idtab_lookup(version);
809 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
810 nxt = TAILQ_NEXT(id, next);
811 /* Skip file--based keys */
812 if (id->provider == NULL)
814 if (!strcmp(provider, id->provider)) {
815 TAILQ_REMOVE(&tab->idlist, id, next);
821 if (pkcs11_del_provider(provider) == 0)
824 error("process_remove_smartcard_key:"
825 " pkcs11_del_provider failed");
827 send_status(e, success);
829 #endif /* ENABLE_PKCS11 */
831 /* dispatch incoming messages */
834 process_message(SocketEntry *e)
841 if (sshbuf_len(e->input) < 5)
842 return; /* Incomplete message. */
843 cp = sshbuf_ptr(e->input);
844 msg_len = PEEK_U32(cp);
845 if (msg_len > 256 * 1024) {
849 if (sshbuf_len(e->input) < msg_len + 4)
852 /* move the current input to e->request */
853 sshbuf_reset(e->request);
854 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
855 (r = sshbuf_get_u8(e->request, &type)) != 0)
856 fatal("%s: buffer error: %s", __func__, ssh_err(r));
858 /* check wheter agent is locked */
859 if (locked && type != SSH_AGENTC_UNLOCK) {
860 sshbuf_reset(e->request);
862 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
863 case SSH2_AGENTC_REQUEST_IDENTITIES:
864 /* send empty lists */
865 no_identities(e, type);
868 /* send a fail message for all other request types */
874 debug("type %d", type);
876 case SSH_AGENTC_LOCK:
877 case SSH_AGENTC_UNLOCK:
878 process_lock_agent(e, type == SSH_AGENTC_LOCK);
882 case SSH_AGENTC_RSA_CHALLENGE:
883 process_authentication_challenge1(e);
885 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
886 process_request_identities(e, 1);
888 case SSH_AGENTC_ADD_RSA_IDENTITY:
889 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
890 process_add_identity(e, 1);
892 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
893 process_remove_identity(e, 1);
896 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
897 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
900 case SSH2_AGENTC_SIGN_REQUEST:
901 process_sign_request2(e);
903 case SSH2_AGENTC_REQUEST_IDENTITIES:
904 process_request_identities(e, 2);
906 case SSH2_AGENTC_ADD_IDENTITY:
907 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
908 process_add_identity(e, 2);
910 case SSH2_AGENTC_REMOVE_IDENTITY:
911 process_remove_identity(e, 2);
913 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
914 process_remove_all_identities(e, 2);
917 case SSH_AGENTC_ADD_SMARTCARD_KEY:
918 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
919 process_add_smartcard_key(e);
921 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
922 process_remove_smartcard_key(e);
924 #endif /* ENABLE_PKCS11 */
926 /* Unknown message. Respond with failure. */
927 error("Unknown message %d", type);
928 sshbuf_reset(e->request);
935 new_socket(sock_type type, int fd)
937 u_int i, old_alloc, new_alloc;
944 for (i = 0; i < sockets_alloc; i++)
945 if (sockets[i].type == AUTH_UNUSED) {
947 if ((sockets[i].input = sshbuf_new()) == NULL)
948 fatal("%s: sshbuf_new failed", __func__);
949 if ((sockets[i].output = sshbuf_new()) == NULL)
950 fatal("%s: sshbuf_new failed", __func__);
951 if ((sockets[i].request = sshbuf_new()) == NULL)
952 fatal("%s: sshbuf_new failed", __func__);
953 sockets[i].type = type;
956 old_alloc = sockets_alloc;
957 new_alloc = sockets_alloc + 10;
958 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
959 for (i = old_alloc; i < new_alloc; i++)
960 sockets[i].type = AUTH_UNUSED;
961 sockets_alloc = new_alloc;
962 sockets[old_alloc].fd = fd;
963 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
964 fatal("%s: sshbuf_new failed", __func__);
965 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
966 fatal("%s: sshbuf_new failed", __func__);
967 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
968 fatal("%s: sshbuf_new failed", __func__);
969 sockets[old_alloc].type = type;
973 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
974 struct timeval **tvpp)
978 static struct timeval tv;
981 for (i = 0; i < sockets_alloc; i++) {
982 switch (sockets[i].type) {
984 case AUTH_CONNECTION:
985 n = MAX(n, sockets[i].fd);
990 fatal("Unknown socket type %d", sockets[i].type);
995 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
996 if (*fdrp == NULL || sz > *nallocp) {
1000 *fdwp = xmalloc(sz);
1004 debug("XXX shrink: %d < %d", n, *fdl);
1006 memset(*fdrp, 0, sz);
1007 memset(*fdwp, 0, sz);
1009 for (i = 0; i < sockets_alloc; i++) {
1010 switch (sockets[i].type) {
1012 case AUTH_CONNECTION:
1013 FD_SET(sockets[i].fd, *fdrp);
1014 if (sshbuf_len(sockets[i].output) > 0)
1015 FD_SET(sockets[i].fd, *fdwp);
1021 deadline = reaper();
1022 if (parent_alive_interval != 0)
1023 deadline = (deadline == 0) ? parent_alive_interval :
1024 MIN(deadline, parent_alive_interval);
1025 if (deadline == 0) {
1028 tv.tv_sec = deadline;
1036 after_select(fd_set *readset, fd_set *writeset)
1038 struct sockaddr_un sunaddr;
1042 u_int i, orig_alloc;
1046 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1047 switch (sockets[i].type) {
1051 if (FD_ISSET(sockets[i].fd, readset)) {
1052 slen = sizeof(sunaddr);
1053 sock = accept(sockets[i].fd,
1054 (struct sockaddr *)&sunaddr, &slen);
1056 error("accept from AUTH_SOCKET: %s",
1060 if (getpeereid(sock, &euid, &egid) < 0) {
1061 error("getpeereid %d failed: %s",
1062 sock, strerror(errno));
1066 if ((euid != 0) && (getuid() != euid)) {
1067 error("uid mismatch: "
1068 "peer euid %u != uid %u",
1069 (u_int) euid, (u_int) getuid());
1073 new_socket(AUTH_CONNECTION, sock);
1076 case AUTH_CONNECTION:
1077 if (sshbuf_len(sockets[i].output) > 0 &&
1078 FD_ISSET(sockets[i].fd, writeset)) {
1079 len = write(sockets[i].fd,
1080 sshbuf_ptr(sockets[i].output),
1081 sshbuf_len(sockets[i].output));
1082 if (len == -1 && (errno == EAGAIN ||
1083 errno == EWOULDBLOCK ||
1087 close_socket(&sockets[i]);
1090 if ((r = sshbuf_consume(sockets[i].output,
1092 fatal("%s: buffer error: %s",
1093 __func__, ssh_err(r));
1095 if (FD_ISSET(sockets[i].fd, readset)) {
1096 len = read(sockets[i].fd, buf, sizeof(buf));
1097 if (len == -1 && (errno == EAGAIN ||
1098 errno == EWOULDBLOCK ||
1102 close_socket(&sockets[i]);
1105 if ((r = sshbuf_put(sockets[i].input,
1107 fatal("%s: buffer error: %s",
1108 __func__, ssh_err(r));
1109 explicit_bzero(buf, sizeof(buf));
1110 process_message(&sockets[i]);
1114 fatal("Unknown type %d", sockets[i].type);
1119 cleanup_socket(void)
1121 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1123 debug("%s: cleanup", __func__);
1125 unlink(socket_name);
1139 cleanup_handler(int sig)
1142 #ifdef ENABLE_PKCS11
1149 check_parent_exists(void)
1152 * If our parent has exited then getppid() will return (pid_t)1,
1153 * so testing for that should be safe.
1155 if (parent_pid != -1 && getppid() != parent_pid) {
1156 /* printf("Parent has died - Authentication agent exiting.\n"); */
1166 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1167 " [-t life] [command [arg ...]]\n"
1168 " ssh-agent [-c | -s] -k\n");
1173 main(int ac, char **av)
1175 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1176 int sock, fd, ch, result, saved_errno;
1178 char *shell, *format, *pidstr, *agentsocket = NULL;
1179 fd_set *readsetp = NULL, *writesetp = NULL;
1180 #ifdef HAVE_SETRLIMIT
1184 extern char *optarg;
1186 char pidstrbuf[1 + 3 * sizeof pid];
1187 struct timeval *tvp = NULL;
1191 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1198 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1199 /* Disable ptrace on Linux without sgid bit */
1200 prctl(PR_SET_DUMPABLE, 0);
1204 OpenSSL_add_all_algorithms();
1207 __progname = ssh_get_progname(av[0]);
1210 while ((ch = getopt(ac, av, "cDdksE:a:t:")) != -1) {
1213 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1214 if (fingerprint_hash == -1)
1215 fatal("Invalid hash algorithm \"%s\"", optarg);
1231 if (d_flag || D_flag)
1236 if (d_flag || D_flag)
1241 agentsocket = optarg;
1244 if ((lifetime = convtime(optarg)) == -1) {
1245 fprintf(stderr, "Invalid lifetime\n");
1256 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1259 if (ac == 0 && !c_flag && !s_flag) {
1260 shell = getenv("SHELL");
1261 if (shell != NULL && (len = strlen(shell)) > 2 &&
1262 strncmp(shell + len - 3, "csh", 3) == 0)
1266 const char *errstr = NULL;
1268 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1269 if (pidstr == NULL) {
1270 fprintf(stderr, "%s not set, cannot kill agent\n",
1271 SSH_AGENTPID_ENV_NAME);
1274 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1277 "%s=\"%s\", which is not a good PID: %s\n",
1278 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1281 if (kill(pid, SIGTERM) == -1) {
1285 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1286 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1287 printf(format, SSH_AGENTPID_ENV_NAME);
1288 printf("echo Agent pid %ld killed;\n", (long)pid);
1291 parent_pid = getpid();
1293 if (agentsocket == NULL) {
1294 /* Create private directory for agent socket */
1295 mktemp_proto(socket_dir, sizeof(socket_dir));
1296 if (mkdtemp(socket_dir) == NULL) {
1297 perror("mkdtemp: private socket dir");
1300 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1303 /* Try to use specified agent socket */
1304 socket_dir[0] = '\0';
1305 strlcpy(socket_name, agentsocket, sizeof socket_name);
1309 * Create socket early so it will exist before command gets run from
1312 prev_mask = umask(0177);
1313 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1315 /* XXX - unix_listener() calls error() not perror() */
1316 *socket_name = '\0'; /* Don't unlink any existing file */
1322 * Fork, and have the parent execute the command, if any, or present
1323 * the socket data. The child continues as the authentication agent.
1325 if (D_flag || d_flag) {
1326 log_init(__progname,
1327 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1328 SYSLOG_FACILITY_AUTH, 1);
1329 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1330 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1331 SSH_AUTHSOCKET_ENV_NAME);
1332 printf("echo Agent pid %ld;\n", (long)parent_pid);
1340 if (pid != 0) { /* Parent - execute the given command. */
1342 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1344 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1345 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1346 SSH_AUTHSOCKET_ENV_NAME);
1347 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1348 SSH_AGENTPID_ENV_NAME);
1349 printf("echo Agent pid %ld;\n", (long)pid);
1352 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1353 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1362 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1364 if (setsid() == -1) {
1365 error("setsid: %s", strerror(errno));
1370 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1371 /* XXX might close listen socket */
1372 (void)dup2(fd, STDIN_FILENO);
1373 (void)dup2(fd, STDOUT_FILENO);
1374 (void)dup2(fd, STDERR_FILENO);
1379 #ifdef HAVE_SETRLIMIT
1380 /* deny core dumps, since memory contains unencrypted private keys */
1381 rlim.rlim_cur = rlim.rlim_max = 0;
1382 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1383 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1390 cleanup_pid = getpid();
1392 #ifdef ENABLE_PKCS11
1395 new_socket(AUTH_SOCKET, sock);
1397 parent_alive_interval = 10;
1399 signal(SIGPIPE, SIG_IGN);
1400 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1401 signal(SIGHUP, cleanup_handler);
1402 signal(SIGTERM, cleanup_handler);
1406 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1407 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1408 saved_errno = errno;
1409 if (parent_alive_interval != 0)
1410 check_parent_exists();
1411 (void) reaper(); /* remove expired keys */
1413 if (saved_errno == EINTR)
1415 fatal("select: %s", strerror(saved_errno));
1416 } else if (result > 0)
1417 after_select(readsetp, writesetp);