Study guide

Cybersecurity for developers, where to start.

The map of the field, the concepts that matter, a five-stage study path, portfolio projects and where to learn, written for people who already program.

Antes de começar: o mapaBefore you start: the map

Cibersegurança parece um território único, mas é um conjunto de ofícios com perguntas diferentes: como eu quebro isto? (red team), como eu percebo que quebraram? (blue team) e como eu construo de um jeito que seja difícil de quebrar? (segurança de aplicações). Quem já programa começa com uma vantagem real: entende como o software é montado, onde as suposições escondem falhas e como um deploy funciona. Esta nota é o ponto de entrada da série de segurança do site: o mapa, os conceitos, uma trilha de estudo, projetos para o portfólio e onde aprender.Cybersecurity looks like one territory, but it is a set of crafts that ask different questions: how do I break this? (red team), how do I notice someone broke it? (blue team) and how do I build it so it is hard to break? (application security). Anyone who already programs starts with a real advantage: you understand how software is assembled, where assumptions hide flaws and how a deploy works. This note is the entry point to the site's security series: the map, the concepts, a study path, portfolio projects and where to learn.

Red teamRed team atacar para provarattack to prove Purple teamPurple team compartilhar o que aprendeushare what was learned Blue teamBlue team detectar e responderdetect and respond AppSec · DevSecOps · segurança em nuvem: construir seguro desde o início (onde o dev entra)AppSec · DevSecOps · cloud security: build it secure from the start (where the developer enters) Os três de cima descobrem e corrigem; o de baixo evita que o problema nasça.The top three find and fix; the bottom one stops the problem being born.
Red e blue se encontram no purple team; a base de AppSec e DevSecOps reduz o trabalho dos dois.Red and blue meet in purple; the AppSec and DevSecOps base reduces the work of both.

O que você já sabe e vira segurançaWhat you already know that turns into security

Habilidade de devDeveloper skillVira, em segurança…Becomes, in security…
code reviewcode reviewrevisão de código seguro: procurar entrada não confiável chegando a uma consulta, a um comando ou ao HTMLsecure code review: looking for untrusted input reaching a query, a command or the HTML
testes automatizadosautomated teststestes de segurança e fuzzing: o caso de teste é a entrada hostilsecurity tests and fuzzing: the test case is the hostile input
CI/CDCI/CDDevSecOps: varredura de segredos, dependências e código a cada pushDevSecOps: scanning for secrets, dependencies and code on every push
logs e observabilidadelogs and observabilitydetecção: o mesmo log que depura um bug mostra um ataque, se alguém olhardetection: the same log that debugs a bug shows an attack, if someone looks
post-mortem de incidenteincident post-mortemresposta a incidentes: linha do tempo, causa raiz e correção sem culpaincident response: timeline, root cause and a blameless fix
Infraestrutura como códigoInfrastructure as codesegurança em nuvem: IAM de menor privilégio e configuração revisável em pull requestcloud security: least-privilege IAM and configuration reviewable in a pull request
Regra de ouro de toda a série: só pratique em sistemas seus (sua máquina, seu laboratório Docker, sua conta de nuvem) ou em alvos que autorizam o teste por escrito (plataformas de treino, CTFs, programas de bug bounty dentro do escopo). A mesma técnica que é um exercício hoje é crime sem autorização. A seção de ética e lei, mais abaixo, detalha isso.Golden rule of the whole series: only practise on systems that are yours (your machine, your Docker lab, your cloud account) or on targets that authorise testing in writing (training platforms, CTFs, bug bounty programmes within scope). The same technique that is an exercise today is a crime without authorisation. The ethics and law section below goes into detail.

Os conceitos que sustentam tudoThe concepts that hold everything up

Antes de ferramenta, vocabulário. Estes onze conceitos aparecem em toda prova de certificação, toda entrevista e todo relatório de incidente. Se você dominar só isto, já lê o resto da área com sentido.Vocabulary comes before tools. These eleven concepts show up in every certification exam, every interview and every incident report. Master only these and you can already read the rest of the field with understanding.

ConceitoConceptEm uma fraseIn one sentenceOnde praticar nesta sérieWhere to practise in this series
Tríade CIACIA triadConfidencialidade (só quem pode lê), integridade (ninguém altera sem querer ou sem permissão) e disponibilidade (funciona quando precisa): todo controle protege uma dessas três.Confidentiality (only those allowed can read), integrity (nobody alters it by accident or without permission) and availability (it works when needed): every control protects one of these three.Aplicações web segurasSecure web apps
Ameaça, vulnerabilidade, riscoThreat, vulnerability, riskA ameaça é quem ou o que pode causar dano, a vulnerabilidade é a fraqueza que permite, o risco é a probabilidade vezes o impacto.The threat is who or what can cause harm, the vulnerability is the weakness that allows it, the risk is probability times impact.Red team 80/20Red team 80/20
Superfície de ataqueAttack surfaceTudo o que um atacante consegue tocar: portas abertas, endpoints, contas, dependências. Reduzir isso é a defesa mais barata.Everything an attacker can touch: open ports, endpoints, accounts, dependencies. Shrinking it is the cheapest defence.Segurança e redes (nmap, firewall)Security and networking (nmap, firewall)
Menor privilégioLeast privilegeCada pessoa, processo e token recebe só a permissão de que precisa, pelo tempo de que precisa.Every person, process and token gets only the permission it needs, for as long as it needs.Postgres (roles e grants)Postgres (roles and grants)
Defesa em profundidadeDefence in depthCamadas independentes: se uma falha, a próxima segura. Firewall, autenticação, validação, criptografia e monitoramento juntos.Independent layers: if one fails, the next holds. Firewall, authentication, validation, encryption and monitoring together.Segurança e redesSecurity and networking
Autenticação e autorizaçãoAuthentication and authorisationAutenticar é provar quem você é; autorizar é decidir o que você pode fazer. Confundir as duas é a origem de metade das falhas de acesso. MFA reforça a primeira.Authenticating is proving who you are; authorising is deciding what you may do. Mixing them up is the root of half of all access flaws. MFA strengthens the first.Aplicações web seguras (sessões, JWT)Secure web apps (sessions, JWT)
Criptografia aplicadaApplied cryptographyHash para senhas (lento e com sal), cifra simétrica para dados, assimétrica para trocar chaves e assinar, TLS para o tráfego. Nunca invente a sua.Hashing for passwords (slow and salted), symmetric ciphers for data, asymmetric for exchanging keys and signing, TLS for traffic. Never invent your own.HTTPS e cabeçalhosHTTPS and headers
Modelagem de ameaçasThreat modellingDesenhar o sistema e perguntar, para cada fluxo, o que pode dar errado (veja o STRIDE abaixo) antes de escrever o código.Drawing the system and asking, for each flow, what can go wrong (see STRIDE below) before writing the code.Projeto 4 desta notaProject 4 in this note
Gestão de vulnerabilidadesVulnerability managementAchar, priorizar e corrigir falhas conhecidas (CVE, CVSS) em dependências, imagens e servidores, de forma contínua.Finding, prioritising and fixing known flaws (CVE, CVSS) in dependencies, images and servers, continuously.Projetos 1 e 2 desta notaProjects 1 and 2 in this note
Supor a invasão (assume breach)Assume breachProjete como se alguém já estivesse dentro: segmente, limite o que sai da rede, registre tudo e tenha um plano de resposta.Design as if someone were already inside: segment, limit what leaves the network, log everything and have a response plan.Red team 80/20 (seção do shell)Red team 80/20 (shell section)
Zero trustZero trustNenhuma requisição é confiável só por vir da rede interna: cada acesso é verificado por identidade, dispositivo e contexto.No request is trusted just for coming from the internal network: every access is verified by identity, device and context.GitHub para AWS com OIDC (sem chaves fixas)GitHub to AWS with OIDC (no static keys)

STRIDE: seis perguntas para modelar ameaçasSTRIDE: six questions for threat modelling

LetraLetterAmeaçaThreatPerguntaQuestionPropriedade violadaProperty violated
SSpoofingalguém consegue se passar por outro usuário ou serviço?can someone pose as another user or service?autenticidadeauthenticity
TTamperingalguém consegue alterar dados em trânsito ou em repouso?can someone change data in transit or at rest?integridadeintegrity
RRepudiationalguém consegue negar uma ação sem que haja prova?can someone deny an action with no proof?não repúdio (logs)non-repudiation (logs)
IInformation disclosurealgum dado vaza para quem não devia ver?does any data leak to someone who should not see it?confidencialidadeconfidentiality
DDenial of servicealguém consegue derrubar ou esgotar o serviço?can someone take down or exhaust the service?disponibilidadeavailability
EElevation of privilegeum usuário comum consegue virar administrador?can an ordinary user become an admin?autorizaçãoauthorisation

Cinco siglas que organizam o vocabulárioFive acronyms that organise the vocabulary

SiglaAcronymO que identificaWhat it identifiesExemploExample
CVEuma vulnerabilidade específica e pública, com um númeroone specific, public vulnerability, with a numberCVE-2021-44228 (Log4Shell)
CWEa classe de fraqueza por trás de muitos CVEsthe class of weakness behind many CVEsCWE-89 (SQL injection)
CVSSa gravidade de 0 a 10 de uma vulnerabilidadethe 0-to-10 severity of a vulnerability9.8 = crítico9.8 = critical
MITRE ATT&CKo catálogo de táticas e técnicas de atacantes, usado por red e bluethe catalogue of attacker tactics and techniques, used by red and blueT1190 (Exploit Public-Facing Application)
OWASP Top 10os riscos mais comuns em aplicações web, para quem constróithe most common web application risks, for buildersA01 Broken Access Control

Os caminhos: red, blue, purple e AppSecThe paths: red, blue, purple and AppSec

CaminhoPathPergunta centralCore questionDia a diaDay to dayPrimeiros passosFirst steps
AppSec / DevSecOpsAppSec / DevSecOpscomo eu construo isto sem as falhas comuns?how do I build this without the common flaws?revisão de código, threat modeling, SAST/DAST, pipelines seguros, treinar devscode review, threat modelling, SAST/DAST, secure pipelines, training developersAplicações web segurasAplicações web seguras · PortSwigger Web Security Academy · Juice Shop
Red team / pentestRed team / pentestcomo um atacante chegaria aqui?how would an attacker get here?testes autorizados, relatórios com evidência e correção sugeridaauthorised testing, reports with evidence and a suggested fixRed team 80/20Red team 80/20 · TryHackMe · Hack The Box Academy
Blue team / SOCBlue team / SOCestamos sendo atacados agora? o que aconteceu?are we being attacked right now? what happened?triagem de alertas, caça a ameaças, resposta a incidentes, engenharia de detecçãoalert triage, threat hunting, incident response, detection engineeringSegurança e redesSegurança e redes · CyberDefenders · LetsDefend · Projeto 3Project 3
Purple teamPurple teama detecção pega o que o ataque faz?does detection catch what the attack does?rodar uma técnica do ATT&CK e conferir se o alerta dispara; ajustar as regrasrunning an ATT&CK technique and checking whether the alert fires; tuning the rulesProjetos 3 e 5 (Sigma + Atomic Red Team)Projects 3 and 5 (Sigma + Atomic Red Team)
Cloud securityCloud securityesta conta de nuvem está configurada com segurança?is this cloud account configured securely?IAM, rede, segredos, logs de auditoria, políticas como códigoIAM, networking, secrets, audit logs, policy as codeGitHub para AWS com OIDCGitHub para AWS com OIDC · AWSAWS

Como um dev deve escolherHow a developer should choose

Comece por AppSec: é onde o que você já sabe rende mais rápido, a nota de aplicações web seguras já cobre a base e o mercado sempre precisa de quem fale as duas línguas, a do código e a da segurança. Em paralelo, faça a trilha ofensiva em laboratório para entender o atacante, e a defensiva para entender o que ele deixa nos logs. Depois de uns seis meses você saberá se prefere quebrar (red), investigar (blue) ou construir (AppSec/cloud). Ninguém acerta de primeira, e as bases são as mesmas.Start with AppSec: it is where what you already know pays off fastest, the secure web apps note already covers the base and the market always needs people who speak both languages, code and security. In parallel, do the offensive path in a lab to understand the attacker, and the defensive one to understand what the attacker leaves in the logs. After about six months you will know whether you prefer to break (red), investigate (blue) or build (AppSec/cloud). Nobody gets it right the first time, and the foundations are the same.

O lado blue em uma páginaThe blue side on one page

As notas existentes são fortes no lado ofensivo e no de quem constrói; o lado de quem detecta cabe aqui, em resumo. O ciclo de resposta a incidentes do NIST (SP 800-61) tem quatro fases, e cada uma tem uma ferramenta típica.The existing notes are strong on the offensive side and on the builder's side; the side of those who detect fits here, in summary. The NIST incident response lifecycle (SP 800-61) has four phases, and each has a typical tool.

FasePhaseO que aconteceWhat happensFerramenta típicaTypical tool
PreparaçãoPreparationinventário, logs centralizados, backups testados, plano e contatos de respostainventory, centralised logs, tested backups, response plan and contactsWazuh, Elastic, auditd, CloudTrailWazuh, Elastic, auditd, CloudTrail
Detecção e análiseDetection and analysisum alerta dispara; o analista confirma se é real e qual o alcancean alert fires; the analyst confirms whether it is real and how far it reachesSuricata (rede), regras Sigma (logs), EDRSuricata (network), Sigma rules (logs), EDR
Contenção, erradicação e recuperaçãoContainment, eradication and recoveryisolar o host, revogar credenciais, remover a persistência, restaurar de backupisolate the host, revoke credentials, remove persistence, restore from backupfirewall, IAM, snapshots, backups 3-2-1firewall, IAM, snapshots, 3-2-1 backups
Pós-incidentePost-incidentlinha do tempo, causa raiz, o que muda para não repetirtimeline, root cause, what changes so it does not repeatpost-mortem sem culpa, ATT&CK para classificarblameless post-mortem, ATT&CK to classify

A trilha em cinco etapasThe path in five stages

0 · Fundamentos0 · Foundations 1 · Apps1 · Apps 2 · Ofensiva2 · Offence 3 · Defesa3 · Defence 4 · Provar4 · Prove it
Cada etapa tem um marco de saída: só avance quando conseguir fazê-lo sem consultar.Each stage has an exit milestone: only move on when you can do it without looking it up.
EtapaStageAprenderLearnNesta sérieIn this seriesFora daquiBeyond this siteMarco de saídaExit milestone
0 · Fundamentos
4 a 6 semanas
0 · Foundations
4 to 6 weeks
TCP/IP, DNS, HTTP, TLS; Linux e shell; um idioma de script (Python ou Bash); GitTCP/IP, DNS, HTTP, TLS; Linux and the shell; a scripting language (Python or Bash); GitComo o Linux funcionaHow Linux works
Segurança e redesSecurity and networking lab
OverTheWire Bandit
Professor Messer, Security+
roadmap.sh/cyber-security
explicar um handshake TCP, ler uma captura no Wireshark e prender um serviço atrás de um firewallexplain a TCP handshake, read a Wireshark capture and put a service behind a firewall
1 · Segurança de aplicações
6 a 8 semanas
1 · Application security
6 to 8 weeks
OWASP Top 10, autenticação e sessão, cabeçalhos, injeção, XSS, CSRF, gestão de segredos e dependênciasOWASP Top 10, authentication and sessions, headers, injection, XSS, CSRF, secrets and dependency managementAplicações web segurasSecure web apps
Postgres para quem programaPostgres for developers
PortSwigger Web Security Academy
OWASP Juice Shop
OWASP Cheat Sheet Series
corrigir uma injeção e um XSS no seu próprio código e provar com um testefix an injection and an XSS in your own code and prove it with a test
2 · Ofensiva em laboratório
6 a 8 semanas
2 · Offence in a lab
6 to 8 weeks
o ciclo de ataque, reconhecimento, exploração web, shells, escalada de privilégio, relatóriothe attack lifecycle, recon, web exploitation, shells, privilege escalation, reportingRed team 80/20Red team 80/20TryHackMe
Hack The Box Academy
picoCTF
resolver uma máquina fácil de ponta a ponta e escrever o relatório com a correçãosolve an easy machine end to end and write the report with the fix
3 · Defesa e detecção
6 a 8 semanas
3 · Defence and detection
6 to 8 weeks
logs, SIEM, IDS, resposta a incidentes, regras de detecção, ATT&CK do lado de quem defendelogs, SIEM, IDS, incident response, detection rules, ATT&CK from the defender's sideRed team 80/20 (o que o blue vê)Red team 80/20 (what blue sees)
Projetos 3 e 5Projects 3 and 5
CyberDefenders
LetsDefend
Blue Team Labs Online
ver o seu próprio ataque de laboratório aparecer num alerta e escrever a regra que o pegasee your own lab attack show up in an alert and write the rule that catches it
4 · Especializar e provar
contínuo
4 · Specialise and prove it
ongoing
nuvem, mobile, reversing, forense ou GRC; certificação; contribuição públicacloud, mobile, reversing, forensics or GRC; certification; public contributionAWSAWS
Terraform 80/20Terraform 80/20
CTFtime
HackerOne
Root-Me
um portfólio público (write-ups, regras, ferramentas) e uma certificação da sua áreaa public portfolio (write-ups, rules, tools) and one certification in your area

Projetos práticos para o portfólioPractical projects for your portfolio

Certificado diz que você estudou; projeto público mostra que você faz. Cada projeto abaixo gera um artefato que cabe num repositório ou num post: um relatório, uma regra, um pipeline. Todos rodam na sua máquina ou em contêineres.A certificate says you studied; a public project shows you can do it. Each project below produces an artefact that fits in a repository or a post: a report, a rule, a pipeline. All of them run on your machine or in containers.

##ProjetoProjectO que você entregaWhat you deliverNívelLevelEtapaStage
1Auditar e endurecer o seu próprio appAudit and harden your own apprelatório com achados priorizados (CVSS) e os commits que corrigemreport with prioritised findings (CVSS) and the commits that fix theminiciantebeginner1
2Pipeline de segurança no CISecurity pipeline in CIworkflow que falha o build com segredo ou CVE críticoa workflow that fails the build on a secret or a critical CVEiniciantebeginner1
3Mini SOC domésticoHome mini-SOCalertas do Suricata e do Wazuh para ataques que você mesmo rodouSuricata and Wazuh alerts for attacks you ran yourselfintermediáriointermediate3
4Modelo de ameaças de um sistemaThreat model of a systemdiagrama de fluxo de dados e tabela STRIDE com mitigaçõesdata flow diagram and STRIDE table with mitigationsiniciantebeginner1
5Regra de detecção em SigmaDetection rule in Sigmaregra versionada, testada contra o ataque do laboratórioa versioned rule, tested against the lab attackintermediáriointermediate3
6Write-ups de laboratóriosLab write-ups10 desafios do Juice Shop ou da PortSwigger explicados passo a passo10 Juice Shop or PortSwigger challenges explained step by stepiniciantebeginner2
7Honeypot SSH isoladoIsolated SSH honeypotuma semana de tentativas reais analisadas (IPs, senhas, comandos)a week of real attempts analysed (IPs, passwords, commands)intermediáriointermediate3
8CTF em equipe ou programa de divulgaçãoTeam CTF or disclosure programmeparticipação no CTFtime e um relato do que você aprendeua CTFtime entry and an account of what you learnedtodos os níveisall levels4

Projeto 1: auditar e endurecer o seu próprio appProject 1: audit and harden your own app

Pegue um projeto seu (qualquer um) e rode três varreduras: segredos, dependências e padrões de código inseguro. Priorize o que achar por gravidade, corrija o que for crítico e registre cada correção num commit com a explicação do risco. Em seguida revise cabeçalhos e cookies com o checklist da nota de aplicações web seguras.Take one of your projects (any of them) and run three scans: secrets, dependencies and insecure code patterns. Prioritise what you find by severity, fix what is critical and record each fix in a commit that explains the risk. Then review headers and cookies with the checklist in the secure web apps note.

# dentro da pasta do seu projeto: três varreduras, nenhuma sai da sua máquina
docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest detect --source /repo --redact
# ^ segredos no código e no histórico do Git
docker run --rm -v "$PWD:/src" aquasec/trivy:latest fs /src
# ^ dependências com CVE, Dockerfile e IaC mal configurados
docker run --rm -v "$PWD:/src" semgrep/semgrep semgrep scan --config auto --metrics=off /src
# ^ padrões de código inseguro (injeção, criptografia fraca, XSS)

Resultado esperado: uma lista de achados, quase sempre com falsos positivos. Aprender a separá-los é metade do ofício: para cada item, escreva "real" ou "falso positivo, porque…". Se o gitleaks achar um segredo real, revogue-o primeiro e só depois limpe o histórico: um segredo que já foi para o Git deve ser tratado como vazado.Expected result: a list of findings, almost always with false positives. Learning to tell them apart is half the craft: for each item write "real" or "false positive, because…". If gitleaks finds a real secret, revoke it first and only then clean the history: a secret that reached Git must be treated as leaked.

Projeto 2: o mesmo, a cada pushProject 2: the same, on every push

Transforme as varreduras do projeto 1 num workflow do GitHub Actions. O objetivo é que um segredo ou uma dependência com CVE crítico quebre o build antes de chegar à produção. Ative também o Dependabot e o secret scanning do repositório (Settings → Code security).Turn the scans from project 1 into a GitHub Actions workflow. The goal is that a secret or a dependency with a critical CVE breaks the build before it reaches production. Also turn on Dependabot and the repository's secret scanning (Settings → Code security).

# .github/workflows/security.yml (esqueleto; fixe versões e SHAs dos actions que você usar)
name: security
on: [push, pull_request]
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }   # gitleaks lê o histórico inteiro
      - name: segredos
        run: docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest detect --source /repo --redact
      - name: dependências e arquivos de configuração
        run: docker run --rm -v "$PWD:/src" aquasec/trivy:latest fs --exit-code 1 --severity HIGH,CRITICAL /src

Resultado esperado: um push com um arquivo .env falso (use um valor inventado) deixa o job vermelho. Teste isso de propósito, em um branch, para ter certeza de que o pipeline realmente barra. Veja também a nota de OIDC: o pipeline não deve ter chaves de nuvem fixas.Expected result: a push with a fake .env file (use an invented value) turns the job red. Test it on purpose, on a branch, to be sure the pipeline really blocks. See also the OIDC note: the pipeline must not hold static cloud keys.

Projeto 3: um mini SOC domésticoProject 3: a home mini-SOC

Aqui o lado blue se encontra com o laboratório da nota de red team. Primeiro, o jeito mais simples: gere tráfego de ataque (um scan com o nmap e uma SQL injection no DVWA), capture com o tcpdump e peça ao Suricata, um IDS de código aberto, que leia a captura.Here the blue side meets the lab from the red team note. First, the simplest way: generate attack traffic (an nmap scan and a SQL injection on DVWA), capture it with tcpdump and ask Suricata, an open-source IDS, to read the capture.

# 1. capture tráfego do laboratório (o mesmo da nota de segurança e redes)
sudo tcpdump -i any -n -w lab.pcap port 80 or port 8081 -c 2000
# 2. rode um ataque conhecido contra o DVWA: um scan com nmap e uma SQL injection
# 3. leia a captura com o Suricata e as regras Emerging Threats (gratuitas)
mkdir -p suricata-out && sudo suricata-update          # baixa o conjunto de regras
suricata -r lab.pcap -l suricata-out
cat suricata-out/fast.log                              # os alertas, uma linha cada

Resultado esperado: o fast.log lista alertas como o do scan de portas e de tentativas de injeção. Anote quais ataques foram vistos e quais passaram em silêncio: os que passaram são o seu trabalho de detecção. Depois suba o Wazuh (SIEM e agente de host) seguindo o guia oficial de implantação com Docker e instale o agente na máquina que hospeda o laboratório; compare o que cada ferramenta enxerga.Expected result: fast.log lists alerts such as the port scan and the injection attempts. Note which attacks were seen and which slipped past silently: the ones that slipped past are your detection work. Then bring up Wazuh (SIEM and host agent) following the official Docker deployment guide and install the agent on the machine hosting the lab; compare what each tool sees.

Projeto 5: uma regra de detecção em SigmaProject 5: a detection rule in Sigma

Sigma é um formato aberto e neutro de regras de detecção: você escreve uma vez e converte para o SIEM que usar. A regra abaixo traduz em código a defesa da nota de red team: um processo de servidor web não deveria gerar um shell filho. Teste rodando o exercício do shell reverso do laboratório e conferindo se a regra, convertida, dispara no seu Wazuh ou Elastic.Sigma is an open, vendor-neutral format for detection rules: you write it once and convert it for whichever SIEM you use. The rule below turns the defence from the red team note into code: a web server process should not spawn a child shell. Test it by running the reverse shell exercise from the lab and checking that the converted rule fires in your Wazuh or Elastic.

# web-shell.yml: um servidor web não deveria abrir um shell (o padrão da nota de red team)
title: Web server spawning a shell
id: 1dca4040-3843-4463-a982-c8a755bbeddc
status: experimental
description: A web server process starting a shell, a common sign of a reverse shell
logsource:
  category: process_creation
  product: linux
detection:
  selection:
    ParentImage|endswith: ['/nginx', '/apache2', '/httpd', '/php-fpm']
    Image|endswith: ['/bash', '/sh', '/dash']
  condition: selection
falsepositives:
  - Deploy scripts started by the web server
level: high

Resultado esperado: um arquivo YAML versionado, um teste que o dispara e uma nota sobre falsos positivos. O repositório SigmaHQ/sigma tem milhares de regras para você ler e o atomic-red-team (Red Canary) tem testes de técnicas do ATT&CK para provar cada regra: é o purple team em casa.Expected result: a versioned YAML file, a test that triggers it and a note on false positives. The SigmaHQ/sigma repository has thousands of rules to read and atomic-red-team (Red Canary) has ATT&CK technique tests to prove each rule: purple team at home.

Projetos 4, 6, 7 e 8, em poucas linhasProjects 4, 6, 7 and 8, in a few lines

  • Modelo de ameaças: desenhe o diagrama de fluxo de dados do sistema (usuário, front, API, banco, filas, terceiros), marque as fronteiras de confiança e percorra cada fluxo com o STRIDE. O OWASP Threat Dragon é uma ferramenta gratuita para isso. Entregue o diagrama e uma tabela "ameaça, mitigação, status".Threat model: draw the system's data flow diagram (user, front end, API, database, queues, third parties), mark the trust boundaries and walk each flow with STRIDE. OWASP Threat Dragon is a free tool for it. Deliver the diagram and a "threat, mitigation, status" table.
  • Write-ups: resolva desafios do Juice Shop e da Web Security Academy da PortSwigger e explique, para cada um, a falha, como você a encontrou e a correção. Escrever é o que transforma exercício em portfólio (e em memória).Write-ups: solve Juice Shop and PortSwigger Web Security Academy challenges and explain, for each, the flaw, how you found it and the fix. Writing is what turns an exercise into a portfolio (and into memory).
  • Honeypot: o Cowrie simula um servidor SSH e registra o que os bots tentam. Rode-o isolado (contêiner, VPS descartável, sem credenciais reais e sem rota para a sua rede) e analise os logs. Só publique algo assim com o isolamento bem pensado.Honeypot: Cowrie simulates an SSH server and records what bots try. Run it isolated (container, disposable VPS, no real credentials and no route to your network) and analyse the logs. Only expose something like this with the isolation well thought through.
  • CTF e divulgação: jogue um CTF por mês (picoCTF é o melhor começo). Quando se sentir pronto, procure programas de divulgação de vulnerabilidades (VDP) e bug bounty, sempre dentro do escopo publicado.CTF and disclosure: play one CTF a month (picoCTF is the best start). When you feel ready, look for vulnerability disclosure programmes (VDP) and bug bounty, always within the published scope.

Onde aprenderWhere to learn

Plataformas práticasHands-on platforms

Aprende-se segurança fazendo. Todas as plataformas abaixo têm trilhas guiadas; as marcadas como "gratuito" não exigem pagamento para o conteúdo principal, e as com "planos pagos" têm uma parte gratuita e outra paga (os preços mudam, confira no site).Security is learned by doing. All the platforms below have guided paths; those marked "free" need no payment for the core content, and those with "paid plans" have a free part and a paid part (prices change, check the site).

PlataformaPlatformFocoFocusCustoCostPara quemBest for
OverTheWire: BanditLinux e shell por meio de jogosLinux and shell through gamesgratuitofreeo primeiro diaday one
picoCTFCTF para iniciantes, da Carnegie Mellonbeginner CTF from Carnegie Mellongratuitofreetreinar jogandolearning by playing
PortSwigger Web Security Academysegurança web em profundidade, com laboratóriosweb security in depth, with labsgratuitofreeo melhor para devsthe best for developers
OWASP Juice Shoploja vulnerável de propósito, com placara deliberately vulnerable shop, with a scoreboardgratuitofreeAppSec práticopractical AppSec
TryHackMetrilhas guiadas, no navegadorguided paths, in the browsergratuito + planos pagosfree + paid plansiniciantes, ofensiva e defesabeginners, offence and defence
Hack The Box Academymódulos aprofundados e máquinasin-depth modules and machinesgratuito + planos pagosfree + paid plansdepois do TryHackMeafter TryHackMe
CyberDefendersinvestigações de blue teamblue team investigationsgratuito + planos pagosfree + paid plansanalistas de SOCSOC analysts
LetsDefendsimulador de SOC com alertasSOC simulator with alertsgratuito + planos pagosfree + paid planstriagem de alertasalert triage
Blue Team Labs Onlineforense e resposta a incidentesforensics and incident responsegratuito + planos pagosfree + paid plansDFIRDFIR
Root-Medesafios em várias áreas (inclui versão em português)challenges in many areas (includes a Portuguese version)gratuitofreevariedadevariety

Referências que valem os favoritosReferences worth bookmarking

LivrosBooks

  • The Web Application Hacker's Handbook (Stuttard e Pinto): o clássico de segurança web, ainda útil nos fundamentos.The Web Application Hacker's Handbook (Stuttard and Pinto): the web security classic, still useful for the fundamentals.
  • Threat Modeling: Designing for Security (Adam Shostack): o livro de referência para o projeto 4.Threat Modeling: Designing for Security (Adam Shostack): the reference book for project 4.
  • Security Engineering (Ross Anderson): por que sistemas reais falham; a obra inteira está disponível online, de graça.Security Engineering (Ross Anderson): why real systems fail; the whole book is available online, free.
  • Linux Basics for Hackers (OccupyTheWeb) e Practical Packet Analysis (Chris Sanders): a base de sistema e rede para a etapa 0.Linux Basics for Hackers (OccupyTheWeb) and Practical Packet Analysis (Chris Sanders): the system and network base for stage 0.

Certificações, na ordem em que fazem sentidoCertifications, in the order they make sense

Certificação não é habilidade: é um filtro de currículo e um roteiro de estudo. Faça uma quando ela te empurrar a estudar o que você evitaria, não como primeiro passo.A certification is not a skill: it is a résumé filter and a study outline. Take one when it pushes you to study what you would otherwise avoid, not as a first step.

CertificaçãoCertificationPara quemFor whomObservaçãoNote
CompTIA Security+base geral, a mais pedida em vagas de entradageneral foundation, the most requested in entry-level jobsconceitos, não prática; combina com a etapa 0concepts, not practice; matches stage 0
eJPT (INE)primeiro teste prático de pentestfirst practical pentest exametapa 2, com laboratóriostage 2, with a lab
BTL1 (Security Blue Team)analista de SOC, práticaSOC analyst, practicaletapa 3stage 3
OSCP (OffSec PEN-200)pentest intermediário, prova de 24 horasintermediate pentest, 24-hour examexige base sólida; reconhecida em ofensivaneeds a solid base; well regarded in offence
AWS Certified Security – Specialtysegurança em nuvemcloud securityfaz par com as notas de AWS e Terraformpairs with the AWS and Terraform notes
CISSP (ISC2)gestão e arquitetura de segurançasecurity management and architectureexige anos de experiência; só mais adianterequires years of experience; only later on

Ética e lei: o que separa estudo de crimeEthics and law: what separates study from crime

A diferença entre um pentester e um criminoso não é a técnica, é a autorização. Antes de testar qualquer coisa, responda por escrito às três perguntas abaixo. Se alguma resposta for "não sei", não teste.The difference between a pentester and a criminal is not the technique, it is authorisation. Before testing anything, answer the three questions below in writing. If any answer is "I don't know", don't test.

  • É meu? Máquina, rede, conta de nuvem e aplicação que você administra e pode quebrar sem prejudicar ninguém.Is it mine? A machine, network, cloud account and application you run and can break without harming anyone.
  • Tenho autorização por escrito? Contrato de pentest, regras de um CTF, política de um programa de bug bounty ou a licença da plataforma de treino.Do I have written authorisation? A pentest contract, the rules of a CTF, a bug bounty programme's policy or the training platform's terms.
  • Qual é o escopo? Quais alvos, quais técnicas e quais horários estão permitidos. Fora do escopo é fora da autorização, mesmo no mesmo domínio.What is the scope? Which targets, techniques and hours are allowed. Outside the scope is outside the authorisation, even on the same domain.

No Brasil, a Lei 12.737/2012 criou o crime de invasão de dispositivo informático (art. 154-A do Código Penal), e a LGPD (Lei 13.709/2018) regula o tratamento de dados pessoais, o que importa se um teste expõe dados reais. Se achar uma falha em um sistema que não é seu, pare, não explore além do mínimo para confirmar, não baixe dados e reporte pelo canal oficial de divulgação (muitas empresas têm um security.txt ou um VDP). Isto é uma orientação geral, não consultoria jurídica.In Brazil, Law 12,737/2012 created the crime of invading a computing device (art. 154-A of the Penal Code), and the LGPD (Law 13,709/2018) regulates the processing of personal data, which matters if a test exposes real data. If you find a flaw in a system that is not yours, stop, do not exploit beyond the minimum needed to confirm, do not download data and report through the official disclosure channel (many companies have a security.txt or a VDP). This is general guidance, not legal advice.

Hábito que vale ouro: mantenha um diário de laboratório com data, alvo, objetivo e resultado de cada exercício. Em uma entrevista, em um relatório ou numa dúvida sobre autorização, esse registro mostra que você trabalha como profissional.A habit worth gold: keep a lab journal with the date, target, goal and result of every exercise. In an interview, in a report or in a doubt about authorisation, that record shows you work like a professional.

Um plano de 90 diasA 90-day plan

Cerca de seis horas por semana, três blocos de duas horas. O plano assume que você já programa e usa o terminal; ajuste o ritmo, mas não pule os marcos.About six hours a week, three two-hour blocks. The plan assumes you already program and use the terminal; adjust the pace, but do not skip the milestones.

SemanasWeeksFocoFocusEntregávelDeliverable
1 a 3Fundamentos: OverTheWire Bandit; nota de Linux; nota de segurança e redes (sessões, nmap, Wireshark)Foundations: OverTheWire Bandit; the Linux note; the security and networking note (sessions, nmap, Wireshark)Bandit até o nível 15; uma captura TCP explicada num post curtoBandit up to level 15; a TCP capture explained in a short post
4 a 6AppSec: nota de aplicações web seguras; 10 laboratórios da Web Security AcademyAppSec: the secure web apps note; 10 Web Security Academy labsprojetos 1 e 2 (auditoria e pipeline) num repositório públicoprojects 1 and 2 (audit and pipeline) in a public repository
7 a 9Ofensiva: nota de red team; Juice Shop; uma trilha do TryHackMeOffence: the red team note; Juice Shop; one TryHackMe pathprojeto 6 (write-ups) com pelo menos 5 desafiosproject 6 (write-ups) with at least 5 challenges
10 a 12Defesa: projetos 3 e 5; duas investigações do CyberDefenders ou LetsDefend; um modelo de ameaçasDefence: projects 3 and 5; two CyberDefenders or LetsDefend investigations; one threat modela regra Sigma, o mini SOC e o modelo de ameaças; decidir o caminho (AppSec, red, blue ou nuvem)the Sigma rule, the mini-SOC and the threat model; decide the path (AppSec, red, blue or cloud)

Cola e revisãoCheat sheet and review

Cola: por onde começar, em uma tabelaCheat sheet: where to start, in one table

Quero…I want…FaçaDo
entender redes e Linuxto understand networks and LinuxNota de LinuxNota de Linux + Segurança e redesSegurança e redes + OverTheWire BanditLinux noteLinux note + Security and networkingSecurity and networking + OverTheWire Bandit
proteger o que eu construoto protect what I buildAplicações web segurasAplicações web seguras + Projetos 1, 2 e 4Secure web appsSecure web apps + Projects 1, 2 and 4
entender o atacanteto understand the attackerRed team 80/20Red team 80/20 + TryHackMe + Juice ShopRed team 80/20Red team 80/20 + TryHackMe + Juice Shop
ver o que o ataque deixa nos logsto see what the attack leaves in the logsProjetos 3 e 5 + CyberDefendersProjects 3 and 5 + CyberDefenders
praticar sem riscoto practise safelysó em alvos seus ou de treino, com o diário de laboratórioonly on targets of your own or training ones, with the lab journal
provar o que seito prove what I knowwrite-ups públicos, CTFs e, depois, uma certificaçãopublic write-ups, CTFs and, later, a certification

Perguntas de revisãoReview questions

PerguntaQuestionRespostaAnswer
Qual a diferença entre ameaça, vulnerabilidade e risco?What is the difference between threat, vulnerability and risk?Ameaça é quem ou o que pode causar dano; vulnerabilidade é a fraqueza que permite; risco é a probabilidade vezes o impacto.Threat is who or what can cause harm; vulnerability is the weakness that allows it; risk is probability times impact.
Para que serve a modelagem de ameaças e quando fazê-la?What is threat modelling for and when should you do it?Achar falhas de projeto antes do código, percorrendo cada fluxo de dados com perguntas como as do STRIDE; quanto mais cedo, mais barato.Finding design flaws before the code, walking each data flow with questions like STRIDE's; the earlier, the cheaper.
Qual a relação entre CVE, CWE e CVSS?How do CVE, CWE and CVSS relate?CVE identifica uma vulnerabilidade específica, CWE a classe de fraqueza por trás dela e CVSS a gravidade de 0 a 10.CVE identifies one specific vulnerability, CWE the class of weakness behind it and CVSS the 0-to-10 severity.
O que diferencia red team, blue team e purple team?What distinguishes red, blue and purple team?Red ataca com autorização, blue detecta e responde, purple faz os dois trabalharem juntos: roda a técnica e confere se o alerta dispara.Red attacks with authorisation, blue detects and responds, purple makes the two work together: runs the technique and checks whether the alert fires.
Por que um dev deve começar por AppSec?Why should a developer start with AppSec?Porque reaproveita o que já sabe (código, testes, CI) e porque cada falha corrigida no projeto evita trabalho de red e de blue depois.Because it reuses what you already know (code, tests, CI) and because each flaw fixed in the design saves red and blue work later.
Por que "supor a invasão" é uma boa premissa de projeto?Why is "assume breach" a good design premise?Porque nenhuma prevenção é perfeita; segmentação, menor privilégio, logs e plano de resposta limitam o dano quando algo passa.Because no prevention is perfect; segmentation, least privilege, logs and a response plan limit the damage when something gets through.
Quais três perguntas responder antes de testar algo?Which three questions must you answer before testing anything?É meu? Tenho autorização por escrito? Qual é o escopo?Is it mine? Do I have written authorisation? What is the scope?