07 protocolos
07 — Protocolos Criptográficos
Protocolos combinam primitivas (cifras, hash, assinatura) em interações entre partes. Aqui: TLS, SSH, IPsec, Kerberos, OAuth/OIDC, Signal, MLS, Noise, WireGuard, OPAQUE, e protocolos clássicos relevantes.
1. SSL / TLS — evolução
SSL 1.0 (Netscape 1994) ❌
Nunca lançado publicamente. Falhas elementares descobertas internamente.
SSL 2.0 (1995) ❌
- MAC e encryption usam mesma chave.
- Tráfego header não autenticado.
- Vulnerável a *runcation attacks*
- *adding oracle issues*
- *eprecated*RFC 6176 (2011). Removido em todo browser ~2015.
SSL 3.0 (1996) ❌
- MAC com SHA-1 mas não cobre tudo.
- CBC vulnerável (BEAST, POODLE).
- *OODLE*(2014) — Padding Oracle On Downgraded Legacy Encryption. Killed SSL 3.0 in browsers Q4/2014.
TLS 1.0 (RFC 2246, 1999) ❌
Renomeio de SSL 3.1 (Netscape vs IETF politics). Mesmos algoritmos. *EAST*(2011) demonstrou problema com CBC IV chaining.
TLS 1.1 (RFC 4346, 2006) ❌
Fix do BEAST: IV explícito por record. Caíram em desuso; deprecated junto com 1.0 em 2020 (RFC 8996).
TLS 1.2 (RFC 5246, 2008) ⚠️
- Suporta SHA
256, AESGCM, AEAD. - Ainda permite RSA key transport (no forward secrecy).
- Ainda permite cipher suites com RC4, 3DES, CBC.
- Configuração segura possível mas exige diligência.
- *tatus* ainda dominante. Deve estar configurado *penas*com cipher suites ECDHE + AEAD.
*ipher suites recomendadas TLS 1.2*
ECDHE-ECDSA-AES128-GCM-SHA256ECDHE-ECDSA-CHACHA20-POLY1305ECDHE-RSA-AES256-GCM-SHA384ECDHE-RSA-CHACHA20-POLY1305
TLS 1.3 (RFC 8446, 2018) ✅
*edesign profundo*
- Remove RSA key transport (sempre ECDHE/DHE → forward secrecy obrigatório).
- Remove RC4, 3DES, MD5, SHA-1, CBC modes (todos), static DH.
- Remove compressão (CRIME).
- Remove renegotiation.
- Apenas 5 cipher suites; todas AEAD.
- *
RTT*(zero roundtrip resumption) — performance mas com replay caveats. - Handshake encrypted após ServerHello.
- *KDF-based key schedule*unificado.
*ipher suites TLS 1.3 (todas obrigatórias)*
TLS_AES_128_GCM_SHA256TLS_AES_256_GCM_SHA384TLS_CHACHA20_POLY1305_SHA256(obrigatório por RFC)TLS_AES_128_CCM_SHA256TLS_AES_128_CCM_8_SHA256
*ey exchange groups* secp256r1 (P256), secp384r1, secp521r1, *25519* X448, plus quântico híbrido, draftX25519MLKEM768 (pósietftlshybriddesign).
TLS 1.3 handshake (simplificado)
ClientHello [random, cipher_suites, key_share, signature_algorithms, ...]
→
ServerHello [random, cipher_suite, key_share, ...]
{EncryptedExtensions}
{Certificate}
{CertificateVerify}
{Finished}
←
{Certificate*} // mTLS opcional
{CertificateVerify*}
{Finished}
→
[Application Data]
⇄{...} = encrypted with handshake traffic secret derived from ECDHE.
Migração pós-quântica
- *25519MLKEM768*— Cloudflare/Google rolling out em 2024–2025. ClientHello carrega ambos key_shares; server escolhe.
- Servers tradicionais ainda em ECDHE puro.
- Migration completa esperada 2028–2032.
Falhas históricas TLS 1.2/1.3
| Ano | Ataque | Impacto |
|---|---|---|
| 2011 | BEAST | CBC IV em TLS 1.0 |
| 2012 | CRIME | TLS compression leak |
| 2013 | Lucky 13 | CBC timing |
| 2014 | Heartbleed | OpenSSL bug (não protocolo) |
| 2014 | POODLE | SSL 3.0 fallback CBC |
| 2014 | Triple Handshake | Cross-protocol |
| 2015 | FREAK | RSA export grade downgrade |
| 2015 | Logjam | DH 1024 pre-computation |
| 2016 | DROWN | SSLv2 cross-protocol oracle |
| 2016 | Sweet32 | 64-bit block ciphers |
| 2017 | ROBOT | Bleichenbacher revived |
| 2018 | Bleichenbacher in TLS 1.3 0-RTT replay | mitigated |
| 2020 | Raccoon attack | DH timing in TLS 1.2 |
| 2023 | Terrapin | SSH transport (não TLS) |
Extensions úteis
- *NI (Server Name Indication, RFC 6066)*— host header em ClientHello.
- *LPN (RFC 7301)*— Application-Layer Protocol Negotiation (HTTP2, HTTP3).
- *CH (Encrypted Client Hello, draft)*— encrypta SNI; substitui ESNI. Usa HPKE.
- *ertificate Transparency (RFC 6962)*— public logs de cert issuances.
- *CSP Stapling (RFC 6066)*— server envia OCSP response, cliente não consulta CA.
- *-RTT*— TLS 1.3 early data com PSK. Risco de replay.
- *LS
PSK*— preshared key, sem cert.
Cert validation chain
Root CA (offline, em HSM)
↓
Intermediate CA (online)
↓
End-entity cert (server)Cliente carrega Root store (Mozilla NSS, Microsoft, Apple, Google CRLSet). Cada intermediário assina o próximo.
*ertificate Transparency (CT)*— log público appendonly assinado. Browsers exigem SCT (Signed Certificate Timestamp). Detecta cert misissued.
2. SSH (Secure Shell)
História
- 1995: Tatu Ylönen (Finlândia) — SSH-1.
- 1996: OpenSSH fork de SSH-1.2.12 (último free).
- 1997–2006: IETF padroniza SSH-2 (RFC 4251–4254).
- 2006: SSH-2 mainstream.
Camadas SSH-2
- *ransport (RFC 4253)*— KEX, encryption, MAC, server authentication.
- *ser auth (RFC 4252)*— password, public key, host-based, GSSAPI.
- *onnection (RFC 4254)*— multiplex channels (shell, exec, port forward, X11).
KEX
- diffie
hellmangroup14-sha256 (RFC 8268) - diffie
hellmangroupexchangesha256 - ecdh
sha2nistp256384521 - *urve25519
sha256@libssh.org / curve25519sha256*(default moderno) - *ntrup761x25519-sha512@openssh.com*(PQC hybrid, OpenSSH 9.0+, abril 2022)
Host keys
- ssh
rsa (legacy, broken hash SHA1; deprecated default em OpenSSH 8.2+) - rsa
sha2256, rsasha2512 - ecdsa
sha2nistp256384521 - *sh-ed25519*(recomendado, default desde 7.x)
User keys
~/.ssh/id_ed25519 recomendado em vez de id_rsa. RSA 4096 OK como alternativa.
Vulnerabilidades históricas
- *RC
32 compensation attack*(1998, SSH1) — RC4-MD5. - *laintext recovery in CBC mode*(Albrecht et al. 2009) — exigia 8 GB tráfego.
- *oaming feature client bug*(CVE
20160777, 2016) — vazava chave privada. - *errapin*(CVE
202348795, dez/2023) — truncation attack em SSH BPP. Atacante MITM no handshake corta extension negotiation. Mitigado por strict KEX no OpenSSH 9.6+ e libssh 0.10.6+.
Hardening 2026
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256
KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
PubkeyAuthentication yes
PasswordAuthentication no
PermitRootLogin prohibit-password3. IPsec / IKE
Network-layer encryption. RFC 4301 (architecture), RFC 7296 (IKEv2).
Componentes
- *H (Authentication Header, RFC 4302)*— integridade + autenticidade (sem confidencialidade). Pouco usado hoje.
- *SP (Encapsulating Security Payload, RFC 4303)*— confidencialidade + integridade.
- *KE (Internet Key Exchange)*— negocia SAs (Security Associations) e chaves.
Modos
- *ransport mode*— IP header preservado; payload cifrado. Host
tohost. - *unnel mode*— IP header dentro cifrado; novo header externo. Gateway
togateway VPN.
IKEv1 ❌
RFC 2409 (1998). Aggressive Mode tem *SK offline crack*(cipherspark 2018 demo). Main Mode mais robusto mas complexo.
IKEv2 ✅
RFC 7296. Simplificação radical: 1 RTT setup, mobility (RFC 4555 MOBIKE), EAP auth.
Cipher suites recomendadas
- AES
GCM128 ou AESGCM256 (RFC 4106) - ChaCha20-Poly1305 (RFC 7634)
- Diffie
Hellman group 19 (256bit ECP) ou 20 (384-bit ECP) ou 31 (X25519)
IKE_AUTH com certificados ou PSK
Falhas
- *VE
20185389*— Aggressive Mode PSK offline. - *trongSwan / Libreswan*stack code: várias CVEs ao longo dos anos; mantenha atualizado.
Alternativa moderna: WireGuard
Ver §10.
4. Kerberos
MIT Athena Project, 1980s. RFC 4120 (V5, 2005). Backbone de Active Directory.
Componentes
- *DC (Key Distribution Center)* emite tickets.
- *S (Authentication Service)* emite TGT (Ticket-Granting Ticket).
- *GS (Ticket-Granting Service)* emite service tickets.
- *rincipal* identidade (user@REALM, host/fqdn@REALM).
Flow
- AS-REQ: cliente envia username; AS responde com TGT cifrada com hash de senha.
- Cliente decifra TGT com senha; agora tem TGT válido (e session key com TGS).
- TGS-REQ: cliente apresenta TGT + service principal pedido; TGS responde com service ticket.
- AP-REQ: cliente apresenta service ticket ao serviço.
Crypto
- DES (deprecated)
- 3DES (deprecated)
- AES
128/256CTSHMACSHA1-96 (RFC 3962) - AES
128/256CTSHMACSHA256/384-192 (RFC 8009)
Vulnerabilidades
- *olden Ticket* comprometeu hash do krbtgt (principal de TGS); pode forjar qualquer TGT. AD requer rotate dupla pra invalidar.
- *ilver Ticket* forja service ticket sem talk ao KDC.
- *erberoasting* pede service tickets com SPN comprometível, faz offline crack da chave (= hash da senha do account).
- *S-REP Roasting* usuários com
DONT_REQ_PREAUTHpermitem dump. - *erologon (CVE
20201472)*— Netlogon protocol bug: AESCFB8 com IV allzeros aceita all-zero plaintext → zera senha do DC. Crítico em set/2020.
5. OAuth 2.0 + OpenID Connect
Não-criptografia per se; protocolo de delegação de acesso.
OAuth 2.0 (RFC 6749, 2012)
Roles:
- *esource Owner*(usuário)
- *lient*(app)
- *uthorization Server*(Koder ID, Google, etc.)
- *esource Server*(API)
Flows:
- *uthorization Code*+ PKCE — padrão atual mobileSPAweb.
- *mplicit Flow*— deprecated (token em URL fragment, vaza).
- *lient Credentials*— service
toservice. - *evice Authorization Flow (RFC 8628)*— TVs, CLIs.
- *efresh Token*— long
lived reauth.
PKCE (RFC 7636)
code_verifier random; code_challenge = SHA256(verifier). Liga authorization code à sessão do cliente. *brigatório*para clientes públicos.
OpenID Connect (OIDC)
Identity layer on top de OAuth 2.0. Server emite *d_token*(JWT) com claims do usuário.
JWT (RFC 7519)
header.payload.signature- *eader* alg, typ.
- *ayload* claims (iss, sub, aud, exp, iat, jti, etc.).
- *ignature* assinatura sobre
header.payload.
*lgoritmos*
- HS256384512 — HMAC, simétrica (shared secret).
- RS256384512 — RSA
PKCS#1 v1.5 SHA*. - PS256384512 — RSA-PSS.
- ES256384512 — ECDSA.
- *dDSA*— Ed25519 (RFC 8037).
Falhas comuns JWT
- *alg: none`*aceito por libs descuidadas (CVE
20159235). - *alg: HS256` com pubkey RSA como secret*(CVE
20152951). - *id path traversal*se kid usado como filename.
- *lgorithm confusion*entre RS256 e HS256.
- *WT explicações* nunca confie em JWT que veio do cliente — sempre valide assinatura, exp, aud, iss.
Koder ID
Spec da Stack: specs/auth/oauth-flow.kmd — slug koder-id, postauth dashboard, no local form, deeplink preserve, R1-R12.
6. Signal Protocol
Endtoend encryption messaging. *pen Whisper Systems*(Moxie Marlinspike, Trevor Perrin) — atual *ignal Foundation*
Componentes
- *3DH*(Extended Triple Diffie
Hellman) — initial key agreement com prekeys publicados. - *ouble Ratchet*— DH ratchet (cada msg, nova chave) + symmetric ratchet (KDF per msg) → *orward secrecy*+ *ost-compromise security*
- *esame*— multi-device session management.
X3DH
Server hosts:
- Long-term *dentity key (IK_B)*— Ed25519.
- *igned pre-key (SPK_B)*— rotated weekly.
- *ne
time prekeys (OPK_B)*— used once.
Alice fetches Bob's bundle. Compute:
DH1 = DH(IK_A, SPK_B)
DH2 = DH(EK_A, IK_B)
DH3 = DH(EK_A, SPK_B)
DH4 = DH(EK_A, OPK_B)
SK = HKDF(DH1 \\\| DH2 \\\| DH3 \\\| DH4)*eniability* alguém com identity keys pode falsificar — Alice tem deniability cryptographically.
Double Ratchet
Para cada msg:
- *ymmetric ratchet* \(\text{chain\_key} \to (\text{msg\_key}, \text{chain\_key}')\) via HMAC-SHA256.
- *H ratchet* ao receber msg nova com nova DH pubkey, advance DH chain: novo DH share → novo root key → novos chain keys.
Resultado:
- *orward secrecy* msg antiga não recuperável mesmo com chave atual.
- *ost-compromise security* depois de comprometer estado, próximo DH ratchet recupera segurança.
Adoção
- Signal app
- WhatsApp (2016)
- Facebook Messenger Secret Conversations
- Google Allo (descontinuado)
- Skype private conversations
- KaKaoTalk
PQXDH (Signal, 2023)
Substituição PQC de X3DH. Combina X25519 + MLKEM1024. Hybrid model: ataque precisa quebrar ambos.
7. MLS — Messaging Layer Security
*FC 9420*(jul/2023). IETF padronização de E2E para *rupos*
Motivação
Signal escala mal pra grupos grandes (cada msg cifra para N membros). MLS usa *reeKEM* árvore binária, cada nó tem chave; mudança propaga em \(O(\log n)\).
Componentes
- *symmetric Ratchet Tree (RT)* árvore com chaves em cada nó.
- *reeKEM* derivação eficiente de chaves de grupo.
- *elcome message* novo membro recebe ratchet state.
- *ommit* muda estado do grupo (add, remove, update).
Adoção
- WebEx (Cisco)
- RingCentral
- Wickr (AWS)
- Implementations: OpenMLS (Rust), mlspp (Cisco C++)
8. Noise Protocol Framework
*revor Perrin* 2015–2018. noiseprotocol.org. Framework para *onstruir*protocolos seguros. Não é protocolo único.
Patterns
Notação: cada handshake = sequência de tokens (e, s, ee, es, se, ss). Exemplos:
- ** one
shot encryption to preknown recipient. - ** known recipient + sender authenticated.
- ** full mutual auth + encrypted transport.
- *K*(interactive K): used por WireGuard.
- *X* mutual auth, cert exchange.
Usado em
- *ireGuard* Noise_IKpsk2.
- *ightning Network* Noise_XK.
- *hatsApp protocol stack*(parts).
- *ym* *esh* *lack Connect*
9. WireGuard
Jason Donenfeld, 2015–2018. Mergeado no kernel Linux 5.6 (mar/2020).
Design
- 4000 lines of kernel C (vs 100k+ de IPsec stack).
- Cryptographic agility: *ejeitada por design* Algoritmos fixos:
- *urve25519*(ECDH)
- *haCha20-Poly1305*(AEAD)
- *LAKE2s*(hash)
- *KDF*
- Sem PKI; cada peer tem pubkey listado em config.
- UDP only, single port.
Handshake
Noise_IKpsk2 — 2 mensagens, 1 RTT. Recupera de hibernação com cookie.
Privacy
Sem identidade em pacotes. Stateless transport packets indistinguíveis sem chave correta.
Limitações
- Sem dynamic peers (use Tailscale/Headscale acima).
- Sem TCP fallback (use TCP-tunneling overlay).
- Sem PQC (proposed:
boringtunPQ fork experimentou em 2023).
10. OPAQUE — PAKE
*FC 9497*(2024). PAKE (Password-Authenticated Key Exchange) que evita servidor armazenar senha ou derivado.
- Server stores
OPRF(salt, password)envelope, sem nunca ver senha. - Mesmo se server vazar, *ffline dictionary attack impossível*
- Substitui sistema "send password, server bcrypt-compares".
Usado experimental em Cloudflare, ProtonMail planning, future Keybase.
Outras PAKE
- *RP (Secure Remote Password)*— antiga, ainda usada em 1Password até 2024.
- *PAKE2, J-PAKE, CPace*— variantes.
11. Email & Documents
PGP / OpenPGP
RFC 4880 (legacy), RFC 9580 (2024 — Crypto Refresh).
- *eb of trust*(vs PKI hierarchical).
- Cifras: AES, Camellia; hashes: SHA
2, SHA3; sigs: RSA, ECDSA, EdDSA, Ed25519. - *FC 9580*adiciona Curve25519, BLAKE2, Argon2.
*ríticas modernas*
- Long-term keys (no forward secrecy).
- UX terrível.
- Implementações divergentes.
- *FAIL*(2018) — backchannel via HTML rendering.
- *OP-spec*(Stateless OpenPGP) tenta limpar implementações.
S/MIME (RFC 8551)
PKCS#7 / CMS para email. CA-based PKI. Menos popular fora corporate.
age (Filippo Valsorda 2019)
Substitui PGP para file encryption.
- Sem long-term identities; cada arquivo tem ephemeral key.
- X25519 + ChaCha20-Poly1305 + scrypt.
- SSH key compatibility (Ed25519, RSA).
ageCLI, libsodium-style.
12. DNSSEC, DoT, DoH, DoQ
DNSSEC (RFC 4033/4035)
Assina records DNS. Cadeia de confiança DS / DNSKEY. Algoritmos modernos: ECDSA P256, Ed25519, Ed448. Algoritmos legacy ainda em uso: RSASHA256, RSA-SHA1 (proibir).
DNSoverTLS (DoT, RFC 7858)
Porta 853. TLS sobre porta dedicada. Server cert validado.
DNSoverHTTPS (DoH, RFC 8484)
Porta 443. Em HTTPS. Mais difícil de censurar mas misturando com tráfego web.
DNSoverQUIC (DoQ, RFC 9250)
DNS sobre QUIC. Latência menor.
ODoH, Oblivious DoH (RFC 9230)
Privacy: client → proxy → resolver. Resolver não sabe IP cliente; proxy não vê queries.
13. QUIC e HTTP/3
QUIC (RFC 9000–9002, 2021) — transport sobre UDP com TLS 1.3 builtin. Multiplex sem headof-line blocking. HTTP/3 (RFC 9114) é HTTP em QUIC.
Toda crypto = TLS 1.3 com extensão pra integrar nos pacotes QUIC.
14. ACME (Let's Encrypt)
*FC 8555*(2019). Protocolo de automatic cert issuance. Cliente prova controle do domain via challenges:
- *TTP
01* serve token em `/.wellknownacme-challenge`. - *NS
01* cria TXT record `_acmechallenge.example.com`. - *LS
ALPN01* serve cert ALPN especial.
Implementações:
- *ertbot*(EFF, original).
- *cme.sh*(bash).
- *ego*(Go, usado pelo Caddy/Traefik).
- *ehydrated*(bash, minimal).
- *oder Jet*native ACME.
Koder Stack: services/foundation/certs em s.khost1:9421 faz DNS-01 via ClouDNS API. LE staging confirmado.
15. WebAuthn / FIDO2
W3C + FIDO Alliance, 2019.
- Public-key authentication com hardware (YubiKey, Titan, Touch ID).
- Resiste phishing (origin binding).
- Crypto: ECDSA P-256, Ed25519, RSA opcional.
- Attestation opcional (prova autenticador genuíno).
Adoção: Google, Apple, Microsoft Passkeys (2022–) substituindo senhas. *asskey*= WebAuthn credential sincronizado em iCloud / Google account.
16. Tor / mix-nets / Loopix
Anonymity protocols.
- *or* 3
hop onion routing com TLS layered. AES128-CTR + DH ECDH. Hidden services .onion. - *2P* garlic routing.
- *ixnets (Loopix, Nym)* cover traffic, mixing nodes. Latency-tolerant.
17. Resumo: protocolos por uso (2026)
| Uso | Use |
|---|---|
| HTTPS browser/API | *LS 1.3*apenas |
| HTTPS legacy compat | TLS 1.2 com ECDHE+AEAD apenas |
| Remote login | *penSSH*≥ 9.6 com Ed25519 |
| VPN site |
*ireGuard*primary; strongSwan IPsec fallback |
| AD / corporate auth | Kerberos (com AES SHA-2) ou *IDC*preferred |
| Web app auth | *IDC*com PKCE + WebAuthn como 2FA |
| Mensageria E2E 1:1 | *ignal Protocol*ou MLS |
| Mensageria E2E grupo | *LS* |
| Email E2E | OpenPGP RFC 9580; ou age para arquivos |
| File encryption | *ge* |
| DNS privado | *oT*(system-wide) ou *oH*(browser) |
| Service mesh mTLS | TLS 1.3 com ECDSA-P256 ou Ed25519 |
| Hardware-backed login | *ebAuthn / FIDO2 / Passkeys* |
| Pós-quântico transit | TLS 1.3 + *25519MLKEM768*hybrid |
18. Referência cruzada
- Primitivas usadas:
04-simetrica.md,05-assimetrica.md,06-hash-e-mac.md. - Ataques contra:
11-ataques.md(BEAST, POODLE, FREAK, Logjam, DROWN, Heartbleed, ROBOT, Terrapin). - PQC integration:
08-pos-quantica.md. - Identidades / certs / CAs:
09-confidential-computing.md+13-incidentes.md(DigiNotar, Comodo). - Koder Stack usage:
14-koder-aplicada.md.