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.
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"
89 #include "ssh-pkcs11.h"
92 #ifndef DEFAULT_PKCS11_WHITELIST
93 # define DEFAULT_PKCS11_WHITELIST "/usr/lib/*,/usr/local/lib/*"
96 #if defined(HAVE_SYS_PRCTL_H)
97 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
109 struct sshbuf *input;
110 struct sshbuf *output;
111 struct sshbuf *request;
114 u_int sockets_alloc = 0;
115 SocketEntry *sockets = NULL;
117 typedef struct identity {
118 TAILQ_ENTRY(identity) next;
128 TAILQ_HEAD(idqueue, identity) idlist;
131 /* private key table, one per protocol version */
136 /* pid of shell == parent of agent */
137 pid_t parent_pid = -1;
138 time_t parent_alive_interval = 0;
140 /* pid of process for which cleanup_socket is applicable */
141 pid_t cleanup_pid = 0;
143 /* pathname and directory for AUTH_SOCKET */
144 char socket_name[PATH_MAX];
145 char socket_dir[PATH_MAX];
147 /* PKCS#11 path whitelist */
148 static char *pkcs11_whitelist;
152 #define LOCK_SALT_SIZE 16
153 #define LOCK_ROUNDS 1
155 char lock_passwd[LOCK_SIZE];
156 char lock_salt[LOCK_SALT_SIZE];
158 extern char *__progname;
160 /* Default lifetime in seconds (0 == forever) */
161 static long lifetime = 0;
163 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
166 close_socket(SocketEntry *e)
170 e->type = AUTH_UNUSED;
171 sshbuf_free(e->input);
172 sshbuf_free(e->output);
173 sshbuf_free(e->request);
181 for (i = 0; i <=2; i++) {
182 TAILQ_INIT(&idtable[i].idlist);
183 idtable[i].nentries = 0;
187 /* return private key table for requested protocol version */
189 idtab_lookup(int version)
191 if (version < 1 || version > 2)
192 fatal("internal error, bad protocol version %d", version);
193 return &idtable[version];
197 free_identity(Identity *id)
199 sshkey_free(id->key);
205 /* return matching private key for given public key */
207 lookup_identity(struct sshkey *key, int version)
211 Idtab *tab = idtab_lookup(version);
212 TAILQ_FOREACH(id, &tab->idlist, next) {
213 if (sshkey_equal(key, id->key))
219 /* Check confirmation of keysign request */
221 confirm_key(Identity *id)
226 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
228 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
237 send_status(SocketEntry *e, int success)
241 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
242 (r = sshbuf_put_u8(e->output, success ?
243 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
244 fatal("%s: buffer error: %s", __func__, ssh_err(r));
247 /* send list of supported public keys to 'client' */
249 process_request_identities(SocketEntry *e, int version)
251 Idtab *tab = idtab_lookup(version);
256 if ((msg = sshbuf_new()) == NULL)
257 fatal("%s: sshbuf_new failed", __func__);
258 if ((r = sshbuf_put_u8(msg, (version == 1) ?
259 SSH_AGENT_RSA_IDENTITIES_ANSWER :
260 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
261 (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
262 fatal("%s: buffer error: %s", __func__, ssh_err(r));
263 TAILQ_FOREACH(id, &tab->idlist, next) {
264 if (id->key->type == KEY_RSA1) {
266 if ((r = sshbuf_put_u32(msg,
267 BN_num_bits(id->key->rsa->n))) != 0 ||
268 (r = sshbuf_put_bignum1(msg,
269 id->key->rsa->e)) != 0 ||
270 (r = sshbuf_put_bignum1(msg,
271 id->key->rsa->n)) != 0)
272 fatal("%s: buffer error: %s",
273 __func__, ssh_err(r));
279 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
280 error("%s: sshkey_to_blob: %s", __func__,
284 if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
285 fatal("%s: buffer error: %s",
286 __func__, ssh_err(r));
289 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
290 fatal("%s: buffer error: %s", __func__, ssh_err(r));
292 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
293 fatal("%s: buffer error: %s", __func__, ssh_err(r));
300 process_authentication_challenge1(SocketEntry *e)
302 u_char buf[32], mdbuf[16], session_id[16];
308 struct ssh_digest_ctx *md;
311 if ((msg = sshbuf_new()) == NULL)
312 fatal("%s: sshbuf_new failed", __func__);
313 if ((key = sshkey_new(KEY_RSA1)) == NULL)
314 fatal("%s: sshkey_new failed", __func__);
315 if ((challenge = BN_new()) == NULL)
316 fatal("%s: BN_new failed", __func__);
318 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
319 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
320 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
321 (r = sshbuf_get_bignum1(e->request, challenge)))
322 fatal("%s: buffer error: %s", __func__, ssh_err(r));
324 /* Only protocol 1.1 is supported */
325 if (sshbuf_len(e->request) == 0)
327 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
328 (r = sshbuf_get_u32(e->request, &response_type)) != 0)
329 fatal("%s: buffer error: %s", __func__, ssh_err(r));
330 if (response_type != 1)
333 id = lookup_identity(key, 1);
334 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
335 struct sshkey *private = id->key;
336 /* Decrypt the challenge using the private key. */
337 if ((r = rsa_private_decrypt(challenge, challenge,
338 private->rsa) != 0)) {
339 fatal("%s: rsa_public_encrypt: %s", __func__,
341 goto failure; /* XXX ? */
344 /* The response is MD5 of decrypted challenge plus session id */
345 len = BN_num_bytes(challenge);
346 if (len <= 0 || len > 32) {
347 logit("%s: bad challenge length %d", __func__, len);
351 BN_bn2bin(challenge, buf + 32 - len);
352 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
353 ssh_digest_update(md, buf, 32) < 0 ||
354 ssh_digest_update(md, session_id, 16) < 0 ||
355 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
356 fatal("%s: md5 failed", __func__);
359 /* Send the response. */
360 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
361 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
362 fatal("%s: buffer error: %s", __func__, ssh_err(r));
367 /* Unknown identity or protocol error. Send failure. */
368 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
369 fatal("%s: buffer error: %s", __func__, ssh_err(r));
371 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
372 fatal("%s: buffer error: %s", __func__, ssh_err(r));
374 BN_clear_free(challenge);
380 agent_decode_alg(struct sshkey *key, u_int flags)
382 if (key->type == KEY_RSA) {
383 if (flags & SSH_AGENT_RSA_SHA2_256)
384 return "rsa-sha2-256";
385 else if (flags & SSH_AGENT_RSA_SHA2_512)
386 return "rsa-sha2-512";
393 process_sign_request2(SocketEntry *e)
395 u_char *blob, *data, *signature = NULL;
396 size_t blen, dlen, slen = 0;
397 u_int compat = 0, flags;
403 if ((msg = sshbuf_new()) == NULL)
404 fatal("%s: sshbuf_new failed", __func__);
405 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
406 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
407 (r = sshbuf_get_u32(e->request, &flags)) != 0)
408 fatal("%s: buffer error: %s", __func__, ssh_err(r));
409 if (flags & SSH_AGENT_OLD_SIGNATURE)
410 compat = SSH_BUG_SIGBLOB;
411 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
412 error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
415 if ((id = lookup_identity(key, 2)) == NULL) {
416 verbose("%s: %s key not found", __func__, sshkey_type(key));
419 if (id->confirm && confirm_key(id) != 0) {
420 verbose("%s: user refused key", __func__);
423 if ((r = sshkey_sign(id->key, &signature, &slen,
424 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
425 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
433 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
434 (r = sshbuf_put_string(msg, signature, slen)) != 0)
435 fatal("%s: buffer error: %s", __func__, ssh_err(r));
436 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
437 fatal("%s: buffer error: %s", __func__, ssh_err(r));
439 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
440 fatal("%s: buffer error: %s", __func__, ssh_err(r));
450 process_remove_identity(SocketEntry *e, int version)
454 struct sshkey *key = NULL;
458 #endif /* WITH_SSH1 */
463 if ((key = sshkey_new(KEY_RSA1)) == NULL) {
464 error("%s: sshkey_new failed", __func__);
467 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
468 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
469 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
470 fatal("%s: buffer error: %s", __func__, ssh_err(r));
472 if (bits != sshkey_size(key))
473 logit("Warning: identity keysize mismatch: "
474 "actual %u, announced %u",
475 sshkey_size(key), bits);
477 #endif /* WITH_SSH1 */
479 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
480 fatal("%s: buffer error: %s", __func__, ssh_err(r));
481 if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
482 error("%s: sshkey_from_blob failed: %s",
483 __func__, ssh_err(r));
488 Identity *id = lookup_identity(key, version);
491 * We have this key. Free the old key. Since we
492 * don't want to leave empty slots in the middle of
493 * the array, we actually free the key there and move
494 * all the entries between the empty slot and the end
497 Idtab *tab = idtab_lookup(version);
498 if (tab->nentries < 1)
499 fatal("process_remove_identity: "
500 "internal error: tab->nentries %d",
502 TAILQ_REMOVE(&tab->idlist, id, next);
509 send_status(e, success);
513 process_remove_all_identities(SocketEntry *e, int version)
515 Idtab *tab = idtab_lookup(version);
518 /* Loop over all identities and clear the keys. */
519 for (id = TAILQ_FIRST(&tab->idlist); id;
520 id = TAILQ_FIRST(&tab->idlist)) {
521 TAILQ_REMOVE(&tab->idlist, id, next);
525 /* Mark that there are no identities. */
532 /* removes expired keys and returns number of seconds until the next expiry */
536 time_t deadline = 0, now = monotime();
541 for (version = 1; version < 3; version++) {
542 tab = idtab_lookup(version);
543 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
544 nxt = TAILQ_NEXT(id, next);
547 if (now >= id->death) {
548 debug("expiring key '%s'", id->comment);
549 TAILQ_REMOVE(&tab->idlist, id, next);
553 deadline = (deadline == 0) ? id->death :
554 MIN(deadline, id->death);
557 if (deadline == 0 || deadline <= now)
560 return (deadline - now);
564 * XXX this and the corresponding serialisation function probably belongs
569 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
571 struct sshkey *k = NULL;
572 int r = SSH_ERR_INTERNAL_ERROR;
575 if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
576 return SSH_ERR_ALLOC_FAIL;
578 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */
579 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
580 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
581 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
582 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
583 /* SSH1 and SSL have p and q swapped */
584 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */
585 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */
588 /* Generate additional parameters */
589 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
591 /* enable blinding */
592 if (RSA_blinding_on(k->rsa, NULL) != 1) {
593 r = SSH_ERR_LIBCRYPTO_ERROR;
605 #endif /* WITH_SSH1 */
608 process_add_identity(SocketEntry *e, int version)
610 Idtab *tab = idtab_lookup(version);
612 int success = 0, confirm = 0;
614 char *comment = NULL;
616 struct sshkey *k = NULL;
618 int r = SSH_ERR_INTERNAL_ERROR;
623 r = agent_decode_rsa1(e->request, &k);
625 #endif /* WITH_SSH1 */
627 r = sshkey_private_deserialize(e->request, &k);
630 if (r != 0 || k == NULL ||
631 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
632 error("%s: decode private key: %s", __func__, ssh_err(r));
636 while (sshbuf_len(e->request)) {
637 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
638 error("%s: buffer error: %s", __func__, ssh_err(r));
642 case SSH_AGENT_CONSTRAIN_LIFETIME:
643 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
644 error("%s: bad lifetime constraint: %s",
645 __func__, ssh_err(r));
648 death = monotime() + seconds;
650 case SSH_AGENT_CONSTRAIN_CONFIRM:
654 error("%s: Unknown constraint %d", __func__, ctype);
656 sshbuf_reset(e->request);
664 if (lifetime && !death)
665 death = monotime() + lifetime;
666 if ((id = lookup_identity(k, version)) == NULL) {
667 id = xcalloc(1, sizeof(Identity));
669 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
670 /* Increment the number of identities. */
676 id->comment = comment;
678 id->confirm = confirm;
680 send_status(e, success);
683 /* XXX todo: encrypt sensitive data with passphrase */
685 process_lock_agent(SocketEntry *e, int lock)
687 int r, success = 0, delay;
688 char *passwd, passwdhash[LOCK_SIZE];
689 static u_int fail_count = 0;
692 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
693 fatal("%s: buffer error: %s", __func__, ssh_err(r));
695 debug("empty password not supported");
696 } else if (locked && !lock) {
697 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
698 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
699 fatal("bcrypt_pbkdf");
700 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) {
701 debug("agent unlocked");
704 explicit_bzero(lock_passwd, sizeof(lock_passwd));
707 /* delay in 0.1s increments up to 10s */
708 if (fail_count < 100)
710 delay = 100000 * fail_count;
711 debug("unlock failed, delaying %0.1lf seconds",
712 (double)delay/1000000);
715 explicit_bzero(passwdhash, sizeof(passwdhash));
716 } else if (!locked && lock) {
717 debug("agent locked");
719 arc4random_buf(lock_salt, sizeof(lock_salt));
720 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
721 lock_passwd, sizeof(lock_passwd), LOCK_ROUNDS) < 0)
722 fatal("bcrypt_pbkdf");
725 explicit_bzero(passwd, pwlen);
727 send_status(e, success);
731 no_identities(SocketEntry *e, u_int type)
736 if ((msg = sshbuf_new()) == NULL)
737 fatal("%s: sshbuf_new failed", __func__);
738 if ((r = sshbuf_put_u8(msg,
739 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
740 SSH_AGENT_RSA_IDENTITIES_ANSWER :
741 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
742 (r = sshbuf_put_u32(msg, 0)) != 0 ||
743 (r = sshbuf_put_stringb(e->output, msg)) != 0)
744 fatal("%s: buffer error: %s", __func__, ssh_err(r));
750 process_add_smartcard_key(SocketEntry *e)
752 char *provider = NULL, *pin, canonical_provider[PATH_MAX];
753 int r, i, version, count = 0, success = 0, confirm = 0;
757 struct sshkey **keys = NULL, *k;
761 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
762 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
763 fatal("%s: buffer error: %s", __func__, ssh_err(r));
765 while (sshbuf_len(e->request)) {
766 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
767 fatal("%s: buffer error: %s", __func__, ssh_err(r));
769 case SSH_AGENT_CONSTRAIN_LIFETIME:
770 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
771 fatal("%s: buffer error: %s",
772 __func__, ssh_err(r));
773 death = monotime() + seconds;
775 case SSH_AGENT_CONSTRAIN_CONFIRM:
779 error("process_add_smartcard_key: "
780 "Unknown constraint type %d", type);
784 if (realpath(provider, canonical_provider) == NULL) {
785 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
786 provider, strerror(errno));
789 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
790 verbose("refusing PKCS#11 add of \"%.100s\": "
791 "provider not whitelisted", canonical_provider);
794 debug("%s: add %.100s", __func__, canonical_provider);
795 if (lifetime && !death)
796 death = monotime() + lifetime;
798 count = pkcs11_add_provider(canonical_provider, pin, &keys);
799 for (i = 0; i < count; i++) {
801 version = k->type == KEY_RSA1 ? 1 : 2;
802 tab = idtab_lookup(version);
803 if (lookup_identity(k, version) == NULL) {
804 id = xcalloc(1, sizeof(Identity));
806 id->provider = xstrdup(canonical_provider);
807 id->comment = xstrdup(canonical_provider); /* XXX */
809 id->confirm = confirm;
810 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
822 send_status(e, success);
826 process_remove_smartcard_key(SocketEntry *e)
828 char *provider = NULL, *pin = NULL;
829 int r, version, success = 0;
833 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
834 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
835 fatal("%s: buffer error: %s", __func__, ssh_err(r));
838 for (version = 1; version < 3; version++) {
839 tab = idtab_lookup(version);
840 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
841 nxt = TAILQ_NEXT(id, next);
842 /* Skip file--based keys */
843 if (id->provider == NULL)
845 if (!strcmp(provider, id->provider)) {
846 TAILQ_REMOVE(&tab->idlist, id, next);
852 if (pkcs11_del_provider(provider) == 0)
855 error("process_remove_smartcard_key:"
856 " pkcs11_del_provider failed");
858 send_status(e, success);
860 #endif /* ENABLE_PKCS11 */
862 /* dispatch incoming messages */
865 process_message(SocketEntry *e)
872 if (sshbuf_len(e->input) < 5)
873 return; /* Incomplete message. */
874 cp = sshbuf_ptr(e->input);
875 msg_len = PEEK_U32(cp);
876 if (msg_len > 256 * 1024) {
880 if (sshbuf_len(e->input) < msg_len + 4)
883 /* move the current input to e->request */
884 sshbuf_reset(e->request);
885 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
886 (r = sshbuf_get_u8(e->request, &type)) != 0)
887 fatal("%s: buffer error: %s", __func__, ssh_err(r));
889 /* check wheter agent is locked */
890 if (locked && type != SSH_AGENTC_UNLOCK) {
891 sshbuf_reset(e->request);
893 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
894 case SSH2_AGENTC_REQUEST_IDENTITIES:
895 /* send empty lists */
896 no_identities(e, type);
899 /* send a fail message for all other request types */
905 debug("type %d", type);
907 case SSH_AGENTC_LOCK:
908 case SSH_AGENTC_UNLOCK:
909 process_lock_agent(e, type == SSH_AGENTC_LOCK);
913 case SSH_AGENTC_RSA_CHALLENGE:
914 process_authentication_challenge1(e);
916 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
917 process_request_identities(e, 1);
919 case SSH_AGENTC_ADD_RSA_IDENTITY:
920 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
921 process_add_identity(e, 1);
923 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
924 process_remove_identity(e, 1);
927 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
928 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
931 case SSH2_AGENTC_SIGN_REQUEST:
932 process_sign_request2(e);
934 case SSH2_AGENTC_REQUEST_IDENTITIES:
935 process_request_identities(e, 2);
937 case SSH2_AGENTC_ADD_IDENTITY:
938 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
939 process_add_identity(e, 2);
941 case SSH2_AGENTC_REMOVE_IDENTITY:
942 process_remove_identity(e, 2);
944 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
945 process_remove_all_identities(e, 2);
948 case SSH_AGENTC_ADD_SMARTCARD_KEY:
949 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
950 process_add_smartcard_key(e);
952 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
953 process_remove_smartcard_key(e);
955 #endif /* ENABLE_PKCS11 */
957 /* Unknown message. Respond with failure. */
958 error("Unknown message %d", type);
959 sshbuf_reset(e->request);
966 new_socket(sock_type type, int fd)
968 u_int i, old_alloc, new_alloc;
975 for (i = 0; i < sockets_alloc; i++)
976 if (sockets[i].type == AUTH_UNUSED) {
978 if ((sockets[i].input = sshbuf_new()) == NULL)
979 fatal("%s: sshbuf_new failed", __func__);
980 if ((sockets[i].output = sshbuf_new()) == NULL)
981 fatal("%s: sshbuf_new failed", __func__);
982 if ((sockets[i].request = sshbuf_new()) == NULL)
983 fatal("%s: sshbuf_new failed", __func__);
984 sockets[i].type = type;
987 old_alloc = sockets_alloc;
988 new_alloc = sockets_alloc + 10;
989 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
990 for (i = old_alloc; i < new_alloc; i++)
991 sockets[i].type = AUTH_UNUSED;
992 sockets_alloc = new_alloc;
993 sockets[old_alloc].fd = fd;
994 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
995 fatal("%s: sshbuf_new failed", __func__);
996 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
997 fatal("%s: sshbuf_new failed", __func__);
998 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
999 fatal("%s: sshbuf_new failed", __func__);
1000 sockets[old_alloc].type = type;
1004 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1005 struct timeval **tvpp)
1009 static struct timeval tv;
1012 for (i = 0; i < sockets_alloc; i++) {
1013 switch (sockets[i].type) {
1015 case AUTH_CONNECTION:
1016 n = MAX(n, sockets[i].fd);
1021 fatal("Unknown socket type %d", sockets[i].type);
1026 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1027 if (*fdrp == NULL || sz > *nallocp) {
1030 *fdrp = xmalloc(sz);
1031 *fdwp = xmalloc(sz);
1035 debug("XXX shrink: %d < %d", n, *fdl);
1037 memset(*fdrp, 0, sz);
1038 memset(*fdwp, 0, sz);
1040 for (i = 0; i < sockets_alloc; i++) {
1041 switch (sockets[i].type) {
1043 case AUTH_CONNECTION:
1044 FD_SET(sockets[i].fd, *fdrp);
1045 if (sshbuf_len(sockets[i].output) > 0)
1046 FD_SET(sockets[i].fd, *fdwp);
1052 deadline = reaper();
1053 if (parent_alive_interval != 0)
1054 deadline = (deadline == 0) ? parent_alive_interval :
1055 MIN(deadline, parent_alive_interval);
1056 if (deadline == 0) {
1059 tv.tv_sec = deadline;
1067 after_select(fd_set *readset, fd_set *writeset)
1069 struct sockaddr_un sunaddr;
1073 u_int i, orig_alloc;
1077 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1078 switch (sockets[i].type) {
1082 if (FD_ISSET(sockets[i].fd, readset)) {
1083 slen = sizeof(sunaddr);
1084 sock = accept(sockets[i].fd,
1085 (struct sockaddr *)&sunaddr, &slen);
1087 error("accept from AUTH_SOCKET: %s",
1091 if (getpeereid(sock, &euid, &egid) < 0) {
1092 error("getpeereid %d failed: %s",
1093 sock, strerror(errno));
1097 if ((euid != 0) && (getuid() != euid)) {
1098 error("uid mismatch: "
1099 "peer euid %u != uid %u",
1100 (u_int) euid, (u_int) getuid());
1104 new_socket(AUTH_CONNECTION, sock);
1107 case AUTH_CONNECTION:
1108 if (sshbuf_len(sockets[i].output) > 0 &&
1109 FD_ISSET(sockets[i].fd, writeset)) {
1110 len = write(sockets[i].fd,
1111 sshbuf_ptr(sockets[i].output),
1112 sshbuf_len(sockets[i].output));
1113 if (len == -1 && (errno == EAGAIN ||
1114 errno == EWOULDBLOCK ||
1118 close_socket(&sockets[i]);
1121 if ((r = sshbuf_consume(sockets[i].output,
1123 fatal("%s: buffer error: %s",
1124 __func__, ssh_err(r));
1126 if (FD_ISSET(sockets[i].fd, readset)) {
1127 len = read(sockets[i].fd, buf, sizeof(buf));
1128 if (len == -1 && (errno == EAGAIN ||
1129 errno == EWOULDBLOCK ||
1133 close_socket(&sockets[i]);
1136 if ((r = sshbuf_put(sockets[i].input,
1138 fatal("%s: buffer error: %s",
1139 __func__, ssh_err(r));
1140 explicit_bzero(buf, sizeof(buf));
1141 process_message(&sockets[i]);
1145 fatal("Unknown type %d", sockets[i].type);
1150 cleanup_socket(void)
1152 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1154 debug("%s: cleanup", __func__);
1156 unlink(socket_name);
1170 cleanup_handler(int sig)
1173 #ifdef ENABLE_PKCS11
1180 check_parent_exists(void)
1183 * If our parent has exited then getppid() will return (pid_t)1,
1184 * so testing for that should be safe.
1186 if (parent_pid != -1 && getppid() != parent_pid) {
1187 /* printf("Parent has died - Authentication agent exiting.\n"); */
1197 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1198 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1199 " ssh-agent [-c | -s] -k\n");
1204 main(int ac, char **av)
1206 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1207 int sock, fd, ch, result, saved_errno;
1209 char *shell, *format, *pidstr, *agentsocket = NULL;
1210 fd_set *readsetp = NULL, *writesetp = NULL;
1211 #ifdef HAVE_SETRLIMIT
1215 extern char *optarg;
1217 char pidstrbuf[1 + 3 * sizeof pid];
1218 struct timeval *tvp = NULL;
1222 ssh_malloc_init(); /* must be called before any mallocs */
1223 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1230 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1231 /* Disable ptrace on Linux without sgid bit */
1232 prctl(PR_SET_DUMPABLE, 0);
1236 OpenSSL_add_all_algorithms();
1239 __progname = ssh_get_progname(av[0]);
1242 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1245 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1246 if (fingerprint_hash == -1)
1247 fatal("Invalid hash algorithm \"%s\"", optarg);
1258 if (pkcs11_whitelist != NULL)
1259 fatal("-P option already specified");
1260 pkcs11_whitelist = xstrdup(optarg);
1268 if (d_flag || D_flag)
1273 if (d_flag || D_flag)
1278 agentsocket = optarg;
1281 if ((lifetime = convtime(optarg)) == -1) {
1282 fprintf(stderr, "Invalid lifetime\n");
1293 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1296 if (pkcs11_whitelist == NULL)
1297 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1299 if (ac == 0 && !c_flag && !s_flag) {
1300 shell = getenv("SHELL");
1301 if (shell != NULL && (len = strlen(shell)) > 2 &&
1302 strncmp(shell + len - 3, "csh", 3) == 0)
1306 const char *errstr = NULL;
1308 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1309 if (pidstr == NULL) {
1310 fprintf(stderr, "%s not set, cannot kill agent\n",
1311 SSH_AGENTPID_ENV_NAME);
1314 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1317 "%s=\"%s\", which is not a good PID: %s\n",
1318 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1321 if (kill(pid, SIGTERM) == -1) {
1325 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1326 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1327 printf(format, SSH_AGENTPID_ENV_NAME);
1328 printf("echo Agent pid %ld killed;\n", (long)pid);
1331 parent_pid = getpid();
1333 if (agentsocket == NULL) {
1334 /* Create private directory for agent socket */
1335 mktemp_proto(socket_dir, sizeof(socket_dir));
1336 if (mkdtemp(socket_dir) == NULL) {
1337 perror("mkdtemp: private socket dir");
1340 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1343 /* Try to use specified agent socket */
1344 socket_dir[0] = '\0';
1345 strlcpy(socket_name, agentsocket, sizeof socket_name);
1349 * Create socket early so it will exist before command gets run from
1352 prev_mask = umask(0177);
1353 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1355 /* XXX - unix_listener() calls error() not perror() */
1356 *socket_name = '\0'; /* Don't unlink any existing file */
1362 * Fork, and have the parent execute the command, if any, or present
1363 * the socket data. The child continues as the authentication agent.
1365 if (D_flag || d_flag) {
1366 log_init(__progname,
1367 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1368 SYSLOG_FACILITY_AUTH, 1);
1369 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1370 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1371 SSH_AUTHSOCKET_ENV_NAME);
1372 printf("echo Agent pid %ld;\n", (long)parent_pid);
1381 if (pid != 0) { /* Parent - execute the given command. */
1383 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1385 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1386 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1387 SSH_AUTHSOCKET_ENV_NAME);
1388 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1389 SSH_AGENTPID_ENV_NAME);
1390 printf("echo Agent pid %ld;\n", (long)pid);
1393 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1394 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1403 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1405 if (setsid() == -1) {
1406 error("setsid: %s", strerror(errno));
1411 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1412 /* XXX might close listen socket */
1413 (void)dup2(fd, STDIN_FILENO);
1414 (void)dup2(fd, STDOUT_FILENO);
1415 (void)dup2(fd, STDERR_FILENO);
1420 #ifdef HAVE_SETRLIMIT
1421 /* deny core dumps, since memory contains unencrypted private keys */
1422 rlim.rlim_cur = rlim.rlim_max = 0;
1423 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1424 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1431 cleanup_pid = getpid();
1433 #ifdef ENABLE_PKCS11
1436 new_socket(AUTH_SOCKET, sock);
1438 parent_alive_interval = 10;
1440 signal(SIGPIPE, SIG_IGN);
1441 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1442 signal(SIGHUP, cleanup_handler);
1443 signal(SIGTERM, cleanup_handler);
1446 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1447 fatal("%s: pledge: %s", __progname, strerror(errno));
1448 platform_pledge_agent();
1451 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1452 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1453 saved_errno = errno;
1454 if (parent_alive_interval != 0)
1455 check_parent_exists();
1456 (void) reaper(); /* remove expired keys */
1458 if (saved_errno == EINTR)
1460 fatal("select: %s", strerror(saved_errno));
1461 } else if (result > 0)
1462 after_select(readsetp, writesetp);