# 11211 - Pentesting Memcache

<details>

<summary><strong>从零开始学习 AWS 黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS 红队专家）</strong></a><strong>！</strong></summary>

支持 HackTricks 的其他方式：

* 如果您想看到您的**公司在 HackTricks 中做广告**或**下载 PDF 版的 HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFT**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)\*\* 上关注\*\*我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

## 协议信息

来自 [维基百科](https://en.wikipedia.org/wiki/Memcached)：

> **Memcached**（发音：mem-cashed，mem-cash-dee）是一个通用的分布式[内存缓存](https://en.wikipedia.org/wiki/Memory_caching)系统。它通常用于通过在 RAM 中缓存数据和对象来加速动态数据库驱动的网站，以减少必须读取外部数据源（如数据库或 API）的次数。

尽管 Memcached 支持 SASL，但大多数实例都是**无需身份验证的暴露状态**。

**默认端口：** 11211

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

## 枚举

### 手动

要提取存储在 memcache 实例中的所有信息，您需要：

1. 找到具有**活动项目**的**slabs**
2. 获取之前检测到的 slabs 的**键名**
3. 通过**获取键名**来**提取保存的数据**

请记住，这项服务只是一个**缓存**，因此**数据可能会出现和消失**。

```bash
echo "version" | nc -vn -w 1 <IP> 11211      #Get version
echo "stats" | nc -vn -w 1 <IP> 11211        #Get status
echo "stats slabs" | nc -vn -w 1 <IP> 11211  #Get slabs
echo "stats items" | nc -vn -w 1 <IP> 11211  #Get items of slabs with info
echo "stats cachedump <number> 0" | nc -vn -w 1 <IP> 11211  #Get key names (the 0 is for unlimited output size)
echo "get <item_name>" | nc -vn -w 1 <IP> 11211  #Get saved info

#This php will just dump the keys, you need to use "get <item_name> later"
sudo apt-get install php-memcached
php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'
```

### 手动2

```bash
sudo apt install libmemcached-tools
memcstat --servers=127.0.0.1 #Get stats
memcdump --servers=127.0.0.1 #Get all items
memccat  --servers=127.0.0.1 <item1> <item2> <item3> #Get info inside the item(s)
```

### 自动化

```bash
nmap -n -sV --script memcached-info -p 11211 <IP>   #Just gather info
msf > use auxiliary/gather/memcached_extractor      #Extracts saved data
msf > use auxiliary/scanner/memcached/memcached_amp #Check is UDP DDoS amplification attack is possible
```

## **Dumping Memcache Keys**

在memcache领域，这是一种通过slabs组织数据的协议，存在特定命令用于检查存储的数据，尽管有明显的限制：

1. 只能按slab类别转储密钥，将相似内容大小的密钥分组在一起。
2. 每个slab类别只能转储一页数据，相当于1MB的数据。
3. 这个功能是非官方的，可能随时停止使用，如[社区论坛](https://groups.google.com/forum/?fromgroups=#!topic/memcached/1-T8I-RVGKM)中所讨论的。

仅能从潜在的几GB数据中转储1MB的限制尤为重要。然而，根据具体需求，这种功能仍然可以提供有关密钥使用模式的见解。对于那些对机制不太感兴趣的人，访问[工具部分](https://lzone.de/cheat-sheet/memcached#tools)可以找到用于全面转储的实用程序。或者，下面概述了使用telnet直接与memcached设置进行交互的过程。

### **工作原理**

Memcache的内存组织至关重要。使用"-vv"选项启动memcache会显示其生成的slab类别，如下所示：

```bash
$ memcached -vv
slab class   1: chunk size        96 perslab   10922
[...]
```

要显示所有当前存在的slabs，使用以下命令：

```bash
stats slabs
```

向memcached 1.4.13添加一个键可说明slab类是如何填充和管理的。例如：

```bash
set mykey 0 60 1
1
STORED
```

执行"stats slabs"命令后添加密钥会产生关于slab利用率的详细统计信息：

```bash
stats slabs
[...]
```

这个输出显示了活跃的slab类型、已使用的块以及操作统计数据，为读取和写入操作的效率提供了见解。

另一个有用的命令是"stats items"，它提供了有关驱逐、内存限制和条目生命周期的数据：

```bash
stats items
[...]
```

### **转储密钥**

对于1.4.31版本之前的版本，可以通过以下方式按slab类转储密钥：

```bash
stats cachedump <slab class> <number of items to dump>
```

例如，要在类别＃1 中转储一个键：

```bash
stats cachedump 1 1000
ITEM mykey [1 b; 1350677968 s]
END
```

### **转储 Memcache 键（版本 1.4.31+）**

从 slab 类中提取并可选地转储键值的方法。

使用 memcache 版本 1.4.31 及以上，引入了一种新的更安全的方法，用于在生产环境中转储键，利用非阻塞模式，详细信息请参阅[发布说明](https://github.com/memcached/memcached/wiki/ReleaseNotes1431)。该方法生成大量输出，因此建议使用 'nc' 命令以提高效率。示例包括：

```bash
echo 'lru_crawler metadump all' | nc 127.0.0.1 11211 | head -1
echo 'lru_crawler metadump all' | nc 127.0.0.1 11211 | grep ee6ba58566e234ccbbce13f9a24f9a28
```

### **转储工具**

表格[来自这里](https://lzone.de/blog).

| 编程语言         | 工具                                                                                                                        | 功能                                                                |                                                                            |         |
| ------------ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------- | ------- |
| PHP          | [简单脚本](http://snipt.org/xtP)                                                                                              | 打印键名。                                                             |                                                                            |         |
| Perl         | [简单脚本](https://wiki.jasig.org/download/attachments/13572172/memcached-clean.pl?version=1\&modificationDate=1229693957401) | 打印键和值                                                             |                                                                            |         |
| Ruby         | [简单脚本](https://gist.github.com/1365005)                                                                                   | 打印键名。                                                             |                                                                            |         |
| Perl         | [memdump](https://search.cpan.org/~dmaki/Memcached-libmemcached-0.4202/src/libmemcached/docs/memdump.pod)                 | CPAN模块中的工具                                                        | [Memcached-libmemcached](https://search.cpan.org/~dmaki/Memcached-libmemc) | ached/) |
| PHP          | [memcache.php](http://livebookmark.net/journal/2008/05/21/memcachephp-stats-like-apcphp/)                                 | Memcache监控GUI，还允许转储键                                              |                                                                            |         |
| libmemcached | [peep](http://blog.evanweaver.com/2009/04/20/peeping-into-memcached/)                                                     | **会冻结您的memcached进程！！！** 在生产环境中使用时要小心。尽管如此，您可以绕过1MB限制，真正转储**所有**键。 |                                                                            |         |

## 故障排除 <a href="#troubleshooting" id="troubleshooting"></a>

### 1MB 数据限制 <a href="#id-1mb-data-limit" id="id-1mb-data-limit"></a>

请注意，在memcached 1.4之前，由于默认最大slab大小，您无法存储大于1MB的对象。

### 永远不要设置超过30天的超时！ <a href="#never-set-a-timeout--30-days" id="never-set-a-timeout--30-days"></a>

如果您尝试使用大于允许的最大超时设置“set”或“add”键，则可能不会得到您期望的结果，因为memcached会将该值视为Unix时间戳。此外，如果时间戳在过去，则根本不会执行任何操作。您的命令将悄无声息地失败。

因此，如果要使用最大生存时间，请指定2592000。示例：

```
set my_key 0 2592000 1
1
```

### 溢出时键值消失 <a href="#disappearing-keys-on-overflow" id="disappearing-keys-on-overflow"></a>

尽管文档中提到64位溢出值会导致使用“incr”时值消失，但需要使用“add”/“set”重新创建该值。

### 复制 <a href="#replication" id="replication"></a>

memcached本身不支持复制。如果确实需要，您需要使用第三方解决方案：

* [repcached](http://repcached.lab.klab.org/): 多主异步复制（memcached 1.2补丁集）
* [Couchbase memcached接口](http://www.couchbase.com/memcached): 使用CouchBase作为memcached的替代
* [yrmcds](https://cybozu.github.io/yrmcds/): 兼容memcached的主从键值存储
* [twemproxy](https://github.com/twitter/twemproxy)（又名nutcracker）：带有memcached支持的代理

### 命令速查表

{% content-ref url="/pages/N3Cx1wiK02yqtP4yjwkX" %}
[Memcache Commands](/network-services-pentesting/11211-memcache/memcache-commands.md)
{% endcontent-ref %}

### **Shodan**

* `port:11211 "STAT pid"`
* `"STAT pid"`

## 参考资料

* <https://lzone.de/cheat-sheet/memcached>

<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS Red Team Expert）</strong></a><strong>！</strong></summary>

支持HackTricks的其他方式：

* 如果您想在HackTricks中看到您的**公司广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索[**PEASS Family**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live) 上**关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hacktricks.xsx.tw/network-services-pentesting/11211-memcache.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
