Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.
Práticas de Codificação Segura (Secure Coding Practices)
Segurança não pode ser aparafusada em uma aplicação depois de construída. Deve ser projetada na arquitetura e escrita no código desde a primeira linha. O custo de corrigir uma vulnerabilidade em produção é 6-15x maior do que corrigi-la durante o desenvolvimento.
1. Validação de Entrada (Input Validation)
Nunca confie em dados do usuário, do cliente ou de qualquer sistema externo.
Estratégia
Descrição
Exemplo
Allow-listing (Lista de permissão)
Defina exatamente o que É permitido
Username: ^[a-zA-Z0-9_]{3,20}$
Block-listing (Lista de bloqueio)
Defina o que NÃO é permitido
Bloquear tags <script>
Verificação de tipo
Garanta que o input corresponde ao tipo esperado
Idade deve ser inteiro
Limites de comprimento
Restrinja o tamanho do input
Comentário máx. 5000 chars
Sempre prefira allow-listing a block-listing. Listas de bloqueio são inerentemente incompletas, atacantes constantemente inventam novos truques de codificação e técnicas de ofuscação para evadi-las.
Validação Server-Side vs. Client-Side
Validação client-side (JavaScript no navegador) melhora UX. Não é um controle de segurança. Atacantes a ignoram trivialmente usando DevTools, Burp Suite ou curl.
Validação server-side é obrigatória. Cada input deve ser validado no servidor.
2. Codificação de Saída (Output Encoding)
A defesa primária contra XSS (Cross-Site Scripting, ou Script entre Sites). Antes de renderizar dados do usuário no navegador, codifique-os para o contexto de saída apropriado.
Contexto
Método
Exemplo
Corpo HTML
Codificação de entidade HTML
< → <
Atributo HTML
Codificação de atributo
" → "
JavaScript
Codificação JavaScript
' → \x27
Parâmetro URL
Codificação percent
< → %3C
Regra de ouro: se você usa dangerouslySetInnerHTML (React), [innerHTML] (Angular) ou v-html (Vue), deve sanitizar o input primeiro usando uma biblioteca como DOMPurify. Essas saídas de emergência desabilitam a proteção XSS do framework.
A única defesa confiável contra SQL Injection (Injeção SQL) é separar código SQL dos dados do usuário.
# ❌ VULNERÁVEL: Concatenação de stringsquery = f"SELECT * FROM users WHERE email = '{email}'"# ✅ SEGURO: Consulta parametrizadacursor.execute("SELECT * FROM users WHERE email = %s", (email,))
// ❌ VULNERÁVEL: Template literalconst query = `SELECT * FROM users WHERE id = ${userId}`;// ✅ SEGURO: Consulta parametrizada (Node.js + pg)const result = await pool.query( 'SELECT * FROM users WHERE id = $1', [userId]);
O driver do banco trata valores parametrizados estritamente como dados, nunca como código SQL executável.
4. Menor Privilégio (Least Privilege)
Cada usuário, processo e aplicação deve ter apenas as permissões mínimas necessárias.
Exemplos no Nível de Aplicação
O usuário do banco de dados da aplicação web deve ter SELECT, INSERT, UPDATE em tabelas específicas: nãoDROP TABLE ou GRANT ALL.
Um microserviço que apenas lê dados deve ter credenciais somente leitura.
Um pipeline CI/CD fazendo deploy em staging não deve ter credenciais de produção.
O Princípio do Raio de Explosão (Blast Radius)
Menor privilégio limita o raio de explosão de um comprometimento. Se um atacante compromete um serviço com permissões mínimas, o dano é contido.
5. Gerenciamento de Segredos (Secrets Management)
Nunca hardcode segredos (chaves de API, senhas de banco, chaves de criptografia, tokens) no código-fonte.Segundo o relatório da GitGuardian de 2023, mais de 10 milhões de novos segredos foram detectados em commits públicos do GitHub em um único ano.
Onde Segredos Devem Ficar
Ambiente
Solução
Desenvolvimento local
Arquivos .env (adicionados ao .gitignore)
Pipelines CI/CD
Secrets do pipeline (GitHub Secrets, GitLab CI Variables)
Use ferramentas como gitleaks, trufflehog ou detect-secrets como hooks de pré-commit para escanear segredos antes de serem commitados:
# Instalar gitleaks como hook de pré-commitbrew install gitleaksgitleaks detect --source . --verbose
6. Segurança de Dependências (Dependency Security)
Aplicações modernas dependem de centenas de pacotes open-source. Cada dependência faz parte da sua superfície de ataque.
Risco na Cadeia de Suprimentos (Supply Chain Risk)
Log4Shell (2021): Vulnerabilidade crítica no Apache Log4j permitia execução remota de código com uma única mensagem de log. CVSS: 10.0/10.0.
event-stream (2018): Pacote npm popular foi comprometido por um novo mantenedor que injetou código direcionado a carteiras de criptomoeda.
Ferramentas de Escaneamento
Ferramenta
Ecossistema
Tipo
npm audit
Node.js
Integrado
Dependabot
GitHub (todas as linguagens)
PRs automatizados para dependências vulneráveis
Snyk
Multi-linguagem
SCA + scanning de containers
pip-audit
Python
Pacotes pip
7. Falhar com Segurança (Fail Securely)
Quando uma aplicação encontra um erro, deve falhar de forma que não conceda acesso adicional ou vaze informações.
# ❌ Vaza detalhes internosexcept Exception as e: return {"error": str(e)} # "Error: connection to postgres://admin:s3cret@db.internal:5432/prod failed"# ✅ Tratamento seguro de errosexcept Exception as e: logger.error(f"Falha na conexão com banco: {e}") # Log detalhado server-side return {"error": "Ocorreu um erro interno. Tente novamente mais tarde."}
8. Modelagem de Ameaças: STRIDE (Threat Modeling)
O framework STRIDE categoriza ameaças:
Letra
Ameaça (Threat)
Pergunta
S
Spoofing (Falsificação de Identidade)
Alguém pode fingir ser outro usuário ou serviço?
T
Tampering (Adulteração)
Alguém pode modificar dados em trânsito ou armazenados?
R
Repudiation (Repúdio)
Alguém pode negar ter realizado uma ação?
I
Information Disclosure (Vazamento de Informação)
Dados sensíveis podem vazar para partes não autorizadas?
D
Denial of Service (Negação de Serviço)
Alguém pode tornar o sistema indisponível?
E
Elevation of Privilege (Escalação de Privilégio)
Alguém pode ganhar permissões além do seu papel?
Principais Conclusões
Valide todo input server-side: Allow-lists sobre block-lists.
Codifique toda saída: Codificação contextual previne XSS.
Parametrize todas as consultas: A única defesa confiável contra SQLi.
Nunca hardcode segredos: Use gerenciadores de segredos e hooks de pré-commit.
Escaneie dependências continuamente: Automatize no CI/CD.
Falhe com segurança: Erros genéricos para usuários, logs detalhados server-side.
Modele ameaças cedo: STRIDE durante o design, não após o deploy.
{"docsConfig":{"theme":"mint","$schema":"https://mintlify.com/docs.json","name":"Road To Cybersec","colors":{"primary":"#1E40AF","light":"#3B82F6","dark":"#1E3A8A"},"logo":{"light":"https://mintcdn.com/richardwollyce/cz5aG1aJIgzXgJFU/logo/light.svg?fit=max\u0026auto=format\u0026n=cz5aG1aJIgzXgJFU\u0026q=85\u0026s=fd89814c7dab9c5234e4fc39868eaf99","dark":"https://mintcdn.com/richardwollyce/cz5aG1aJIgzXgJFU/logo/dark.svg?fit=max\u0026auto=format\u0026n=cz5aG1aJIgzXgJFU\u0026q=85\u0026s=0b2b65bab0ded351a66e3464e3df8110"},"favicon":"https://mintcdn.com/richardwollyce/vjW9nh05Vox9FT6V/favicon.svg?fit=max\u0026auto=format\u0026n=vjW9nh05Vox9FT6V\u0026q=85\u0026s=70003e3b2955dca5d45bc9eb5bdfef8e","styling":{"latex":false},"navigation":{"global":{"anchors":[{"anchor":"GitHub","icon":"github","href":"https://github.com/richard-wollyce/road-to-cybersec"},{"anchor":"License","icon":"book","href":"/license"}]},"languages":[{"language":"en","default":true,"href":""},{"language":"pt-BR","href":"pt-br/essentials/essentials-overview"}]}},"deployment":{"deploymentMetadataValue":{"subdomain":"richardwollyce","hasAudioNarration":false,"actualSubdomain":"richardwollyce","customDomains":["roadtocybersec.com"],"gitSource":{"type":"github","owner":"richard-wollyce","repo":"road-to-cybersec","deployBranch":"main","contentDirectory":"","isPrivate":false,"mountPath":"","label":""},"entitlements":{"AI_CHAT":{"status":"DISABLED"}},"buildId":"6ae95786a9cd2a01522c5d8f:success","clientVersion":"0.0.4271","searchFilterCounts":[{"language":"en","tag":"Advanced Topics","count":9},{"language":"pt-BR","tag":"Tópicos Avançados","count":9},{"language":"en","tag":"Essentials","count":6},{"language":"pt-BR","tag":"Fundamentos","count":6},{"language":"en","tag":"Welcome","count":1},{"language":"en","tag":"Workshop","count":1}]},"assistantConfig":{"enableAskAiButton":false,"enableStarterQuestions":false,"enableContextualStarterQuestions":false,"enableAskAiSearchBar":true},"basePath":"","hasChatPermissions":false,"hasWebMcpPermissions":false,"toggles":[{"name":"kill-isr","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"custom-rbac-roles","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-mintlify-slack","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-integrations-settings","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"rbac-expansion","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-pr-grouping","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"custom-prefix","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"analytics-v7","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"user-flows-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"no-publish-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-onboarding","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving-live","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"stripTemperatureMiddleware","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"support-platform-pylon-zendesk","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"instant-rollback","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications-server","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-fable","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fixed-ai-action-pricing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"site-roles","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automation-resolve-merge-conflict","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"scoped-publishing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"mintql","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"page-level-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"editor-version-history-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"billing-page-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"full-page-search","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workspace-projects","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"assistant-v5","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fork-pr-previews","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"revalidation-jwt","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-sso-scim","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"hobby-abuse-scan","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"dashboard-inbox","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-signup","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"turbopuffer-dual-write","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-enabled","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"approve-review-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"editor-metadata","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"sso-setup-deadline-banner","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"turbopuffer-serve","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"live-agents","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"starter-pricing","enabled":true,"variant":{"name":"control","enabled":true,"payload":{"type":"string","value":"control"},"feature_enabled":true},"impressionData":false},{"name":"llms-txt-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"wildcard-email-auth","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false}],"googleFontsInlined":false},"customCss":[{"filePath":"styles/logo.css","content":"header img[src*=\"/logo/\"],.logo img,.navbar img[src*=\"/logo/\"],.mint-nav img[src*=\"/logo/\"]{height:48px!important;max-height:48px!important;width:auto!important}img[alt*=\"logo\"]{max-height:48px!important}.rtc-home{min-height:calc(100vh - 96px);max-width:760px;margin:0 auto;padding:6rem 1.25rem;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center}.rtc-home h1{margin:0;font-size:clamp(2.25rem, 7vw, 4.5rem);line-height:1}.rtc-home-description{margin:1.25rem 0 0;max-width:620px;font-size:1.2rem;line-height:1.7}.rtc-home-actions{margin-top:1.75rem;display:flex;flex-wrap:wrap;justify-content:center;gap:0.875rem}.rtc-home-button{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0.75rem 1rem;border-radius:8px;font-weight:600;text-decoration:none!important;border:1px solid transparent;transition:all 0.2s ease-in-out}.rtc-home-button-primary{border-color:#1e40af;color:#1e40af!important;background:transparent}.rtc-home-button-primary:hover{background:#1e40af;color:#ffffff!important}.rtc-home-button-secondary{border-color:#1e40af;color:#1e40af!important;background:transparent}.rtc-home-button-secondary:hover{background:#1e40af;color:#ffffff!important}html.dark .rtc-home-button-primary{border-color:#1e40af;color:#ffffff!important;background:transparent}html.dark .rtc-home-button-primary:hover{background:#1e40af;color:#ffffff!important}html.dark .rtc-home-button-secondary{border-color:#1e40af;color:#ffffff!important;background:transparent}html.dark .rtc-home-button-secondary:hover{background:#1e40af;color:#ffffff!important}.rtc-home-eyebrow{margin:2rem 0 0.75rem;letter-spacing:0.21em;font-size:0.875rem;font-weight:300;color:var(--primary-color, #252525)}html.dark .rtc-home-eyebrow{margin:2rem 0 0.75rem;letter-spacing:0.21em;font-size:0.875rem;font-weight:300;color:var(--primary-color, #fafafa8e)}"}]}
{"page":{"pagePath":"pt-br/advanced/secure-coding-practices","slug":"/pt-br/advanced/secure-coding-practices","pageMetadata":{"title":"Práticas de Codificação Segura","description":"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.","href":"/pt-br/advanced/secure-coding-practices"},"description":{"compiledSource":"\"use strict\";\nconst {jsx: _jsx} = arguments[0];\nconst {useMDXComponents: _provideComponents} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = {\n p: \"p\",\n ..._provideComponents(),\n ...props.components\n };\n return _jsx(_components.p, {\n children: \"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\"\n });\n}\nfunction MDXContent(props = {}) {\n const {wrapper: MDXLayout} = {\n ..._provideComponents(),\n ...props.components\n };\n return MDXLayout ? _jsx(MDXLayout, {\n ...props,\n children: _jsx(_createMdxContent, {\n ...props\n })\n }) : _createMdxContent(props);\n}\nreturn {\n default: MDXContent\n};\n","frontmatter":{},"scope":{}},"pageType":"default","mdx":{"mdxSource":{"compiledSource":"\"use strict\";const{Fragment:_Fragment,jsx:_jsx,jsxs:_jsxs}=arguments[0];const{useMDXComponents:_provideComponents}=arguments[0];function _createMdxContent(props){const _components={code:`code`,li:`li`,ol:`ol`,p:`p`,pre:`pre`,span:`span`,strong:`strong`,tbody:`tbody`,td:`td`,th:`th`,thead:`thead`,tr:`tr`,ul:`ul`,..._provideComponents(),...props.components},{CodeBlock,Heading,Table,Tip,Warning}=_components;if(!CodeBlock)_missingMdxReference(`CodeBlock`,true);if(!Heading)_missingMdxReference(`Heading`,true);if(!Table)_missingMdxReference(`Table`,true);if(!Tip)_missingMdxReference(`Tip`,true);if(!Warning)_missingMdxReference(`Warning`,true);return _jsxs(_Fragment,{children:[_jsx(Heading,{level:`1`,id:`práticas-de-codificação-segura-secure-coding-practices`,children:`Práticas de Codificação Segura (Secure Coding Practices)`}),`\n`,_jsxs(_components.p,{children:[`Segurança não pode ser aparafusada em uma aplicação depois de construída. Deve ser `,_jsx(_components.strong,{children:`projetada na arquitetura`}),` e `,_jsx(_components.strong,{children:`escrita no código`}),` desde a primeira linha. O custo de corrigir uma vulnerabilidade em produção é `,_jsx(_components.strong,{children:`6-15x maior`}),` do que corrigi-la durante o desenvolvimento.`]}),`\n`,_jsx(Heading,{level:`2`,id:`1-validação-de-entrada-input-validation`,children:`1. Validação de Entrada (Input Validation)`}),`\n`,_jsx(_components.p,{children:_jsx(_components.strong,{children:`Nunca confie em dados do usuário, do cliente ou de qualquer sistema externo.`})}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Estratégia`}),_jsx(_components.th,{children:`Descrição`}),_jsx(_components.th,{children:`Exemplo`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Allow-listing (Lista de permissão)`})}),_jsx(_components.td,{children:`Defina exatamente o que É permitido`}),_jsxs(_components.td,{children:[`Username: `,_jsx(_components.code,{children:`^[a-zA-Z0-9_]{3,20}$`})]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Block-listing (Lista de bloqueio)`})}),_jsx(_components.td,{children:`Defina o que NÃO é permitido`}),_jsxs(_components.td,{children:[`Bloquear tags `,_jsx(_components.code,{children:`\u003cscript>`})]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Verificação de tipo`})}),_jsx(_components.td,{children:`Garanta que o input corresponde ao tipo esperado`}),_jsx(_components.td,{children:`Idade deve ser inteiro`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Limites de comprimento`})}),_jsx(_components.td,{children:`Restrinja o tamanho do input`}),_jsx(_components.td,{children:`Comentário máx. 5000 chars`})]})]})]}),`\n`,_jsx(Warning,{children:_jsxs(_components.p,{children:[_jsx(_components.strong,{children:`Sempre prefira allow-listing a block-listing.`}),` Listas de bloqueio são inerentemente incompletas, atacantes constantemente inventam novos truques de codificação e técnicas de ofuscação para evadi-las.`]})}),`\n`,_jsx(Heading,{level:`3`,id:`validação-server-side-vs-client-side`,children:`Validação Server-Side vs. Client-Side`}),`\n`,_jsxs(_components.ul,{children:[`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Validação client-side`}),` (JavaScript no navegador) melhora UX. `,_jsx(_components.strong,{children:`Não`}),` é um controle de segurança. Atacantes a ignoram trivialmente usando DevTools, Burp Suite ou curl.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Validação server-side`}),` é obrigatória. Cada input deve ser validado no servidor.`]}),`\n`]}),`\n`,_jsx(Heading,{level:`2`,id:`2-codificação-de-saída-output-encoding`,children:`2. Codificação de Saída (Output Encoding)`}),`\n`,_jsxs(_components.p,{children:[`A defesa primária contra `,_jsx(_components.strong,{children:`XSS (Cross-Site Scripting, ou Script entre Sites)`}),`. Antes de renderizar dados do usuário no navegador, codifique-os para o `,_jsx(_components.strong,{children:`contexto de saída`}),` apropriado.`]}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Contexto`}),_jsx(_components.th,{children:`Método`}),_jsx(_components.th,{children:`Exemplo`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:`Corpo HTML`}),_jsx(_components.td,{children:`Codificação de entidade HTML`}),_jsxs(_components.td,{children:[_jsx(_components.code,{children:`\u003c`}),` → `,_jsx(_components.code,{children:`\u0026lt;`})]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:`Atributo HTML`}),_jsx(_components.td,{children:`Codificação de atributo`}),_jsxs(_components.td,{children:[_jsx(_components.code,{children:`\"`}),` → `,_jsx(_components.code,{children:`\u0026quot;`})]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:`JavaScript`}),_jsx(_components.td,{children:`Codificação JavaScript`}),_jsxs(_components.td,{children:[_jsx(_components.code,{children:`'`}),` → `,_jsx(_components.code,{children:`\\\\x27`})]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:`Parâmetro URL`}),_jsx(_components.td,{children:`Codificação percent`}),_jsxs(_components.td,{children:[_jsx(_components.code,{children:`\u003c`}),` → `,_jsx(_components.code,{children:`%3C`})]})]})]})]}),`\n`,_jsx(Tip,{children:_jsxs(_components.p,{children:[`Regra de ouro: se você usa `,_jsx(_components.code,{children:`dangerouslySetInnerHTML`}),` (React), `,_jsx(_components.code,{children:`[innerHTML]`}),` (Angular) ou `,_jsx(_components.code,{children:`v-html`}),` (Vue), deve sanitizar o input primeiro usando uma biblioteca como DOMPurify. Essas saídas de emergência desabilitam a proteção XSS do framework.`]})}),`\n`,_jsx(Heading,{level:`2`,id:`3-consultas-parametrizadas-parameterized-queries`,children:`3. Consultas Parametrizadas (Parameterized Queries)`}),`\n`,_jsxs(_components.p,{children:[`A `,_jsx(_components.strong,{children:`única defesa confiável`}),` contra SQL Injection (Injeção SQL) é separar código SQL dos dados do usuário.`]}),`\n`,_jsx(CodeBlock,{filename:``,numberOfLines:`5`,language:`python`,children:_jsx(_components.pre,{className:`shiki shiki-themes github-light-default dark-plus`,style:{backgroundColor:`#ffffff`,\"--shiki-dark-bg\":`#0B0C0E`,color:`#1f2328`,\"--shiki-dark\":`#D4D4D4`},language:`python`,children:_jsxs(_components.code,{language:`python`,numberOfLines:`5`,children:[_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# ❌ VULNERÁVEL: Concatenação de strings`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`query `}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#D4D4D4`},children:`=`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:` f`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"SELECT * FROM users WHERE email = '`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`{`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`email`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`}`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`'\"`})]}),`\n`,_jsx(_components.span,{className:`line`}),`\n`,_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# ✅ SEGURO: Consulta parametrizada`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`cursor.execute(`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"SELECT * FROM users WHERE email = `}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`%s`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`, (email,))`})]}),`\n`]})})}),`\n`,_jsx(CodeBlock,{filename:``,numberOfLines:`8`,language:`javascript`,children:_jsx(_components.pre,{className:`shiki shiki-themes github-light-default dark-plus`,style:{backgroundColor:`#ffffff`,\"--shiki-dark-bg\":`#0B0C0E`,color:`#1f2328`,\"--shiki-dark\":`#D4D4D4`},language:`javascript`,children:_jsxs(_components.code,{language:`javascript`,numberOfLines:`8`,children:[_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`// ❌ VULNERÁVEL: Template literal`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`const`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#4FC1FF`},children:` query`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#D4D4D4`},children:` =`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:\" `SELECT * FROM users WHERE id = \"}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#569CD6`},children:\"${\"}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#9CDCFE`},children:`userId`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#569CD6`},children:`}`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:\"`\"}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`;`})]}),`\n`,_jsx(_components.span,{className:`line`}),`\n`,_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`// ✅ SEGURO: Consulta parametrizada (Node.js + pg)`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`const`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#4FC1FF`},children:` result`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#D4D4D4`},children:` =`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:` await`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#9CDCFE`},children:` pool`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`.`}),_jsx(_components.span,{style:{color:`#8250DF`,\"--shiki-dark\":`#DCDCAA`},children:`query`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`(`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:` 'SELECT * FROM users WHERE id = $1'`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`,`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` [`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#9CDCFE`},children:`userId`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`]`})]}),`\n`,_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`);`})}),`\n`]})})}),`\n`,_jsxs(_components.p,{children:[`O driver do banco trata valores parametrizados estritamente como `,_jsx(_components.strong,{children:`dados`}),`, nunca como código SQL executável.`]}),`\n`,_jsx(Heading,{level:`2`,id:`4-menor-privilégio-least-privilege`,children:`4. Menor Privilégio (Least Privilege)`}),`\n`,_jsxs(_components.p,{children:[`Cada usuário, processo e aplicação deve ter `,_jsx(_components.strong,{children:`apenas as permissões mínimas necessárias`}),`.`]}),`\n`,_jsx(Heading,{level:`3`,id:`exemplos-no-nível-de-aplicação`,children:`Exemplos no Nível de Aplicação`}),`\n`,_jsxs(_components.ul,{children:[`\n`,_jsxs(_components.li,{children:[`O usuário do banco de dados da aplicação web deve ter `,_jsx(_components.code,{children:`SELECT`}),`, `,_jsx(_components.code,{children:`INSERT`}),`, `,_jsx(_components.code,{children:`UPDATE`}),` em tabelas específicas: `,_jsx(_components.strong,{children:`não`}),` `,_jsx(_components.code,{children:`DROP TABLE`}),` ou `,_jsx(_components.code,{children:`GRANT ALL`}),`.`]}),`\n`,_jsx(_components.li,{children:`Um microserviço que apenas lê dados deve ter credenciais somente leitura.`}),`\n`,_jsx(_components.li,{children:`Um pipeline CI/CD fazendo deploy em staging não deve ter credenciais de produção.`}),`\n`]}),`\n`,_jsx(Heading,{level:`3`,id:`o-princípio-do-raio-de-explosão-blast-radius`,children:`O Princípio do Raio de Explosão (Blast Radius)`}),`\n`,_jsxs(_components.p,{children:[`Menor privilégio limita o `,_jsx(_components.strong,{children:`raio de explosão`}),` de um comprometimento. Se um atacante compromete um serviço com permissões mínimas, o dano é contido.`]}),`\n`,_jsx(Heading,{level:`2`,id:`5-gerenciamento-de-segredos-secrets-management`,children:`5. Gerenciamento de Segredos (Secrets Management)`}),`\n`,_jsxs(_components.p,{children:[_jsx(_components.strong,{children:`Nunca hardcode segredos`}),` (chaves de API, senhas de banco, chaves de criptografia, tokens) no código-fonte.`]}),`\n`,_jsxs(_components.p,{children:[`Segundo o relatório da GitGuardian de 2023, mais de `,_jsx(_components.strong,{children:`10 milhões de novos segredos`}),` foram detectados em commits públicos do GitHub em um único ano.`]}),`\n`,_jsx(Heading,{level:`3`,id:`onde-segredos-devem-ficar`,children:`Onde Segredos Devem Ficar`}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Ambiente`}),_jsx(_components.th,{children:`Solução`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Desenvolvimento local`})}),_jsxs(_components.td,{children:[`Arquivos `,_jsx(_components.code,{children:`.env`}),` (adicionados ao `,_jsx(_components.code,{children:`.gitignore`}),`)`]})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Pipelines CI/CD`})}),_jsx(_components.td,{children:`Secrets do pipeline (GitHub Secrets, GitLab CI Variables)`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Produção`})}),_jsx(_components.td,{children:`Gerenciadores dedicados (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager)`})]})]})]}),`\n`,_jsx(Heading,{level:`3`,id:`hooks-de-pré-commit-pre-commit-hooks`,children:`Hooks de Pré-commit (Pre-commit Hooks)`}),`\n`,_jsxs(_components.p,{children:[`Use ferramentas como `,_jsx(_components.strong,{children:`gitleaks`}),`, `,_jsx(_components.strong,{children:`trufflehog`}),` ou `,_jsx(_components.strong,{children:`detect-secrets`}),` como hooks de pré-commit para escanear segredos antes de serem commitados:`]}),`\n`,_jsx(CodeBlock,{filename:``,numberOfLines:`3`,language:`shellscript`,children:_jsx(_components.pre,{className:`shiki shiki-themes github-light-default dark-plus`,style:{backgroundColor:`#ffffff`,\"--shiki-dark-bg\":`#0B0C0E`,color:`#1f2328`,\"--shiki-dark\":`#D4D4D4`},language:`shellscript`,children:_jsxs(_components.code,{language:`shellscript`,numberOfLines:`3`,children:[_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# Instalar gitleaks como hook de pré-commit`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#953800`,\"--shiki-dark\":`#DCDCAA`},children:`brew`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:` install`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:` gitleaks`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#953800`,\"--shiki-dark\":`#DCDCAA`},children:`gitleaks`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:` detect`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#569CD6`},children:` --source`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:` .`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#569CD6`},children:` --verbose`})]}),`\n`]})})}),`\n`,_jsx(Heading,{level:`2`,id:`6-segurança-de-dependências-dependency-security`,children:`6. Segurança de Dependências (Dependency Security)`}),`\n`,_jsx(_components.p,{children:`Aplicações modernas dependem de centenas de pacotes open-source. Cada dependência faz parte da sua superfície de ataque.`}),`\n`,_jsx(Heading,{level:`3`,id:`risco-na-cadeia-de-suprimentos-supply-chain-risk`,children:`Risco na Cadeia de Suprimentos (Supply Chain Risk)`}),`\n`,_jsxs(_components.ul,{children:[`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Log4Shell (2021)`}),`: Vulnerabilidade crítica no Apache Log4j permitia execução remota de código com uma única mensagem de log. CVSS: `,_jsx(_components.strong,{children:`10.0/10.0`}),`.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`event-stream (2018)`}),`: Pacote npm popular foi comprometido por um novo mantenedor que injetou código direcionado a carteiras de criptomoeda.`]}),`\n`]}),`\n`,_jsx(Heading,{level:`3`,id:`ferramentas-de-escaneamento`,children:`Ferramentas de Escaneamento`}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Ferramenta`}),_jsx(_components.th,{children:`Ecossistema`}),_jsx(_components.th,{children:`Tipo`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`npm audit`})}),_jsx(_components.td,{children:`Node.js`}),_jsx(_components.td,{children:`Integrado`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Dependabot`})}),_jsx(_components.td,{children:`GitHub (todas as linguagens)`}),_jsx(_components.td,{children:`PRs automatizados para dependências vulneráveis`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`Snyk`})}),_jsx(_components.td,{children:`Multi-linguagem`}),_jsx(_components.td,{children:`SCA + scanning de containers`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`pip-audit`})}),_jsx(_components.td,{children:`Python`}),_jsx(_components.td,{children:`Pacotes pip`})]})]})]}),`\n`,_jsx(Heading,{level:`2`,id:`7-falhar-com-segurança-fail-securely`,children:`7. Falhar com Segurança (Fail Securely)`}),`\n`,_jsxs(_components.p,{children:[`Quando uma aplicação encontra um erro, deve falhar de forma que `,_jsx(_components.strong,{children:`não conceda acesso adicional ou vaze informações`}),`.`]}),`\n`,_jsx(CodeBlock,{filename:``,numberOfLines:`9`,language:`python`,children:_jsx(_components.pre,{className:`shiki shiki-themes github-light-default dark-plus`,style:{backgroundColor:`#ffffff`,\"--shiki-dark-bg\":`#0B0C0E`,color:`#1f2328`,\"--shiki-dark\":`#D4D4D4`},language:`python`,children:_jsxs(_components.code,{language:`python`,numberOfLines:`9`,children:[_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# ❌ Vaza detalhes internos`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:`except`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#4EC9B0`},children:` Exception`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:` as`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` e:`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:` return`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` {`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"error\"`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`: `}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#4EC9B0`},children:`str`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`(e)}`})]}),`\n`,_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:` # \"Error: connection to postgres://admin:s3cret@db.internal:5432/prod failed\"`})}),`\n`,_jsx(_components.span,{className:`line`}),`\n`,_jsx(_components.span,{className:`line`,children:_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# ✅ Tratamento seguro de erros`})}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:`except`}),_jsx(_components.span,{style:{color:`#0550AE`,\"--shiki-dark\":`#4EC9B0`},children:` Exception`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:` as`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` e:`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` logger.error(`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`f`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"Falha na conexão com banco: `}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`{`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`e`}),_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#569CD6`},children:`}`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`) `}),_jsx(_components.span,{style:{color:`#6E7781`,\"--shiki-dark\":`#6A9955`},children:`# Log detalhado server-side`})]}),`\n`,_jsxs(_components.span,{className:`line`,children:[_jsx(_components.span,{style:{color:`#CF222E`,\"--shiki-dark\":`#C586C0`},children:` return`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:` {`}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"error\"`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`: `}),_jsx(_components.span,{style:{color:`#0A3069`,\"--shiki-dark\":`#CE9178`},children:`\"Ocorreu um erro interno. Tente novamente mais tarde.\"`}),_jsx(_components.span,{style:{color:`#1F2328`,\"--shiki-dark\":`#D4D4D4`},children:`}`})]}),`\n`]})})}),`\n`,_jsx(Heading,{level:`2`,id:`8-modelagem-de-ameaças-stride-threat-modeling`,children:`8. Modelagem de Ameaças: STRIDE (Threat Modeling)`}),`\n`,_jsxs(_components.p,{children:[`O framework `,_jsx(_components.strong,{children:`STRIDE`}),` categoriza ameaças:`]}),`\n`,_jsxs(Table,{children:[_jsx(_components.thead,{children:_jsxs(_components.tr,{children:[_jsx(_components.th,{children:`Letra`}),_jsx(_components.th,{children:`Ameaça (Threat)`}),_jsx(_components.th,{children:`Pergunta`})]})}),_jsxs(_components.tbody,{children:[_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`S`})}),_jsx(_components.td,{children:`Spoofing (Falsificação de Identidade)`}),_jsx(_components.td,{children:`Alguém pode fingir ser outro usuário ou serviço?`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`T`})}),_jsx(_components.td,{children:`Tampering (Adulteração)`}),_jsx(_components.td,{children:`Alguém pode modificar dados em trânsito ou armazenados?`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`R`})}),_jsx(_components.td,{children:`Repudiation (Repúdio)`}),_jsx(_components.td,{children:`Alguém pode negar ter realizado uma ação?`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`I`})}),_jsx(_components.td,{children:`Information Disclosure (Vazamento de Informação)`}),_jsx(_components.td,{children:`Dados sensíveis podem vazar para partes não autorizadas?`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`D`})}),_jsx(_components.td,{children:`Denial of Service (Negação de Serviço)`}),_jsx(_components.td,{children:`Alguém pode tornar o sistema indisponível?`})]}),_jsxs(_components.tr,{children:[_jsx(_components.td,{children:_jsx(_components.strong,{children:`E`})}),_jsx(_components.td,{children:`Elevation of Privilege (Escalação de Privilégio)`}),_jsx(_components.td,{children:`Alguém pode ganhar permissões além do seu papel?`})]})]})]}),`\n`,_jsx(Heading,{level:`2`,id:`principais-conclusões`,children:`Principais Conclusões`}),`\n`,_jsxs(_components.ol,{children:[`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Valide todo input server-side`}),`: Allow-lists sobre block-lists.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Codifique toda saída`}),`: Codificação contextual previne XSS.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Parametrize todas as consultas`}),`: A única defesa confiável contra SQLi.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Nunca hardcode segredos`}),`: Use gerenciadores de segredos e hooks de pré-commit.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Escaneie dependências continuamente`}),`: Automatize no CI/CD.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Falhe com segurança`}),`: Erros genéricos para usuários, logs detalhados server-side.`]}),`\n`,_jsxs(_components.li,{children:[_jsx(_components.strong,{children:`Modele ameaças cedo`}),`: STRIDE durante o design, não após o deploy.`]}),`\n`]})]})}function MDXContent(props={}){const{wrapper:MDXLayout}={..._provideComponents(),...props.components};return MDXLayout?_jsx(MDXLayout,{...props,children:_jsx(_createMdxContent,{...props})}):_createMdxContent(props)}return{default:MDXContent};function _missingMdxReference(id,component){throw new Error(`Expected `+(component?`component`:`object`)+\" `\"+id+\"` to be defined: you likely forgot to import, pass, or provide it.\")}","frontmatter":{},"scope":{"config":{},"pageMetadata":{"title":"Práticas de Codificação Segura","description":"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.","href":"/pt-br/advanced/secure-coding-practices"}}},"mdxSourceWithNoJs":null},"mdxExtracts":{"tableOfContents":[{"title":"Práticas de Codificação Segura (Secure Coding Practices)","slug":"práticas-de-codificação-segura-secure-coding-practices","depth":1,"children":[]},{"title":"1. Validação de Entrada (Input Validation)","slug":"1-validação-de-entrada-input-validation","depth":2,"children":[{"title":"Validação Server-Side vs. Client-Side","slug":"validação-server-side-vs-client-side","depth":3,"children":[]}]},{"title":"2. Codificação de Saída (Output Encoding)","slug":"2-codificação-de-saída-output-encoding","depth":2,"children":[]},{"title":"3. Consultas Parametrizadas (Parameterized Queries)","slug":"3-consultas-parametrizadas-parameterized-queries","depth":2,"children":[]},{"title":"4. Menor Privilégio (Least Privilege)","slug":"4-menor-privilégio-least-privilege","depth":2,"children":[{"title":"Exemplos no Nível de Aplicação","slug":"exemplos-no-nível-de-aplicação","depth":3,"children":[]},{"title":"O Princípio do Raio de Explosão (Blast Radius)","slug":"o-princípio-do-raio-de-explosão-blast-radius","depth":3,"children":[]}]},{"title":"5. Gerenciamento de Segredos (Secrets Management)","slug":"5-gerenciamento-de-segredos-secrets-management","depth":2,"children":[{"title":"Onde Segredos Devem Ficar","slug":"onde-segredos-devem-ficar","depth":3,"children":[]},{"title":"Hooks de Pré-commit (Pre-commit Hooks)","slug":"hooks-de-pré-commit-pre-commit-hooks","depth":3,"children":[]}]},{"title":"6. Segurança de Dependências (Dependency Security)","slug":"6-segurança-de-dependências-dependency-security","depth":2,"children":[{"title":"Risco na Cadeia de Suprimentos (Supply Chain Risk)","slug":"risco-na-cadeia-de-suprimentos-supply-chain-risk","depth":3,"children":[]},{"title":"Ferramentas de Escaneamento","slug":"ferramentas-de-escaneamento","depth":3,"children":[]}]},{"title":"7. Falhar com Segurança (Fail Securely)","slug":"7-falhar-com-segurança-fail-securely","depth":2,"children":[]},{"title":"8. Modelagem de Ameaças: STRIDE (Threat Modeling)","slug":"8-modelagem-de-ameaças-stride-threat-modeling","depth":2,"children":[]},{"title":"Principais Conclusões","slug":"principais-conclusões","depth":2,"children":[]}],"codeExamples":{}},"jsLinks":[],"subdomain":"richardwollyce","siteName":"Road To Cybersec","title":"Práticas de Codificação Segura - Road To Cybersec","navMaps":{"firstHrefInVersion":{},"firstHrefInLanguage":{"en":{"href":"/advanced/secure-coding-practices","matchLevel":1},"pt-BR":{"href":"/pt-br/advanced/secure-coding-practices","matchLevel":0}}},"lastModified":"2026-05-21T18:11:04.007Z","originalFileLocation":"pt-br/advanced/secure-coding-practices.mdx","locale":"pt-BR"},"headHtml":"\u003cscript data-mint-head>(function(){var d=document.documentElement,p=null;if(!p){try{p=localStorage.getItem(\"isDarkMode\")}catch(e){}if(p==='true')p='dark';else if(p==='false')p='light';if(p!=='light'\u0026\u0026p!=='dark'\u0026\u0026p!=='system')p=\"system\"}var r=p==='system'?(matchMedia(\"(prefers-color-scheme: dark)\").matches?'dark':'light'):p;d.classList.remove(r==='dark'?'light':'dark');d.classList.add(r);d.setAttribute(\"data-theme-preference\",p)})();\u003c/script>\u003cmeta data-mint-head name=\"description\" content=\"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\">\u003cmeta data-mint-head name=\"application-name\" content=\"Road To Cybersec\">\u003cmeta data-mint-head name=\"generator\" content=\"Mintlify\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/android-chrome-192x192.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"apple-touch-icon\" type=\"image/png\" sizes=\"180x180\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/apple-touch-icon.png\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/favicon-16x16.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/favicon-32x32.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/favicon.ico\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon-dark/android-chrome-192x192.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon-dark/favicon-16x16.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon-dark/favicon-32x32.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon-dark/favicon.ico\" media=\"(prefers-color-scheme: dark)\">\u003cmeta data-mint-head property=\"og:title\" content=\"Práticas de Codificação Segura - Road To Cybersec\">\u003cmeta data-mint-head property=\"og:description\" content=\"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\">\u003cmeta data-mint-head property=\"og:site_name\" content=\"Road To Cybersec\">\u003cmeta data-mint-head property=\"og:url\" content=\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\">\u003cmeta data-mint-head property=\"og:type\" content=\"website\">\u003cmeta data-mint-head property=\"og:image\" content=\"https://richardwollyce.mintlify.site/_mintlify/api/og/v2?division=T%C3%B3picos+Avan%C3%A7ados\u0026amp;title=Pr%C3%A1ticas+de+Codifica%C3%A7%C3%A3o+Segura\u0026amp;description=Valida%C3%A7%C3%A3o+de+entrada%2C+codifica%C3%A7%C3%A3o+de+sa%C3%ADda%2C+escaneamento+de+depend%C3%AAncias%2C+gerenciamento+de+segredos%2C+seguran%C3%A7a+CI%2FCD+e+modelagem+de+amea%C3%A7as.\u0026amp;theme=13e12c4fba3ae563774d290f\u0026amp;signature=075a91f61a04fd8164637013158a522b3554dcfe355030a4f6a26dc4214de0c3\">\u003cmeta data-mint-head property=\"og:image:width\" content=\"1200\">\u003cmeta data-mint-head property=\"og:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"twitter:card\" content=\"summary_large_image\">\u003cmeta data-mint-head name=\"twitter:title\" content=\"Práticas de Codificação Segura - Road To Cybersec\">\u003cmeta data-mint-head name=\"twitter:description\" content=\"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\">\u003cmeta data-mint-head name=\"twitter:image\" content=\"https://richardwollyce.mintlify.site/_mintlify/api/og/v2?division=T%C3%B3picos+Avan%C3%A7ados\u0026amp;title=Pr%C3%A1ticas+de+Codifica%C3%A7%C3%A3o+Segura\u0026amp;description=Valida%C3%A7%C3%A3o+de+entrada%2C+codifica%C3%A7%C3%A3o+de+sa%C3%ADda%2C+escaneamento+de+depend%C3%AAncias%2C+gerenciamento+de+segredos%2C+seguran%C3%A7a+CI%2FCD+e+modelagem+de+amea%C3%A7as.\u0026amp;theme=13e12c4fba3ae563774d290f\u0026amp;signature=075a91f61a04fd8164637013158a522b3554dcfe355030a4f6a26dc4214de0c3\">\u003cmeta data-mint-head name=\"twitter:image:width\" content=\"1200\">\u003cmeta data-mint-head name=\"twitter:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"msapplication-config\" content=\"/mintlify-assets/_mintlify/favicons/richardwollyce/zW2Tc3K73A_SSlMw/_generated/favicon/browserconfig.xml\">\u003cmeta data-mint-head name=\"apple-mobile-web-app-title\" content=\"Road To Cybersec\">\u003cmeta data-mint-head name=\"msapplication-TileColor\" content=\"#1E40AF\">\u003clink data-mint-head rel=\"canonical\" href=\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\">\u003clink data-mint-head rel=\"alternate\" type=\"application/xml\" href=\"/sitemap.xml\">\u003clink data-mint-head rel=\"alternate\" type=\"text/markdown\" href=\"/pt-br/advanced/secure-coding-practices.md\">\u003clink data-mint-head rel=\"alternate\" hreflang=\"pt-BR\" href=\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\">\u003clink data-mint-head rel=\"alternate\" hreflang=\"en\" href=\"https://roadtocybersec.com/advanced/secure-coding-practices\">\u003clink data-mint-head rel=\"alternate\" hreflang=\"x-default\" href=\"https://roadtocybersec.com/advanced/secure-coding-practices\">\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https://roadtocybersec.com/#organization\",\"name\":\"Road To Cybersec\",\"url\":\"https://roadtocybersec.com\",\"logo\":{\"@type\":\"ImageObject\",\"url\":\"https://mintcdn.com/richardwollyce/cz5aG1aJIgzXgJFU/logo/light.svg?fit=max\u0026auto=format\u0026n=cz5aG1aJIgzXgJFU\u0026q=85\u0026s=fd89814c7dab9c5234e4fc39868eaf99\"}},{\"@type\":\"WebSite\",\"@id\":\"https://roadtocybersec.com#website\",\"name\":\"Road To Cybersec\",\"url\":\"https://roadtocybersec.com\",\"publisher\":{\"@id\":\"https://roadtocybersec.com/#organization\"}},{\"@type\":\"WebPage\",\"@id\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices#webpage\",\"url\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\",\"name\":\"Práticas de Codificação Segura\",\"description\":\"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\",\"dateModified\":\"2026-05-21T18:11:04.007Z\",\"isPartOf\":{\"@id\":\"https://roadtocybersec.com#website\"},\"breadcrumb\":{\"@id\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices#breadcrumb\"}},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Tópicos Avançados\",\"item\":\"https://roadtocybersec.com/pt-br/advanced/network-security\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Práticas de Codificação Segura\",\"item\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\"}]},{\"@type\":[\"Article\",\"TechArticle\"],\"@id\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices#article\",\"headline\":\"Práticas de Codificação Segura\",\"name\":\"Práticas de Codificação Segura\",\"description\":\"Validação de entrada, codificação de saída, escaneamento de dependências, gerenciamento de segredos, segurança CI/CD e modelagem de ameaças.\",\"url\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices\",\"mainEntityOfPage\":{\"@id\":\"https://roadtocybersec.com/pt-br/advanced/secure-coding-practices#webpage\"},\"dateModified\":\"2026-05-21T18:11:04.007Z\",\"publisher\":{\"@id\":\"https://roadtocybersec.com/#organization\"},\"isPartOf\":{\"@id\":\"https://roadtocybersec.com#website\"}}]}\u003c/script>\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@type\":\"WebSite\",\"name\":\"Road To Cybersec\",\"publisher\":{\"@type\":\"Organization\",\"name\":\"Road To Cybersec\"},\"provider\":{\"@type\":\"Organization\",\"name\":\"Mintlify\",\"url\":\"https://mintlify.com\"}}\u003c/script>","agentPointerHref":"/pt-br/advanced/secure-coding-practices.md","siteName":"Road To Cybersec","nav":{"global":{"anchors":[{"anchor":"GitHub","icon":"github","href":"https://github.com/richard-wollyce/road-to-cybersec"},{"anchor":"License","icon":"book","href":"/license"}]},"languages":[{"language":"en","default":true,"pages":[{"title":"en","href":"/advanced/secure-coding-practices"}]},{"language":"pt-BR","groups":[{"group":"Fundamentos","pages":[{"title":"Fundamentos de Cibersegurança","href":"/pt-br/essentials/essentials-overview"},{"title":"Ameaças e Ataques","href":"/pt-br/essentials/threats-and-attacks"},{"title":"Segurança de Senhas e MFA","href":"/pt-br/essentials/password-security"},{"title":"Navegação Segura","href":"/pt-br/essentials/safe-browsing"},{"title":"Higiene de Dispositivos","href":"/pt-br/essentials/device-hygiene"},{"title":"O Que Fazer Se For Hackeado","href":"/pt-br/essentials/what-to-do-if-hacked"}]},{"group":"Tópicos Avançados","pages":[{"title":"Segurança de Redes","href":"/pt-br/advanced/network-security"},{"title":"Criptografia","href":"/pt-br/advanced/cryptography"},{"title":"Vulnerabilidades Web","description":"O OWASP Top 10, ataques de injeção, XSS, CSRF, SSRF, autenticação quebrada e configurações inseguras, com exemplos reais.","href":"/pt-br/advanced/web-vulnerabilities"},{"title":"Práticas de Codificação Segura","href":"/pt-br/advanced/secure-coding-practices"},{"title":"Segurança Avançada da Cadeia de Suprimentos","description":"Entenda o comprometimento de código a montante (upstream), explorações de registros de pacotes, vulnerabilidades em pipelines de build e CI/CD, riscos no ambiente do desenvolvedor e defesas robustas.","href":"/pt-br/advanced/supply-chain-security"},{"title":"Segurança em IA e Riscos de LLMs","href":"/pt-br/advanced/ai-security"},{"title":"Testes de Penetração","href":"/pt-br/advanced/penetration-testing"},{"title":"Os Cypherpunks","href":"/pt-br/advanced/cypherpunks"},{"title":"O Caso GitHub: Ataque de Cadeia de Suprimentos no CI/CD","href":"/pt-br/advanced/github-issue"}]}]}]},"basePath":"","title":"Práticas de Codificação Segura - Road To Cybersec","deploymentId":"dpl_Em2U4NQQ2N2DE3HPbPUJVZLnAtvc","buildId":"dpl_Em2U4NQQ2N2DE3HPbPUJVZLnAtvc","dynamics":[],"chunks":[]}