1 /* $OpenBSD: ssh-agent.c,v 1.199 2015/03/04 21:12:59 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/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"
72 #include "key.h" /* XXX for typedef */
73 #include "buffer.h" /* XXX for typedef */
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 char *lock_passwd = NULL;
146 extern char *__progname;
148 /* Default lifetime in seconds (0 == forever) */
149 static long lifetime = 0;
151 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
154 close_socket(SocketEntry *e)
158 e->type = AUTH_UNUSED;
159 sshbuf_free(e->input);
160 sshbuf_free(e->output);
161 sshbuf_free(e->request);
169 for (i = 0; i <=2; i++) {
170 TAILQ_INIT(&idtable[i].idlist);
171 idtable[i].nentries = 0;
175 /* return private key table for requested protocol version */
177 idtab_lookup(int version)
179 if (version < 1 || version > 2)
180 fatal("internal error, bad protocol version %d", version);
181 return &idtable[version];
185 free_identity(Identity *id)
187 sshkey_free(id->key);
193 /* return matching private key for given public key */
195 lookup_identity(struct sshkey *key, int version)
199 Idtab *tab = idtab_lookup(version);
200 TAILQ_FOREACH(id, &tab->idlist, next) {
201 if (sshkey_equal(key, id->key))
207 /* Check confirmation of keysign request */
209 confirm_key(Identity *id)
214 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
216 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
225 send_status(SocketEntry *e, int success)
229 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
230 (r = sshbuf_put_u8(e->output, success ?
231 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
232 fatal("%s: buffer error: %s", __func__, ssh_err(r));
235 /* send list of supported public keys to 'client' */
237 process_request_identities(SocketEntry *e, int version)
239 Idtab *tab = idtab_lookup(version);
244 if ((msg = sshbuf_new()) == NULL)
245 fatal("%s: sshbuf_new failed", __func__);
246 if ((r = sshbuf_put_u8(msg, (version == 1) ?
247 SSH_AGENT_RSA_IDENTITIES_ANSWER :
248 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
249 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
250 fatal("%s: buffer error: %s", __func__, ssh_err(r));
251 TAILQ_FOREACH(id, &tab->idlist, next) {
252 if (id->key->type == KEY_RSA1) {
254 if ((r = sshbuf_put_u32(msg,
255 BN_num_bits(id->key->rsa->n))) != 0 ||
256 (r = sshbuf_put_bignum1(msg,
257 id->key->rsa->e)) != 0 ||
258 (r = sshbuf_put_bignum1(msg,
259 id->key->rsa->n)) != 0)
260 fatal("%s: buffer error: %s",
261 __func__, ssh_err(r));
267 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
268 error("%s: sshkey_to_blob: %s", __func__,
272 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
273 fatal("%s: buffer error: %s",
274 __func__, ssh_err(r));
277 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
278 fatal("%s: buffer error: %s", __func__, ssh_err(r));
280 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
281 fatal("%s: buffer error: %s", __func__, ssh_err(r));
288 process_authentication_challenge1(SocketEntry *e)
290 u_char buf[32], mdbuf[16], session_id[16];
296 struct ssh_digest_ctx *md;
299 if ((msg = sshbuf_new()) == NULL)
300 fatal("%s: sshbuf_new failed", __func__);
301 if ((key = sshkey_new(KEY_RSA1)) == NULL)
302 fatal("%s: sshkey_new failed", __func__);
303 if ((challenge = BN_new()) == NULL)
304 fatal("%s: BN_new failed", __func__);
306 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
307 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
308 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
309 (r = sshbuf_get_bignum1(e->request, challenge)))
310 fatal("%s: buffer error: %s", __func__, ssh_err(r));
312 /* Only protocol 1.1 is supported */
313 if (sshbuf_len(e->request) == 0)
315 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
316 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
317 fatal("%s: buffer error: %s", __func__, ssh_err(r));
318 if (response_type != 1)
321 id = lookup_identity(key, 1);
322 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
323 struct sshkey *private = id->key;
324 /* Decrypt the challenge using the private key. */
325 if ((r = rsa_private_decrypt(challenge, challenge,
326 private->rsa) != 0)) {
327 fatal("%s: rsa_public_encrypt: %s", __func__,
329 goto failure; /* XXX ? */
332 /* The response is MD5 of decrypted challenge plus session id */
333 len = BN_num_bytes(challenge);
334 if (len <= 0 || len > 32) {
335 logit("%s: bad challenge length %d", __func__, len);
339 BN_bn2bin(challenge, buf + 32 - len);
340 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
341 ssh_digest_update(md, buf, 32) < 0 ||
342 ssh_digest_update(md, session_id, 16) < 0 ||
343 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
344 fatal("%s: md5 failed", __func__);
347 /* Send the response. */
348 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
349 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
350 fatal("%s: buffer error: %s", __func__, ssh_err(r));
355 /* Unknown identity or protocol error. Send failure. */
356 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
357 fatal("%s: buffer error: %s", __func__, ssh_err(r));
359 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
360 fatal("%s: buffer error: %s", __func__, ssh_err(r));
362 BN_clear_free(challenge);
369 process_sign_request2(SocketEntry *e)
371 u_char *blob, *data, *signature = NULL;
372 size_t blen, dlen, slen = 0;
373 u_int compat = 0, flags;
379 if ((msg = sshbuf_new()) == NULL)
380 fatal("%s: sshbuf_new failed", __func__);
381 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
382 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
383 (r = sshbuf_get_u32(e->request, &flags)) != 0)
384 fatal("%s: buffer error: %s", __func__, ssh_err(r));
385 if (flags & SSH_AGENT_OLD_SIGNATURE)
386 compat = SSH_BUG_SIGBLOB;
387 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
388 error("%s: cannot parse key blob: %s", __func__, ssh_err(ok));
391 if ((id = lookup_identity(key, 2)) == NULL) {
392 verbose("%s: %s key not found", __func__, sshkey_type(key));
395 if (id->confirm && confirm_key(id) != 0) {
396 verbose("%s: user refused key", __func__);
399 if ((r = sshkey_sign(id->key, &signature, &slen,
400 data, dlen, compat)) != 0) {
401 error("%s: sshkey_sign: %s", __func__, ssh_err(ok));
409 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
410 (r = sshbuf_put_string(msg, signature, slen)) != 0)
411 fatal("%s: buffer error: %s", __func__, ssh_err(r));
412 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
413 fatal("%s: buffer error: %s", __func__, ssh_err(r));
415 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
416 fatal("%s: buffer error: %s", __func__, ssh_err(r));
426 process_remove_identity(SocketEntry *e, int version)
430 struct sshkey *key = NULL;
434 #endif /* WITH_SSH1 */
439 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
440 error("%s: sshkey_new failed", __func__);
443 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
444 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
445 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
446 fatal("%s: buffer error: %s", __func__, ssh_err(r));
448 if (bits != sshkey_size(key))
449 logit("Warning: identity keysize mismatch: "
450 "actual %u, announced %u",
451 sshkey_size(key), bits);
453 #endif /* WITH_SSH1 */
455 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
456 fatal("%s: buffer error: %s", __func__, ssh_err(r));
457 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
458 error("%s: sshkey_from_blob failed: %s",
459 __func__, ssh_err(r));
464 Identity *id = lookup_identity(key, version);
467 * We have this key. Free the old key. Since we
468 * don't want to leave empty slots in the middle of
469 * the array, we actually free the key there and move
470 * all the entries between the empty slot and the end
473 Idtab *tab = idtab_lookup(version);
474 if (tab->nentries < 1)
475 fatal("process_remove_identity: "
476 "internal error: tab->nentries %d",
478 TAILQ_REMOVE(&tab->idlist, id, next);
485 send_status(e, success);
489 process_remove_all_identities(SocketEntry *e, int version)
491 Idtab *tab = idtab_lookup(version);
494 /* Loop over all identities and clear the keys. */
495 for (id = TAILQ_FIRST(&tab->idlist); id;
496 id = TAILQ_FIRST(&tab->idlist)) {
497 TAILQ_REMOVE(&tab->idlist, id, next);
501 /* Mark that there are no identities. */
508 /* removes expired keys and returns number of seconds until the next expiry */
512 time_t deadline = 0, now = monotime();
517 for (version = 1; version < 3; version++) {
518 tab = idtab_lookup(version);
519 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
520 nxt = TAILQ_NEXT(id, next);
523 if (now >= id->death) {
524 debug("expiring key '%s'", id->comment);
525 TAILQ_REMOVE(&tab->idlist, id, next);
529 deadline = (deadline == 0) ? id->death :
530 MIN(deadline, id->death);
533 if (deadline == 0 || deadline <= now)
536 return (deadline - now);
540 * XXX this and the corresponding serialisation function probably belongs
545 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
547 struct sshkey *k = NULL;
548 int r = SSH_ERR_INTERNAL_ERROR;
551 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
552 return SSH_ERR_ALLOC_FAIL;
554 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
555 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
556 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
557 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
558 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
559 /* SSH1 and SSL have p and q swapped */
560 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
561 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
564 /* Generate additional parameters */
565 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
567 /* enable blinding */
568 if (RSA_blinding_on(k->rsa, NULL) != 1) {
569 r = SSH_ERR_LIBCRYPTO_ERROR;
581 #endif /* WITH_SSH1 */
584 process_add_identity(SocketEntry *e, int version)
586 Idtab *tab = idtab_lookup(version);
588 int success = 0, confirm = 0;
590 char *comment = NULL;
592 struct sshkey *k = NULL;
594 int r = SSH_ERR_INTERNAL_ERROR;
599 r = agent_decode_rsa1(e->request, &k);
601 #endif /* WITH_SSH1 */
603 r = sshkey_private_deserialize(e->request, &k);
606 if (r != 0 || k == NULL ||
607 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
608 error("%s: decode private key: %s", __func__, ssh_err(r));
612 while (sshbuf_len(e->request)) {
613 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
614 error("%s: buffer error: %s", __func__, ssh_err(r));
618 case SSH_AGENT_CONSTRAIN_LIFETIME:
619 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
620 error("%s: bad lifetime constraint: %s",
621 __func__, ssh_err(r));
624 death = monotime() + seconds;
626 case SSH_AGENT_CONSTRAIN_CONFIRM:
630 error("%s: Unknown constraint %d", __func__, ctype);
632 sshbuf_reset(e->request);
640 if (lifetime && !death)
641 death = monotime() + lifetime;
642 if ((id = lookup_identity(k, version)) == NULL) {
643 id = xcalloc(1, sizeof(Identity));
645 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
646 /* Increment the number of identities. */
652 id->comment = comment;
654 id->confirm = confirm;
656 send_status(e, success);
659 /* XXX todo: encrypt sensitive data with passphrase */
661 process_lock_agent(SocketEntry *e, int lock)
666 if ((r = sshbuf_get_cstring(e->request, &passwd, NULL)) != 0)
667 fatal("%s: buffer error: %s", __func__, ssh_err(r));
668 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
670 explicit_bzero(lock_passwd, strlen(lock_passwd));
674 } else if (!locked && lock) {
676 lock_passwd = xstrdup(passwd);
679 explicit_bzero(passwd, strlen(passwd));
681 send_status(e, success);
685 no_identities(SocketEntry *e, u_int type)
690 if ((msg = sshbuf_new()) == NULL)
691 fatal("%s: sshbuf_new failed", __func__);
692 if ((r = sshbuf_put_u8(msg,
693 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
694 SSH_AGENT_RSA_IDENTITIES_ANSWER :
695 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
696 (r = sshbuf_put_u32(msg, 0)) != 0 ||
697 (r = sshbuf_put_stringb(e->output, msg)) != 0)
698 fatal("%s: buffer error: %s", __func__, ssh_err(r));
704 process_add_smartcard_key(SocketEntry *e)
706 char *provider = NULL, *pin;
707 int r, i, version, count = 0, success = 0, confirm = 0;
711 struct sshkey **keys = NULL, *k;
715 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
716 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
717 fatal("%s: buffer error: %s", __func__, ssh_err(r));
719 while (sshbuf_len(e->request)) {
720 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
721 fatal("%s: buffer error: %s", __func__, ssh_err(r));
723 case SSH_AGENT_CONSTRAIN_LIFETIME:
724 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
725 fatal("%s: buffer error: %s",
726 __func__, ssh_err(r));
727 death = monotime() + seconds;
729 case SSH_AGENT_CONSTRAIN_CONFIRM:
733 error("process_add_smartcard_key: "
734 "Unknown constraint type %d", type);
738 if (lifetime && !death)
739 death = monotime() + lifetime;
741 count = pkcs11_add_provider(provider, pin, &keys);
742 for (i = 0; i < count; i++) {
744 version = k->type == KEY_RSA1 ? 1 : 2;
745 tab = idtab_lookup(version);
746 if (lookup_identity(k, version) == NULL) {
747 id = xcalloc(1, sizeof(Identity));
749 id->provider = xstrdup(provider);
750 id->comment = xstrdup(provider); /* XXX */
752 id->confirm = confirm;
753 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
765 send_status(e, success);
769 process_remove_smartcard_key(SocketEntry *e)
771 char *provider = NULL, *pin = NULL;
772 int r, version, success = 0;
776 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
777 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
778 fatal("%s: buffer error: %s", __func__, ssh_err(r));
781 for (version = 1; version < 3; version++) {
782 tab = idtab_lookup(version);
783 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
784 nxt = TAILQ_NEXT(id, next);
785 /* Skip file--based keys */
786 if (id->provider == NULL)
788 if (!strcmp(provider, id->provider)) {
789 TAILQ_REMOVE(&tab->idlist, id, next);
795 if (pkcs11_del_provider(provider) == 0)
798 error("process_remove_smartcard_key:"
799 " pkcs11_del_provider failed");
801 send_status(e, success);
803 #endif /* ENABLE_PKCS11 */
805 /* dispatch incoming messages */
808 process_message(SocketEntry *e)
815 if (sshbuf_len(e->input) < 5)
816 return; /* Incomplete message. */
817 cp = sshbuf_ptr(e->input);
818 msg_len = PEEK_U32(cp);
819 if (msg_len > 256 * 1024) {
823 if (sshbuf_len(e->input) < msg_len + 4)
826 /* move the current input to e->request */
827 sshbuf_reset(e->request);
828 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
829 (r = sshbuf_get_u8(e->request, &type)) != 0)
830 fatal("%s: buffer error: %s", __func__, ssh_err(r));
832 /* check wheter agent is locked */
833 if (locked && type != SSH_AGENTC_UNLOCK) {
834 sshbuf_reset(e->request);
836 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
837 case SSH2_AGENTC_REQUEST_IDENTITIES:
838 /* send empty lists */
839 no_identities(e, type);
842 /* send a fail message for all other request types */
848 debug("type %d", type);
850 case SSH_AGENTC_LOCK:
851 case SSH_AGENTC_UNLOCK:
852 process_lock_agent(e, type == SSH_AGENTC_LOCK);
856 case SSH_AGENTC_RSA_CHALLENGE:
857 process_authentication_challenge1(e);
859 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
860 process_request_identities(e, 1);
862 case SSH_AGENTC_ADD_RSA_IDENTITY:
863 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
864 process_add_identity(e, 1);
866 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
867 process_remove_identity(e, 1);
870 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
871 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
874 case SSH2_AGENTC_SIGN_REQUEST:
875 process_sign_request2(e);
877 case SSH2_AGENTC_REQUEST_IDENTITIES:
878 process_request_identities(e, 2);
880 case SSH2_AGENTC_ADD_IDENTITY:
881 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
882 process_add_identity(e, 2);
884 case SSH2_AGENTC_REMOVE_IDENTITY:
885 process_remove_identity(e, 2);
887 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
888 process_remove_all_identities(e, 2);
891 case SSH_AGENTC_ADD_SMARTCARD_KEY:
892 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
893 process_add_smartcard_key(e);
895 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
896 process_remove_smartcard_key(e);
898 #endif /* ENABLE_PKCS11 */
900 /* Unknown message. Respond with failure. */
901 error("Unknown message %d", type);
902 sshbuf_reset(e->request);
909 new_socket(sock_type type, int fd)
911 u_int i, old_alloc, new_alloc;
918 for (i = 0; i < sockets_alloc; i++)
919 if (sockets[i].type == AUTH_UNUSED) {
921 if ((sockets[i].input = sshbuf_new()) == NULL)
922 fatal("%s: sshbuf_new failed", __func__);
923 if ((sockets[i].output = sshbuf_new()) == NULL)
924 fatal("%s: sshbuf_new failed", __func__);
925 if ((sockets[i].request = sshbuf_new()) == NULL)
926 fatal("%s: sshbuf_new failed", __func__);
927 sockets[i].type = type;
930 old_alloc = sockets_alloc;
931 new_alloc = sockets_alloc + 10;
932 sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
933 for (i = old_alloc; i < new_alloc; i++)
934 sockets[i].type = AUTH_UNUSED;
935 sockets_alloc = new_alloc;
936 sockets[old_alloc].fd = fd;
937 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
938 fatal("%s: sshbuf_new failed", __func__);
939 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
940 fatal("%s: sshbuf_new failed", __func__);
941 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
942 fatal("%s: sshbuf_new failed", __func__);
943 sockets[old_alloc].type = type;
947 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
948 struct timeval **tvpp)
952 static struct timeval tv;
955 for (i = 0; i < sockets_alloc; i++) {
956 switch (sockets[i].type) {
958 case AUTH_CONNECTION:
959 n = MAX(n, sockets[i].fd);
964 fatal("Unknown socket type %d", sockets[i].type);
969 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
970 if (*fdrp == NULL || sz > *nallocp) {
978 debug("XXX shrink: %d < %d", n, *fdl);
980 memset(*fdrp, 0, sz);
981 memset(*fdwp, 0, sz);
983 for (i = 0; i < sockets_alloc; i++) {
984 switch (sockets[i].type) {
986 case AUTH_CONNECTION:
987 FD_SET(sockets[i].fd, *fdrp);
988 if (sshbuf_len(sockets[i].output) > 0)
989 FD_SET(sockets[i].fd, *fdwp);
996 if (parent_alive_interval != 0)
997 deadline = (deadline == 0) ? parent_alive_interval :
998 MIN(deadline, parent_alive_interval);
1002 tv.tv_sec = deadline;
1010 after_select(fd_set *readset, fd_set *writeset)
1012 struct sockaddr_un sunaddr;
1016 u_int i, orig_alloc;
1020 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1021 switch (sockets[i].type) {
1025 if (FD_ISSET(sockets[i].fd, readset)) {
1026 slen = sizeof(sunaddr);
1027 sock = accept(sockets[i].fd,
1028 (struct sockaddr *)&sunaddr, &slen);
1030 error("accept from AUTH_SOCKET: %s",
1034 if (getpeereid(sock, &euid, &egid) < 0) {
1035 error("getpeereid %d failed: %s",
1036 sock, strerror(errno));
1040 if ((euid != 0) && (getuid() != euid)) {
1041 error("uid mismatch: "
1042 "peer euid %u != uid %u",
1043 (u_int) euid, (u_int) getuid());
1047 new_socket(AUTH_CONNECTION, sock);
1050 case AUTH_CONNECTION:
1051 if (sshbuf_len(sockets[i].output) > 0 &&
1052 FD_ISSET(sockets[i].fd, writeset)) {
1053 len = write(sockets[i].fd,
1054 sshbuf_ptr(sockets[i].output),
1055 sshbuf_len(sockets[i].output));
1056 if (len == -1 && (errno == EAGAIN ||
1057 errno == EWOULDBLOCK ||
1061 close_socket(&sockets[i]);
1064 if ((r = sshbuf_consume(sockets[i].output,
1066 fatal("%s: buffer error: %s",
1067 __func__, ssh_err(r));
1069 if (FD_ISSET(sockets[i].fd, readset)) {
1070 len = read(sockets[i].fd, buf, sizeof(buf));
1071 if (len == -1 && (errno == EAGAIN ||
1072 errno == EWOULDBLOCK ||
1076 close_socket(&sockets[i]);
1079 if ((r = sshbuf_put(sockets[i].input,
1081 fatal("%s: buffer error: %s",
1082 __func__, ssh_err(r));
1083 explicit_bzero(buf, sizeof(buf));
1084 process_message(&sockets[i]);
1088 fatal("Unknown type %d", sockets[i].type);
1093 cleanup_socket(void)
1095 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1097 debug("%s: cleanup", __func__);
1099 unlink(socket_name);
1113 cleanup_handler(int sig)
1116 #ifdef ENABLE_PKCS11
1123 check_parent_exists(void)
1126 * If our parent has exited then getppid() will return (pid_t)1,
1127 * so testing for that should be safe.
1129 if (parent_pid != -1 && getppid() != parent_pid) {
1130 /* printf("Parent has died - Authentication agent exiting.\n"); */
1140 "usage: ssh-agent [-c | -s] [-d] [-a bind_address] [-E fingerprint_hash]\n"
1141 " [-t life] [command [arg ...]]\n"
1142 " ssh-agent [-c | -s] -k\n");
1147 main(int ac, char **av)
1149 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1150 int sock, fd, ch, result, saved_errno;
1152 char *shell, *format, *pidstr, *agentsocket = NULL;
1153 fd_set *readsetp = NULL, *writesetp = NULL;
1154 #ifdef HAVE_SETRLIMIT
1158 extern char *optarg;
1160 char pidstrbuf[1 + 3 * sizeof pid];
1161 struct timeval *tvp = NULL;
1165 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1172 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1173 /* Disable ptrace on Linux without sgid bit */
1174 prctl(PR_SET_DUMPABLE, 0);
1178 OpenSSL_add_all_algorithms();
1181 __progname = ssh_get_progname(av[0]);
1184 while ((ch = getopt(ac, av, "cdksE:a:t:")) != -1) {
1187 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1188 if (fingerprint_hash == -1)
1189 fatal("Invalid hash algorithm \"%s\"", optarg);
1210 agentsocket = optarg;
1213 if ((lifetime = convtime(optarg)) == -1) {
1214 fprintf(stderr, "Invalid lifetime\n");
1225 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1228 if (ac == 0 && !c_flag && !s_flag) {
1229 shell = getenv("SHELL");
1230 if (shell != NULL && (len = strlen(shell)) > 2 &&
1231 strncmp(shell + len - 3, "csh", 3) == 0)
1235 const char *errstr = NULL;
1237 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1238 if (pidstr == NULL) {
1239 fprintf(stderr, "%s not set, cannot kill agent\n",
1240 SSH_AGENTPID_ENV_NAME);
1243 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1246 "%s=\"%s\", which is not a good PID: %s\n",
1247 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1250 if (kill(pid, SIGTERM) == -1) {
1254 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1255 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1256 printf(format, SSH_AGENTPID_ENV_NAME);
1257 printf("echo Agent pid %ld killed;\n", (long)pid);
1260 parent_pid = getpid();
1262 if (agentsocket == NULL) {
1263 /* Create private directory for agent socket */
1264 mktemp_proto(socket_dir, sizeof(socket_dir));
1265 if (mkdtemp(socket_dir) == NULL) {
1266 perror("mkdtemp: private socket dir");
1269 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1272 /* Try to use specified agent socket */
1273 socket_dir[0] = '\0';
1274 strlcpy(socket_name, agentsocket, sizeof socket_name);
1278 * Create socket early so it will exist before command gets run from
1281 prev_mask = umask(0177);
1282 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1284 /* XXX - unix_listener() calls error() not perror() */
1285 *socket_name = '\0'; /* Don't unlink any existing file */
1291 * Fork, and have the parent execute the command, if any, or present
1292 * the socket data. The child continues as the authentication agent.
1295 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1296 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1297 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1298 SSH_AUTHSOCKET_ENV_NAME);
1299 printf("echo Agent pid %ld;\n", (long)parent_pid);
1307 if (pid != 0) { /* Parent - execute the given command. */
1309 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1311 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1312 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1313 SSH_AUTHSOCKET_ENV_NAME);
1314 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1315 SSH_AGENTPID_ENV_NAME);
1316 printf("echo Agent pid %ld;\n", (long)pid);
1319 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1320 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1329 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1331 if (setsid() == -1) {
1332 error("setsid: %s", strerror(errno));
1337 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1338 /* XXX might close listen socket */
1339 (void)dup2(fd, STDIN_FILENO);
1340 (void)dup2(fd, STDOUT_FILENO);
1341 (void)dup2(fd, STDERR_FILENO);
1346 #ifdef HAVE_SETRLIMIT
1347 /* deny core dumps, since memory contains unencrypted private keys */
1348 rlim.rlim_cur = rlim.rlim_max = 0;
1349 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1350 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1357 cleanup_pid = getpid();
1359 #ifdef ENABLE_PKCS11
1362 new_socket(AUTH_SOCKET, sock);
1364 parent_alive_interval = 10;
1366 signal(SIGPIPE, SIG_IGN);
1367 signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1368 signal(SIGHUP, cleanup_handler);
1369 signal(SIGTERM, cleanup_handler);
1373 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1374 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1375 saved_errno = errno;
1376 if (parent_alive_interval != 0)
1377 check_parent_exists();
1378 (void) reaper(); /* remove expired keys */
1380 if (saved_errno == EINTR)
1382 fatal("select: %s", strerror(saved_errno));
1383 } else if (result > 0)
1384 after_select(readsetp, writesetp);