Parte 1: Linux
1.1 A filosofia: "tudo é arquivo"
No Linux, quase tudo é tratado como arquivo: um documento é arquivo, um disco é arquivo (/dev/sda), um processo tem representação em arquivo (/proc/1234), até uma conexão de rede aparece como arquivo. As mesmas ferramentas (cat, grep, ls) servem para inspecionar coisas muito diferentes. Imagine um escritório onde tudo, pessoas, salas, telefones, tem uma ficha padronizada no mesmo formato: você aprende a ler uma ficha e investiga qualquer coisa.
1.2 Estrutura de diretórios (FHS)
O Linux organiza tudo a partir da raiz / (não existe "C:"). É uma árvore invertida.
| Diretório | O que guarda | Relevância para cyber |
|---|---|---|
| /bin, /usr/bin | Comandos/executáveis | Binários adulterados = comprometimento |
| /sbin | Comandos de administração | · |
| /etc | Arquivos de configuração | Senhas, serviços, rede: ouro |
| /home | Pastas dos usuários | Dados, chaves SSH, histórico |
| /root | Pasta do superusuário | Alvo nobre |
| /var | Dados variáveis: logs (/var/log), web | A investigação vive aqui |
| /tmp | Temporários (limpo no boot) | Malware adora (gravável por todos) |
| /proc | Pseudo-arquivos de processos e kernel | Investigar processos em tempo real |
| /dev | Dispositivos (discos, terminais) | · |
| /boot | Kernel e arquivos de inicialização | · |
Dois lugares merecem seu olho de imediato: /etc (config, credenciais) e /var/log (o que aconteceu). Malware frequentemente se esconde em /tmp, /dev/shm ou pastas ocultas (que começam com ponto, tipo /home/user/.config/.oculto).
1.3 Terminal e shell
O shell é o interpretador de comandos (o mais comum é o Bash). É a interface mais poderosa do sistema: e por isso a mais visada.
pwd # onde estou
ls -la # lista tudo, com detalhes e ocultos
cd /var/log # mudar de diretório
cat arquivo # mostrar conteúdo
find / -name "*.conf" 2>/dev/null # procurar arquivos
grep "erro" log.txt # buscar texto dentro de arquivos
history # comandos digitados pelo usuário
O pipe | encadeia comandos (a saída de um vira entrada do outro), a essência do poder do Linux:
cat /etc/passwd | grep "/bin/bash" | wc -l # quantos usuários têm shell bash
ps aux | grep ssh # processos com "ssh" no nome
O history de um usuário (~/.bash_history) conta o que a pessoa (ou o atacante) digitou. Numa investigação, é uma das primeiras coisas a olhar: mas atacantes espertos limpam ou desabilitam o histórico, e isso, por si só, já é um indício.
1.4 Permissões: o coração do modelo de segurança do Linux
-rwxr-xr-- 1 julio devs 4096 Jan 10 12:00 script.sh
│└┬┘└┬┘└┬┘
│ │ │ └── outros: r-- (só ler)
│ │ └───── grupo: r-x (ler e executar)
│ └──────── dono: rwx (ler, escrever, executar)
└────────── tipo: - arquivo | d diretório | l link
Cada trio é r(4) w(2) x(1), para dono → grupo → outros. Soma por categoria: rwx=7, rw-=6, r-x=5, r--=4. Então rwxr-xr-- = 754.
chmod 640 arquivo # dono rw, grupo r, outros nada
chmod +x script.sh # dá permissão de execução
chmod u+x,g-w arquivo # simbólico: +x pro dono, tira w do grupo
chown julio:devs arquivo # muda dono e grupo
Permissões especiais que atacantes exploram:
| Bit | O que faz | Perigo |
|---|---|---|
| SUID | Executa com a permissão do dono do arquivo, não de quem roda | Binário root com SUID e explorável → escalada para root |
| SGID | Executa com a permissão do grupo | Similar |
| Sticky | Em pastas: só o dono do arquivo pode apagá-lo (ex.: /tmp) | Proteção |
find / -perm -4000 -type f 2>/dev/null # todos os binários com SUID
Permissões mal configuradas são uma das causas nº 1 de escalada de privilégio. Um script executável por "outros" que roda como root, um /etc/shadow legível por todos, um binário SUID vulnerável: tudo isso é caminho de usuário comum → root. Defesa: menor privilégio, auditar SUID/SGID e nunca dar 777 ("777" = todo mundo pode tudo = pesadelo).
1.5 Usuários e grupos
julio:x:1000:1000:Julio Martins:/home/julio:/bin/bash
│ │ │ │ │ │ │
user │ UID GID nome home shell
└── senha fica no shadow (o "x")
/etc/passwd lista usuários (legível por todos); /etc/shadow guarda os hashes (só root lê), alvo de quebra offline; /etc/group os grupos. UID 0 = root: se qualquer conta tem UID 0, ela é root; atacantes criam contas UID 0 escondidas.
sudo comando # roda como root (registra em log!)
su - julio # troca para o usuário julio
sudo -l # o que EU posso rodar como sudo (recon de privilégio)
Verificar /etc/passwd em busca de contas suspeitas (UID 0 indevido, usuários que ninguém criou), checar quem está no grupo sudo/wheel e revisar /etc/sudoers são passos básicos de auditoria. Uma configuração sudoers frouxa (usuário pode rodar vi como root) vira escalada trivial. E /etc/shadow roubado + hashcat/John = senhas comprometidas se forem fracas.
1.6 Processos
Um processo é um programa em execução, com um PID e um dono.
ps aux # todos os processos (a=todos, u=por usuário, x=sem terminal)
top / htop # monitor em tempo real (CPU, memória)
kill 1234 / kill -9 1234 # encerra / força
pstree # árvore de processos (quem é pai de quem)
ls -l /proc/1234/exe # qual binário roda (mesmo se deletado!)
cat /proc/1234/cmdline # linha de comando completa
Processos são onde o malware vive. Sinais de alerta: nome estranho, rodando de /tmp, binário deletado do disco mas ainda em memória (/proc/PID/exe aponta para "(deleted)": evasão clássica), ou CPU absurda (cryptominer). A relação pai-filho denuncia: um nginx que vira "pai" de um shell bash é altamente suspeito: provável exploração.
1.7 Serviços e systemd
Em servidores, programas ficam como serviços (daemons) que iniciam sozinhos. O gerenciador padrão é o systemd.
systemctl status ssh # estado de um serviço
systemctl enable/disable nginx # iniciar / não iniciar no boot
systemctl list-unit-files --state=enabled # o que sobe no boot
systemd é vetor de persistência: um atacante cria um serviço malicioso que sobe a cada boot. Investigação: liste serviços habilitados e desconfie de units recém-criadas, com nomes que imitam legítimos ("systemd-helper", "network-manager2") ou que executam scripts de /tmp. Timers do systemd (systemctl list-timers) são a versão moderna do cron e também servem para persistência.
1.8 SSH: acesso remoto seguro
SSH (Secure Shell) administra um servidor Linux remotamente, criptografado. Porta padrão: 22. Autenticação por chave (par pública/privada) é melhor que senha.
ssh julio@192.168.1.10 # conectar
scp arquivo julio@servidor:/tmp/ # copiar via SSH
ssh-keygen -t ed25519 # gera o par de chaves
ssh-copy-id julio@servidor # instala a chave pública no servidor
Hardening (em /etc/ssh/sshd_config): desabilitar login de root (PermitRootLogin no), só chave (PasswordAuthentication no), mudar a porta (reduz ruído de bots) e usar MFA.
SSH é um dos serviços mais escaneados e atacados da internet (brute force constante na 22). O arquivo ~/.ssh/authorized_keys é vetor de persistência favorito: o atacante adiciona a própria chave pública e volta quando quiser, sem senha. Sempre confira chaves não reconhecidas. Logs em /var/log/auth.log.
1.9 Logs: a memória do sistema
| Arquivo | O que registra |
|---|---|
| /var/log/auth.log (Debian) / secure (RHEL) | Autenticação: logins, sudo, SSH |
| /var/log/syslog / messages | Mensagens gerais do sistema |
| /var/log/kern.log | Kernel |
| /var/log/cron | Execução de tarefas agendadas |
| /var/log/apache2/, /var/log/nginx/ | Acessos web |
journalctl -u ssh # só do serviço ssh
journalctl --since "1 hour ago" # janela de tempo
journalctl -p err # só erros
grep "Failed password" /var/log/auth.log # brute force
grep "Accepted" /var/log/auth.log # logins bem-sucedidos
last / lastb # últimos logins / logins que falharam
Logs são a base da detecção e da perícia. Mas logs locais podem ser apagados pelo atacante (por isso empresas mandam para um SIEM central). Sinal de alerta: um auth.log com "buraco" temporal sugere que alguém limpou. A regra: quem apaga rastro, deixa o rastro de ter apagado.
1.10 Cron: o agendador de tarefas
┌───── minuto (0-59)
│ ┌─── hora (0-23)
│ │ ┌─ dia do mês (1-31)
│ │ │ ┌ mês (1-12)
│ │ │ │ ┌ dia da semana (0-7)
* * * * * comando
0 2 * * * /backup.sh # todo dia às 02:00
*/5 * * * * /script.sh # a cada 5 minutos
crontab -l # listar tarefas do usuário atual
cat /etc/crontab # crontab do sistema
ls /etc/cron.d/ # tarefas adicionais
Cron é o mecanismo de persistência mais clássico do Linux: o atacante agenda algo que a cada X minutos reconecta o backdoor ou baixa payload. Investigação obrigatória: crontab -l de cada usuário, /etc/crontab, /etc/cron.d/, /etc/cron.daily|hourly|weekly. Uma linha que roda algo de /tmp ou faz curl | bash para um IP estranho é red flag máxima. Um cron "a cada 5 minutos" é candidato a beaconing.
1.11 Bash scripting: o básico que você usa em cyber
#!/bin/bash
ALVO="192.168.1.1"
if ping -c 1 "$ALVO" &>/dev/null; then
echo "$ALVO está online"
else
echo "$ALVO está offline"
fi
# laço: varrer uma faixa
for ip in $(seq 1 10); do
ping -c 1 192.168.1.$ip &>/dev/null && echo "192.168.1.$ip vivo"
done
Conceitos-chave: variáveis ($VAR), condicionais (if), laços (for/while), redirecionamento (>, >>, 2>) e &&/||.
Você vai ler scripts o tempo todo, de administração legítima e de malware. Saber Bash te deixa entender o que um script faz antes de rodar (crucial ao analisar um curl | bash suspeito) e automatizar tarefas de SOC. grep, awk, sed, cut, sort, uniq são seus aliados para triturar logs.
Parte 2: Windows
O parque corporativo do mundo é majoritariamente Windows, e o coração dele é o Active Directory. Para cyber em ambiente empresarial, dominar AD não é opcional.
2.1 Active Directory (AD): a espinha dorsal da empresa
Em vez de cada computador ter sua lista de usuários e senhas (caos!), existe um cartório central que sabe quem é cada funcionário, a que setor pertence, o que pode fazer e autentica todo mundo. Esse cartório é o AD, e roda num servidor chamado Domain Controller (DC).
Floresta (Forest) ← container maior
└── Domínio: empresa.local ← unidade de administração/segurança
├── Unidades Organizacionais (OU) ← "pastas" para organizar
├── Usuários / Grupos / Computadores
Grupos poderosíssimos: Domain Admins, Enterprise Admins, Administrators.
Em pentest/red team, o objetivo quase sempre é "Domain Admin": controle total do domínio. Todo o campo de AD security gira em torno de como o atacante enumera o AD, escala privilégios e chega ao DC, e como o defensor detecta e barra isso. Grupos privilegiados devem ter o mínimo de membros e ser monitorados de perto.
2.2 DNS no ambiente Windows
O AD depende fortemente de DNS. Os clientes acham o DC através de registros DNS especiais (registros SRV). Sem DNS, o AD desmorona. Por isso, num ambiente Windows, o DC costuma ser também o servidor DNS.
O DNS interno mapeia toda a rede (nomes de servidores, DCs, serviços), então é uma mina de reconhecimento para o atacante. Ataques específicos de AD (envenenamento via LLMNR/NBT-NS) exploram como o Windows resolve nomes quando o DNS falha: o atacante responde no lugar e captura credenciais.
2.3 GPO: Group Policy Objects
É como o admin aplica configurações e regras em massa, de um lugar só. "Todos os PCs terão papel de parede X, senha mínima de 12 caracteres, USB bloqueado." O admin escreve uma vez (a GPO), vincula a uma OU, e vale para todos ali. Exemplos: política de senha, bloqueio de conta, restrições de software, mapeamento de drives, scripts de logon.
GPO é faca de dois gumes. Bem usada, é hardening em escala. Mas se um atacante modifica uma GPO, ele empurra malware para toda a rede de uma vez: um dos ataques mais devastadores em AD. Auditar quem pode editar GPOs e monitorar mudanças é essencial.
2.4 Autenticação: Kerberos e NTLM
Kerberos (moderno). Analogia do parque: você chega na bilheteria (o DC), mostra sua identidade e recebe uma pulseira mestra (TGT: Ticket Granting Ticket). Para entrar em cada brinquedo (serviço), mostra a pulseira e recebe um ingresso específico (TGS). Você nunca reapresenta a senha, só os tickets. Fluxo: login → pede TGT ao KDC (no DC) → KDC entrega o TGT → apresenta o TGT e pede um TGS para o serviço → apresenta o TGS ao serviço → acesso.
NTLM (legado). Desafio-resposta usando o hash da senha. Mais fraco, mas ainda existe por compatibilidade. É onde mora o Pass-the-Hash: basta o hash, sem a senha em texto.
Pass-the-Hash: autenticar com o hash NTLM roubado. Pass-the-Ticket: roubar e reutilizar tickets Kerberos. Kerberoasting: pedir TGS de contas de serviço e quebrar offline (senhas fracas que nunca expiram). Golden Ticket: com a chave da conta krbtgt, forjar TGTs válidos para qualquer usuário: controle quase absoluto. Defesa: desabilitar NTLM onde possível, senhas fortes em contas de serviço, monitorar pedidos de ticket anômalos e proteger a krbtgt.
2.5 PowerShell: o terminal de poder do Windows
É o Bash do Windows, orientado a objetos. Ferramenta de administração, e de ataque, mais poderosa da plataforma. Cmdlets no formato Verbo-Substantivo:
Get-Process # lista processos (equivale a ps)
Get-Service # lista serviços
Get-NetTCPConnection # conexões de rede (equivale a netstat)
Get-LocalUser # usuários locais
Get-EventLog -LogName Security -Newest 20
Get-ScheduledTask # tarefas agendadas
# Consultas ao AD:
Get-ADUser -Filter * # todos os usuários do domínio
Get-ADGroupMember "Domain Admins" # quem é admin do domínio
PowerShell é adorado por atacantes: nativo, poderoso e roda na memória (fileless, sem tocar o disco, difícil de detectar por AV tradicional). Frameworks ofensivos inteiros são escritos nele. A resposta defensiva é o logging avançado: Script Block Logging e Module Logging registram o que foi executado, mesmo ofuscado. Monitorar comandos suspeitos (download de payload, -EncodedCommand em Base64, Invoke-Expression) é uma das detecções mais valiosas em Windows.
2.6 Serviços no Windows
Get-Service # PowerShell
sc query # prompt clássico
sc qc nome_do_servico # config de um serviço (qual binário roda)
Serviços são vetor de persistência e escalada (como systemd no Linux). Falhas clássicas: unquoted service path (caminho sem aspas, permite injetar um executável no meio do caminho) e weak service permissions (usuário comum modifica o binário que roda como SYSTEM). Investigação: serviços recém-criados, com nomes que imitam legítimos ou apontando para binários em pastas suspeitas.
2.7 Registro do Windows (Registry)
Banco de dados central de configuração do Windows, organizado em "colmeias" (hives) e chaves.
| Hive | Abrev. | Conteúdo |
|---|---|---|
| HKEY_LOCAL_MACHINE | HKLM | Configurações do sistema (toda a máquina) |
| HKEY_CURRENT_USER | HKCU | Configurações do usuário logado |
| HKEY_CLASSES_ROOT | HKCR | Associações de arquivo |
| HKEY_USERS | HKU | Todos os perfis de usuário |
Acessar: regedit (gráfico) ou reg query.
O Registro é o paraíso da persistência no Windows. As chaves de execução automática ("Run keys") fazem programas iniciarem no logon:
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunMalware adiciona uma entrada ali para renascer a cada login. Ferramentas como Autoruns (Sysinternals) listam tudo que inicia automaticamente: um dos primeiros passos ao caçar persistência.
2.8 Event Viewer: os logs do Windows
Logs mais importantes: Security (autenticação, logons, privilégios: o mais importante), System (serviços, drivers) e Application. Cada evento tem um Event ID:
| Event ID | Log | Significado |
|---|---|---|
| 4624 | Security | Logon bem-sucedido |
| 4625 | Security | Logon falhou (brute force em massa) |
| 4634 / 4647 | Security | Logoff |
| 4672 | Security | Logon com privilégios especiais (admin) |
| 4688 | Security | Novo processo criado |
| 4720 | Security | Conta de usuário criada |
| 4732 / 4728 | Security | Usuário adicionado a grupo privilegiado |
| 7045 | System | Novo serviço instalado (persistência!) |
| 1102 | Security | Log de auditoria foi limpo |
Get-WinEvent -LogName Security -MaxEvents 50
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625} # só falhas
Dominar Event IDs transforma um monte de logs numa história. Muitos 4625 seguidos de um 4624 = brute force que teve sucesso. Um 4720 fora do processo normal = atacante criando persistência. Um 1102 = alguém apagando rastros. O tipo de logon ("Logon Type") também importa: tipo 3 (rede), 10 (RDP): revelam como alguém entrou.
Parte 3: Investigação (onde os dois mundos se encontram)
Dado um sistema (Linux ou Windows) possivelmente comprometido, o que você olha? A lógica é a mesma; muda a ferramenta.
3.1 Investigar processos suspeitos
O que procurar: processo com nome estranho ou que imita legítimo (svch0st.exe, scvhost.exe), rodando de local incomum (/tmp, C:\Users\Public, %TEMP%), relação pai-filho anômala (Word abrindo PowerShell; nginx abrindo bash), binário deletado ainda em execução, consumo de CPU/rede anormal.
# LINUX
ps auxf # árvore de processos
ls -l /proc/<PID>/exe # binário real (detecta "(deleted)")
lsof -p <PID> # arquivos e conexões abertos
# WINDOWS
Get-Process | Sort-Object CPU -Descending
Get-CimInstance Win32_Process | Select ProcessId, ParentProcessId, CommandLine
# Ou Process Explorer (Sysinternals)
3.2 Investigar conexões de rede
O que procurar: conexões de saída para IPs desconhecidos, portas incomuns escutando, e qual processo é dono de cada conexão.
# LINUX
ss -tulpn # portas em escuta + processo
ss -tanp # todas as conexões TCP + processo
lsof -i # arquivos de rede abertos
# WINDOWS
Get-NetTCPConnection -State Established
netstat -anob # conexões + processo (precisa admin)
Correlacione: "esse processo estranho tem uma conexão estabelecida com um IP na Rússia na porta 4444" → processo suspeito + conexão suspeita = provável C2.
3.3 Investigar tarefas agendadas
# LINUX
crontab -l ; cat /etc/crontab ; ls -la /etc/cron.*
systemctl list-timers # timers do systemd
# WINDOWS
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"}
Get-ScheduledTask | Get-ScheduledTaskInfo # última/próxima execução
3.4 Caçar mecanismos de persistência
Persistência = como o atacante garante que volta mesmo após reboot. O checklist mental:
No Linux: cron (de cada usuário, /etc/cron*), timers do systemd, serviços novos/suspeitos, chaves em ~/.ssh/authorized_keys, arquivos de perfil (~/.bashrc, ~/.profile, /etc/profile) com comandos injetados, binários SUID novos, contas UID 0 indevidas, módulos de kernel suspeitos (rootkits).
No Windows: Run keys no Registro, tarefas agendadas, serviços recém-criados (Event 7045), pasta Startup (shell:startup), WMI event subscriptions, contas novas/adicionadas a grupos admin (Event 4720/4732), e Autoruns para varrer tudo de uma vez.
O atacante precisa executar código (processos), manter acesso (persistência), falar com o C2 (conexões) e não ser visto (logs). Toda investigação é procurar as pegadas dessas necessidades: onde ele está rodando, como volta após reboot, como fala com o C2 e o que tentou apagar.
Linux: /etc (config/credenciais), /var/log (o que aconteceu), /tmp (onde malware se esconde). Permissões rwx, octal (7=rwx), SUID = escalada. /etc/passwd (usuários), /etc/shadow (hashes), UID 0 = root. Processos: ps aux, /proc/PID, pai-filho anômalo = suspeito. Persistência: cron, systemd, authorized_keys, .bashrc. Logs: auth.log, journalctl.
Windows: AD = cartório central; DC = alvo supremo; Domain Admins = objetivo do atacante. Autenticação: Kerberos (TGT/TGS), NTLM (Pass-the-Hash). PowerShell = poder total (e fileless); habilitar Script Block Logging. Registro: Run keys = persistência clássica. Event Viewer: 4625 (falha), 4624 (sucesso), 4720 (conta criada), 7045 (serviço novo), 1102 (log limpo).
Investigação (ambos): processos → conexões → tarefas agendadas → persistência → logs adulterados. Conheça o normal para reconhecer o anormal.
Suba duas VMs: um Linux (Ubuntu/Debian) e um Windows (Server com AD, se conseguir). No Linux, crie um cron "malicioso" inofensivo (um echo a cada minuto) e depois encontre-o só investigando, como se não soubesse que existe. No Windows, adicione uma entrada numa Run key e localize-a com Autoruns. Fazer o papel de atacante e depois de defensor no mesmo laboratório é o jeito mais rápido de fixar isto.
Part 1: Linux
1.1 The philosophy: "everything is a file"
In Linux, almost everything is treated as a file: a document is a file, a disk is a file (/dev/sda), a process has a file representation (/proc/1234), and even a network connection shows up as a file. The same tools (cat, grep, ls) can inspect very different things. Picture an office where everything, people, rooms, phones, has a standardized record in the same format: once you learn to read one record, you can investigate anything.
1.2 Directory structure (FHS)
Linux organizes everything from the root / (there is no "C:"). It is an upside-down tree.
| Directory | What it holds | Relevance for cyber |
|---|---|---|
| /bin, /usr/bin | Commands/executables | Tampered binaries = compromise |
| /sbin | Administration commands | · |
| /etc | Configuration files | Passwords, services, network: gold |
| /home | User folders | Data, SSH keys, history |
| /root | Superuser's folder | High-value target |
| /var | Variable data: logs (/var/log), web | Investigation lives here |
| /tmp | Temporary files (cleared on boot) | Malware loves it (world-writable) |
| /proc | Pseudo-files for processes and the kernel | Investigate processes in real time |
| /dev | Devices (disks, terminals) | · |
| /boot | Kernel and boot files | · |
Two places deserve your attention right away: /etc (config, credentials) and /var/log (what happened). Malware often hides in /tmp, /dev/shm or hidden folders (those starting with a dot, like /home/user/.config/.oculto).
1.3 Terminal and shell
The shell is the command interpreter (the most common one is Bash). It is the most powerful interface on the system, and that is why it is the most targeted.
pwd # where am I
ls -la # list everything, with details and hidden files
cd /var/log # change directory
cat arquivo # show contents
find / -name "*.conf" 2>/dev/null # search for files
grep "erro" log.txt # search for text inside files
history # commands typed by the user
The pipe | chains commands (the output of one becomes the input of the next), the essence of Linux's power:
cat /etc/passwd | grep "/bin/bash" | wc -l # how many users have a bash shell
ps aux | grep ssh # processes with "ssh" in the name
A user's history (~/.bash_history) tells you what that person (or the attacker) typed. In an investigation, it is one of the first things to check. But smart attackers clear or disable the history, and that, in itself, is already an indicator.
1.4 Permissions: the heart of the Linux security model
-rwxr-xr-- 1 julio devs 4096 Jan 10 12:00 script.sh
│└┬┘└┬┘└┬┘
│ │ │ └── others: r-- (read only)
│ │ └───── group: r-x (read and execute)
│ └──────── owner: rwx (read, write, execute)
└────────── type: - file | d directory | l link
Each triplet is r(4) w(2) x(1), for owner → group → others. Sum per category: rwx=7, rw-=6, r-x=5, r--=4. So rwxr-xr-- = 754.
chmod 640 arquivo # owner rw, group r, others nothing
chmod +x script.sh # grant execute permission
chmod u+x,g-w arquivo # symbolic: +x for owner, remove w from group
chown julio:devs arquivo # change owner and group
Special permissions attackers exploit:
| Bit | What it does | Danger |
|---|---|---|
| SUID | Runs with the permissions of the file's owner, not of whoever runs it | Exploitable root-owned SUID binary → escalation to root |
| SGID | Runs with the group's permissions | Similar |
| Sticky | On directories: only the file's owner can delete it (e.g. /tmp) | Protection |
find / -perm -4000 -type f 2>/dev/null # all binaries with SUID
Misconfigured permissions are one of the top causes of privilege escalation. A script executable by "others" that runs as root, a world-readable /etc/shadow, a vulnerable SUID binary: all of these are paths from regular user → root. Defense: least privilege, audit SUID/SGID and never grant 777 ("777" = everyone can do everything = nightmare).
1.5 Users and groups
julio:x:1000:1000:Julio Martins:/home/julio:/bin/bash
│ │ │ │ │ │ │
user │ UID GID name home shell
└── password is stored in shadow (the "x")
/etc/passwd lists users (world-readable); /etc/shadow stores the hashes (readable only by root), a target for offline cracking; /etc/group holds the groups. UID 0 = root: if any account has UID 0, it is root; attackers create hidden UID 0 accounts.
sudo comando # run as root (gets logged!)
su - julio # switch to user julio
sudo -l # what I can run with sudo (privilege recon)
Checking /etc/passwd for suspicious accounts (improper UID 0, users nobody created), checking who is in the sudo/wheel group and reviewing /etc/sudoers are basic audit steps. A loose sudoers configuration (a user can run vi as root) becomes trivial escalation. And a stolen /etc/shadow + hashcat/John = compromised passwords if they are weak.
1.6 Processes
A process is a running program, with a PID and an owner.
ps aux # all processes (a=all users, u=user-oriented format, x=no terminal)
top / htop # real-time monitor (CPU, memory)
kill 1234 / kill -9 1234 # terminate / force kill
pstree # process tree (who is the parent of whom)
ls -l /proc/1234/exe # which binary is running (even if deleted!)
cat /proc/1234/cmdline # full command line
Processes are where malware lives. Warning signs: an odd name, running from /tmp, a binary deleted from disk but still in memory (/proc/PID/exe points to "(deleted)": a classic evasion technique), or absurd CPU usage (cryptominer). The parent-child relationship gives it away: an nginx process that becomes the "parent" of a bash shell is highly suspicious, likely exploitation.
1.7 Services and systemd
On servers, programs run as services (daemons) that start on their own. The default manager is systemd.
systemctl status ssh # state of a service
systemctl enable/disable nginx # start / don't start at boot
systemctl list-unit-files --state=enabled # what starts at boot
systemd is a persistence vector: an attacker creates a malicious service that starts on every boot. Investigation: list enabled services and be suspicious of recently created units, units with names that mimic legitimate ones ("systemd-helper", "network-manager2") or units that run scripts from /tmp. systemd timers (systemctl list-timers) are the modern version of cron and can also be used for persistence.
1.8 SSH: secure remote access
SSH (Secure Shell) lets you administer a Linux server remotely, over an encrypted channel. Default port: 22. Key-based authentication (public/private key pair) is better than passwords.
ssh julio@192.168.1.10 # connect
scp arquivo julio@servidor:/tmp/ # copy over SSH
ssh-keygen -t ed25519 # generate the key pair
ssh-copy-id julio@servidor # install the public key on the server
Hardening (in /etc/ssh/sshd_config): disable root login (PermitRootLogin no), keys only (PasswordAuthentication no), change the port (reduces bot noise) and use MFA.
SSH is one of the most scanned and attacked services on the internet (constant brute force on port 22). The ~/.ssh/authorized_keys file is a favorite persistence vector: the attacker adds their own public key and comes back whenever they want, no password needed. Always check for unrecognized keys. Logs are in /var/log/auth.log.
1.9 Logs: the system's memory
| File | What it records |
|---|---|
| /var/log/auth.log (Debian) / secure (RHEL) | Authentication: logins, sudo, SSH |
| /var/log/syslog / messages | General system messages |
| /var/log/kern.log | Kernel |
| /var/log/cron | Scheduled task execution |
| /var/log/apache2/, /var/log/nginx/ | Web access |
journalctl -u ssh # ssh service only
journalctl --since "1 hour ago" # time window
journalctl -p err # errors only
grep "Failed password" /var/log/auth.log # brute force
grep "Accepted" /var/log/auth.log # successful logins
last / lastb # last logins / failed logins
Logs are the foundation of detection and forensics. But local logs can be deleted by the attacker (which is why companies ship them to a central SIEM). Warning sign: an auth.log with a time "gap" suggests someone wiped it. The rule: whoever erases their tracks leaves the track of having erased them.
1.10 Cron: the task scheduler
┌───── minute (0-59)
│ ┌─── hour (0-23)
│ │ ┌─ day of month (1-31)
│ │ │ ┌ month (1-12)
│ │ │ │ ┌ day of week (0-7)
* * * * * comando
0 2 * * * /backup.sh # every day at 02:00
*/5 * * * * /script.sh # every 5 minutes
crontab -l # list the current user's tasks
cat /etc/crontab # system crontab
ls /etc/cron.d/ # additional tasks
Cron is the most classic persistence mechanism on Linux: the attacker schedules something that, every X minutes, reconnects the backdoor or downloads a payload. Mandatory investigation: crontab -l for each user, /etc/crontab, /etc/cron.d/, /etc/cron.daily|hourly|weekly. A line that runs something from /tmp or does curl | bash to a strange IP is a maximum red flag. An "every 5 minutes" cron job is a beaconing candidate.
1.11 Bash scripting: the basics you use in cyber
#!/bin/bash
TARGET="192.168.1.1"
if ping -c 1 "$TARGET" &>/dev/null; then
echo "$TARGET is online"
else
echo "$TARGET is offline"
fi
# loop: sweep a range
for ip in $(seq 1 10); do
ping -c 1 192.168.1.$ip &>/dev/null && echo "192.168.1.$ip alive"
done
Key concepts: variables ($VAR), conditionals (if), loops (for/while), redirection (>, >>, 2>) and &&/||.
You will read scripts all the time, both legitimate administration scripts and malware. Knowing Bash lets you understand what a script does before running it (crucial when analyzing a suspicious curl | bash) and automate SOC tasks. grep, awk, sed, cut, sort, uniq are your allies for crunching logs.
Part 2: Windows
The world's corporate fleet is predominantly Windows, and its heart is Active Directory. For cyber in an enterprise environment, mastering AD is not optional.
2.1 Active Directory (AD): the backbone of the enterprise
Instead of every computer having its own list of users and passwords (chaos!), there is a central records office that knows who each employee is, which department they belong to, what they are allowed to do, and that authenticates everyone. That records office is AD, and it runs on a server called the Domain Controller (DC).
Forest ← largest container
└── Domain: empresa.local ← administration/security unit
├── Organizational Units (OU) ← "folders" for organizing
├── Users / Groups / Computers
Extremely powerful groups: Domain Admins, Enterprise Admins, Administrators.
In pentest/red team engagements, the goal is almost always "Domain Admin": full control of the domain. The entire field of AD security revolves around how the attacker enumerates AD, escalates privileges and reaches the DC, and how the defender detects and stops it. Privileged groups should have the fewest possible members and be closely monitored.
2.2 DNS in the Windows environment
AD depends heavily on DNS. Clients find the DC through special DNS records (SRV records). Without DNS, AD collapses. That is why, in a Windows environment, the DC is usually also the DNS server.
Internal DNS maps the entire network (server names, DCs, services), so it is a reconnaissance goldmine for the attacker. AD-specific attacks (LLMNR/NBT-NS poisoning) exploit how Windows resolves names when DNS fails: the attacker answers in its place and captures credentials.
2.3 GPO: Group Policy Objects
This is how the admin applies settings and rules at scale, from a single place. "All PCs will have wallpaper X, a 12-character minimum password, USB blocked." The admin writes it once (the GPO), links it to an OU, and it applies to everything in there. Examples: password policy, account lockout, software restrictions, drive mappings, logon scripts.
GPO is a double-edged sword. Used well, it is hardening at scale. But if an attacker modifies a GPO, they can push malware to the entire network at once: one of the most devastating attacks in AD. Auditing who can edit GPOs and monitoring changes is essential.
2.4 Authentication: Kerberos and NTLM
Kerberos (modern). Amusement park analogy: you arrive at the ticket office (the DC), show your ID and receive a master wristband (TGT: Ticket Granting Ticket). To get on each ride (service), you show the wristband and receive a specific ticket (TGS). You never present your password again, only the tickets. Flow: login → request a TGT from the KDC (on the DC) → the KDC issues the TGT → present the TGT and request a TGS for the service → present the TGS to the service → access.
NTLM (legacy). Challenge-response using the password hash. Weaker, but still around for compatibility. This is where Pass-the-Hash lives: the hash alone is enough, no plaintext password needed.
Pass-the-Hash: authenticate with a stolen NTLM hash. Pass-the-Ticket: steal and reuse Kerberos tickets. Kerberoasting: request TGS tickets for service accounts and crack them offline (weak passwords that never expire). Golden Ticket: with the krbtgt account's key, forge valid TGTs for any user: near-absolute control. Defense: disable NTLM where possible, strong passwords on service accounts, monitor anomalous ticket requests and protect krbtgt.
2.5 PowerShell: Windows' power terminal
It is the Bash of Windows, object-oriented. The most powerful administration tool on the platform, and the most powerful attack tool too. Cmdlets follow the Verb-Noun format:
Get-Process # list processes (equivalent to ps)
Get-Service # list services
Get-NetTCPConnection # network connections (equivalent to netstat)
Get-LocalUser # local users
Get-EventLog -LogName Security -Newest 20
Get-ScheduledTask # scheduled tasks
# AD queries:
Get-ADUser -Filter * # all users in the domain
Get-ADGroupMember "Domain Admins" # who is a domain admin
Attackers love PowerShell: native, powerful and runs in memory (fileless, never touches the disk, hard for traditional AV to detect). Entire offensive frameworks are written in it. The defensive answer is advanced logging: Script Block Logging and Module Logging record what was executed, even when obfuscated. Monitoring suspicious commands (payload downloads, Base64 -EncodedCommand, Invoke-Expression) is one of the most valuable detections on Windows.
2.6 Services on Windows
Get-Service # PowerShell
sc query # classic command prompt
sc qc nome_do_servico # a service's config (which binary it runs)
Services are a persistence and escalation vector (like systemd on Linux). Classic flaws: unquoted service path (a path without quotes, which lets you plant an executable partway along the path) and weak service permissions (a regular user can modify the binary that runs as SYSTEM). Investigation: recently created services, services with names that mimic legitimate ones, or services pointing to binaries in suspicious folders.
2.7 Windows Registry
The central configuration database of Windows, organized into hives and keys.
| Hive | Abbr. | Contents |
|---|---|---|
| HKEY_LOCAL_MACHINE | HKLM | System settings (the whole machine) |
| HKEY_CURRENT_USER | HKCU | Settings for the logged-on user |
| HKEY_CLASSES_ROOT | HKCR | File associations |
| HKEY_USERS | HKU | All user profiles |
Access it with: regedit (graphical) or reg query.
The Registry is a persistence paradise on Windows. The autostart keys ("Run keys") make programs start at logon:
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunMalware adds an entry there to come back to life at every login. Tools like Autoruns (Sysinternals) list everything that starts automatically: one of the first steps when hunting for persistence.
2.8 Event Viewer: the Windows logs
The most important logs: Security (authentication, logons, privileges: the most important one), System (services, drivers) and Application. Every event has an Event ID:
| Event ID | Log | Meaning |
|---|---|---|
| 4624 | Security | Successful logon |
| 4625 | Security | Failed logon (brute force when in bulk) |
| 4634 / 4647 | Security | Logoff |
| 4672 | Security | Logon with special privileges (admin) |
| 4688 | Security | New process created |
| 4720 | Security | User account created |
| 4732 / 4728 | Security | User added to a privileged group |
| 7045 | System | New service installed (persistence!) |
| 1102 | Security | Audit log was cleared |
Get-WinEvent -LogName Security -MaxEvents 50
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625} # failures only
Mastering Event IDs turns a pile of logs into a story. Many 4625 events followed by a 4624 = a brute force that succeeded. A 4720 outside the normal process = an attacker establishing persistence. A 1102 = someone covering their tracks. The logon type ("Logon Type") also matters: type 3 (network), 10 (RDP) reveal how someone got in.
Part 3: Investigation (where the two worlds meet)
Given a possibly compromised system (Linux or Windows), what do you look at? The logic is the same; only the tools change.
3.1 Investigating suspicious processes
What to look for: a process with an odd name or one that mimics a legitimate one (svch0st.exe, scvhost.exe), running from an unusual location (/tmp, C:\Users\Public, %TEMP%), an anomalous parent-child relationship (Word spawning PowerShell; nginx spawning bash), a deleted binary still running, abnormal CPU/network usage.
# LINUX
ps auxf # process tree
ls -l /proc/<PID>/exe # actual binary (detects "(deleted)")
lsof -p <PID> # open files and connections
# WINDOWS
Get-Process | Sort-Object CPU -Descending
Get-CimInstance Win32_Process | Select ProcessId, ParentProcessId, CommandLine
# Or Process Explorer (Sysinternals)
3.2 Investigating network connections
What to look for: outbound connections to unknown IPs, unusual listening ports, and which process owns each connection.
# LINUX
ss -tulpn # listening ports + process
ss -tanp # all TCP connections + process
lsof -i # open network files
# WINDOWS
Get-NetTCPConnection -State Established
netstat -anob # connections + process (requires admin)
Correlate: "this odd process has an established connection to an IP in Russia on port 4444" → suspicious process + suspicious connection = likely C2.
3.3 Investigating scheduled tasks
# LINUX
crontab -l ; cat /etc/crontab ; ls -la /etc/cron.*
systemctl list-timers # systemd timers
# WINDOWS
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"}
Get-ScheduledTask | Get-ScheduledTaskInfo # last/next run
3.4 Hunting persistence mechanisms
Persistence = how the attacker makes sure they come back even after a reboot. The mental checklist:
On Linux: cron (per user, /etc/cron*), systemd timers, new/suspicious services, keys in ~/.ssh/authorized_keys, profile files (~/.bashrc, ~/.profile, /etc/profile) with injected commands, new SUID binaries, improper UID 0 accounts, suspicious kernel modules (rootkits).
On Windows: Run keys in the Registry, scheduled tasks, recently created services (Event 7045), the Startup folder (shell:startup), WMI event subscriptions, new accounts or accounts added to admin groups (Event 4720/4732), and Autoruns to sweep everything at once.
The attacker needs to execute code (processes), maintain access (persistence), talk to the C2 (connections) and stay unseen (logs). Every investigation is a search for the footprints of these needs: where they are running, how they come back after a reboot, how they talk to the C2 and what they tried to erase.
Linux: /etc (config/credentials), /var/log (what happened), /tmp (where malware hides). rwx permissions, octal (7=rwx), SUID = escalation. /etc/passwd (users), /etc/shadow (hashes), UID 0 = root. Processes: ps aux, /proc/PID, anomalous parent-child = suspicious. Persistence: cron, systemd, authorized_keys, .bashrc. Logs: auth.log, journalctl.
Windows: AD = central records office; DC = ultimate target; Domain Admins = the attacker's goal. Authentication: Kerberos (TGT/TGS), NTLM (Pass-the-Hash). PowerShell = full power (and fileless); enable Script Block Logging. Registry: Run keys = classic persistence. Event Viewer: 4625 (failure), 4624 (success), 4720 (account created), 7045 (new service), 1102 (log cleared).
Investigation (both): processes → connections → scheduled tasks → persistence → tampered logs. Know what normal looks like so you can recognize the abnormal.
Spin up two VMs: one Linux (Ubuntu/Debian) and one Windows (Server with AD, if you can). On Linux, create a harmless "malicious" cron job (an echo every minute) and then find it purely by investigating, as if you didn't know it existed. On Windows, add an entry to a Run key and locate it with Autoruns. Playing attacker and then defender in the same lab is the fastest way to make this stick.