hacktricks/network-services-pentesting/11211-memcache/memcache-commands.md
carlospolop 63bd9641c0 f
2023-06-05 20:33:24 +02:00

309 lines
17 KiB
Markdown

# Comandos de Memcache
<details>
<summary><a href="https://cloud.hacktricks.xyz/pentesting-cloud/pentesting-cloud-methodology"><strong>☁️ HackTricks Cloud ☁️</strong></a> -<a href="https://twitter.com/hacktricks_live"><strong>🐦 Twitter 🐦</strong></a> - <a href="https://www.twitch.tv/hacktricks_live/schedule"><strong>🎙️ Twitch 🎙️</strong></a> - <a href="https://www.youtube.com/@hacktricks_LIVE"><strong>🎥 Youtube 🎥</strong></a></summary>
* ¿Trabajas en una **empresa de ciberseguridad**? ¿Quieres ver tu **empresa anunciada en HackTricks**? ¿O quieres tener acceso a la **última versión de PEASS o descargar HackTricks en PDF**? ¡Consulta los [**PLANES DE SUSCRIPCIÓN**](https://github.com/sponsors/carlospolop)!
* Descubre [**The PEASS Family**](https://opensea.io/collection/the-peass-family), nuestra colección exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* Obtén el [**swag oficial de PEASS y HackTricks**](https://peass.creator-spring.com)
* **Únete al** [**💬**](https://emojipedia.org/speech-balloon/) [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **sígueme** en **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Comparte tus trucos de hacking enviando PR al** [**repositorio de hacktricks**](https://github.com/carlospolop/hacktricks) **y al** [**repositorio de hacktricks-cloud**](https://github.com/carlospolop/hacktricks-cloud).
</details>
## Hoja de trucos de comandos
**De** [**https://lzone.de/cheat-sheet/memcached**](https://lzone.de/cheat-sheet/memcached)\*\*\*\*
Los comandos admitidos (los oficiales y algunos no oficiales) se documentan en el documento [doc/protocol.txt](https://github.com/memcached/memcached/blob/master/doc/protocol.txt).
Lamentablemente, la descripción de la sintaxis no es muy clara y un simple comando de ayuda que enumere los comandos existentes sería mucho mejor. Aquí hay una descripción general de los comandos que se pueden encontrar en la [fuente](https://github.com/memcached/memcached) (a partir del 19.08.2016):
| Comando | Descripción | Ejemplo |
| --------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| get | Lee un valor | `get mykey` |
| set | Establece una clave sin condiciones | <p><code>set mykey &#x3C;flags> &#x3C;ttl> &#x3C;size></code><br><br>&#x3C;p>Asegúrese de usar \r\n como saltos de línea al usar herramientas de CLI de Unix. Por ejemplo&#x3C;/p> <code>printf "set mykey 0 60 4\r\ndata\r\n" | nc localhost 11211</code></p> |
| add | Agrega una nueva clave | `add newkey 0 60 5` |
| replace | Sobrescribe una clave existente | `replace key 0 60 5` |
| append | Agrega datos a una clave existente | `append key 0 60 15` |
| prepend | Agrega datos al principio de una clave existente | `prepend key 0 60 15` |
| incr | Incrementa el valor de la clave numérica en la cantidad dada | `incr mykey 2` |
| decr | Decrementa el valor de la clave numérica en la cantidad dada | `decr mykey 5` |
| delete | Elimina una clave existente | `delete mykey` |
| flush\_all | Invalida todos los elementos inmediatamente | `flush_all` |
| flush\_all | Invalida todos los elementos en n segundos | `flush_all 900` |
| stats | Imprime estadísticas generales | `stats` |
| | Imprime estadísticas de memoria | `stats slabs` |
| | Imprime estadísticas de asignación de nivel superior | `stats malloc` |
| | Imprime información sobre elementos | `stats items` |
| | | `stats detail` |
| | | `stats sizes` |
| | Restablece los contadores de estadísticas | `stats reset` |
| lru\_crawler metadump | Vuelca (la mayoría de) los metadatos de (todos) los elementos en la caché | `lru_crawler metadump all` |
| version | Imprime la versión del servidor. | `version` |
| verbosity | Aumenta el nivel de registro | `verbosity` |
| quit | Termina la sesión | `quit` |
#### Estadísticas de tráfico <a href="#traffic-statistics" id="traffic-statistics"></a>
Puede consultar las estadísticas de tráfico actuales utilizando el comando.
```
stats
```
Obtendrás una lista que muestra el número de conexiones, bytes de entrada/salida y mucho más.
Ejemplo de salida:
```
STAT pid 14868
STAT uptime 175931
STAT time 1220540125
STAT version 1.2.2
STAT pointer_size 32
STAT rusage_user 620.299700
STAT rusage_system 1545.703017
STAT curr_items 228
STAT total_items 779
STAT bytes 15525
STAT curr_connections 92
STAT total_connections 1740
STAT connection_structures 165
STAT cmd_get 7411
STAT cmd_set 28445156
STAT get_hits 5183
STAT get_misses 2228
STAT evictions 0
STAT bytes_read 2112768087
STAT bytes_written 1000038245
STAT limit_maxbytes 52428800
STAT threads 1
END
```
#### Estadísticas de Memoria <a href="#memory-statistics" id="memory-statistics"></a>
Puedes consultar las estadísticas actuales de memoria usando
```
stats slabs
```
```
# Memcache Commands
Memcache is a distributed memory caching system often used to speed up dynamic web applications by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.
## Basic Commands
### SET
The `SET` command is used to store a value in memcache. The syntax is as follows:
```
SET <key> <flags> <exptime> <bytes> [noreply]\r\n
<value>\r\n
```
- `<key>`: The key under which to store the value.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value.
- `[noreply]`: Optional parameter that tells the server not to send a response.
Example:
```
SET mykey 0 3600 5\r\nhello\r\n
```
This sets the value of `mykey` to `hello`, with no flags, an expiration time of 3600 seconds (1 hour), and a value length of 5 bytes.
### GET
The `GET` command is used to retrieve a value from memcache. The syntax is as follows:
```
GET <key>\r\n
```
- `<key>`: The key of the value to retrieve.
Example:
```
GET mykey\r\n
```
This retrieves the value of `mykey`.
### DELETE
The `DELETE` command is used to delete a value from memcache. The syntax is as follows:
```
DELETE <key> [noreply]\r\n
```
- `<key>`: The key of the value to delete.
- `[noreply]`: Optional parameter that tells the server not to send a response.
Example:
```
DELETE mykey\r\n
```
This deletes the value of `mykey`.
## Advanced Commands
### STATS
The `STATS` command is used to retrieve statistics about the memcache server. The syntax is as follows:
```
STATS [settings]\r\n
```
- `[settings]`: Optional parameter that specifies which statistics to retrieve. If not specified, all statistics are returned.
Example:
```
STATS\r\n
```
This retrieves all statistics.
### FLUSH_ALL
The `FLUSH_ALL` command is used to delete all values from memcache. The syntax is as follows:
```
FLUSH_ALL [delay]\r\n
```
- `[delay]`: Optional parameter that specifies the number of seconds to wait before flushing the cache. If not specified, the cache is flushed immediately.
Example:
```
FLUSH_ALL\r\n
```
This immediately flushes the cache.
### INCR/DECR
The `INCR` and `DECR` commands are used to increment or decrement a numeric value in memcache. The syntax is as follows:
```
INCR <key> <value> [noreply]\r\n
DECR <key> <value> [noreply]\r\n
```
- `<key>`: The key of the value to increment or decrement.
- `<value>`: The amount to increment or decrement the value by.
- `[noreply]`: Optional parameter that tells the server not to send a response.
Example:
```
SET mycounter 0 0 1\r\n0\r\n
INCR mycounter 1\r\n
```
This sets the value of `mycounter` to `0`, then increments it by `1`.
### APPEND/PREPEND
The `APPEND` and `PREPEND` commands are used to append or prepend data to an existing value in memcache. The syntax is as follows:
```
APPEND <key> <flags> <exptime> <bytes> [noreply]\r\n
<value>\r\n
PREPEND <key> <flags> <exptime> <bytes> [noreply]\r\n
<value>\r\n
```
- `<key>`: The key of the value to append or prepend to.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value to append or prepend.
- `[noreply]`: Optional parameter that tells the server not to send a response.
Example:
```
SET mykey 0 0 5\r\nworld\r\n
APPEND mykey 0 0 1\r\n!\r\n
```
This sets the value of `mykey` to `world`, then appends `!` to it.
### CAS
The `CAS` command is used to check and set a value in memcache. The syntax is as follows:
```
CAS <key> <flags> <exptime> <bytes> <cas_unique> [noreply]\r\n
<value>\r\n
```
- `<key>`: The key of the value to check and set.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value.
- `<cas_unique>`: A unique value that identifies the current state of the value. If the value has been modified since it was last retrieved, the `CAS` command fails.
- `[noreply]`: Optional parameter that tells the server not to send a response.
Example:
```
SET mykey 0 0 5\r\nhello\r\n
gets mykey\r\n
# returns: VALUE mykey 0 5 123456\r\nhello\r\n
cas mykey 0 0 5 123456\r\nworld\r\n
```
This sets the value of `mykey` to `hello`, retrieves it with the `gets` command (which returns the value and its unique identifier), then sets it to `world` using the `cas` command (which only succeeds if the unique identifier matches the current state of the value).
```
STAT 1:chunk_size 80
STAT 1:chunks_per_page 13107
STAT 1:total_pages 1
STAT 1:total_chunks 13107
STAT 1:used_chunks 13106
STAT 1:free_chunks 1
STAT 1:free_chunks_end 12886
STAT 2:chunk_size 100
STAT 2:chunks_per_page 10485
STAT 2:total_pages 1
STAT 2:total_chunks 10485
STAT 2:used_chunks 10484
STAT 2:free_chunks 1
STAT 2:free_chunks_end 10477
[...]
STAT active_slabs 3
STAT total_malloced 3145436
END
```
Si no estás seguro de si tienes suficiente memoria para tu instancia de memcached, siempre debes estar atento a los contadores de "evictions" proporcionados por el comando "stats". Si tienes suficiente memoria para la instancia, el contador de "evictions" debería ser 0 o al menos no estar aumentando.
#### ¿Qué claves se utilizan? <a href="#which-keys-are-used" id="which-keys-are-used"></a>
No hay una función incorporada para determinar directamente el conjunto actual de claves. Sin embargo, puedes usar el
```
stats items
```
Comando para determinar cuántas claves existen.
```
stats items
```
```
stats items
STAT items:1:number 220
STAT items:1:age 83095
STAT items:2:number 7
STAT items:2:age 1405
[...]
END
```
Esto al menos ayuda a ver si se están utilizando claves. Para volcar los nombres de las claves desde un script PHP que ya accede a memcache, se puede utilizar el código PHP de [100days.de](http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html).