Conceitos de Identidade e Acesso
Gestão de identidade e acesso no fio, de MFA e federação a OAuth, OIDC, diretórios e modelos de autorização, explicada a fundo, um conceito de cada vez.
Foundations
Authentication Factors
Senhas e Ataques a Credenciais: Hash, Stuffing, Spraying e Política Moderna
Senhas do lado do servidor, medidas nesta máquina. Custo por hash de SHA-256, PBKDF2, bcrypt, scrypt e Argon2id nos parâmetros atuais da OWASP e a conta de palpites por segundo de quem tem o banco vazado (estimativa), salt único e pepper, formato PHC e migração de hash legado com rehash no login, as classes de ataque (força bruta online e offline, dicionário, credential stuffing, password spraying) contra um endpoint de login de brinquedo local, limitação de taxa, atraso progressivo contra bloqueio duro, resposta e tempo iguais para usuário inexistente, detecção, a política do NIST SP 800-63B-4, verificação de senha vazada com k-anonymity, fluxo de reset seguro e a tabela ataque, defesa, métrica.
MFA: Fatores, HOTP, TOTP, SMS, Push e Recuperação
Os fatores de autenticação medidos no fio. Algo que você sabe, tem e é, HOTP (RFC 4226) e TOTP (RFC 6238) escritos do zero em 10 linhas e validados contra os 18 vetores de teste oficiais do RFC 6238, o URI otpauth:// do QR code, janela de tolerância e deriva de relógio, replay de código, força bruta e bloqueio com as contas feitas, o segredo cifrado em repouso, códigos de recuperação de uso único, SMS e e-mail segundo o NIST SP 800-63B-4, fadiga de push e number matching, phishing em tempo real (AiTM) e origin binding, e a tabela de resistência a phishing de cada fator.
WebAuthn, FIDO2 e passkeys: o protocolo medido
WebAuthn medido sem navegador e sem chave física, com um autenticador ES256 de software e um servidor RP em Node 22. A cerimônia de registro (challenge, rp.id, user.id, authenticatorSelection), o clientDataJSON e o attestationObject CBOR, o authData byte a byte (rpIdHash, flags UP/UV/BE/BS/AT/ED, signCount, AAGUID, credentialId, chave COSE), a autenticação (assinatura sobre authData e SHA-256 do clientDataJSON) e a verificação passo a passo, credenciais discoverable e login sem username, origin binding contra phishing com o TOTP aceito no mesmo ataque, signCount e clonagem, passkey sincronizada contra ligada ao dispositivo, attestation e AAGUID, userVerification, recuperação de conta e a tabela de parâmetros do RP.
Identity Threats: AiTM, Phishing, Consent Phishing and Recovery
Identity attacks as failures of the trust model, with defenses measured on toy services of my own. The phishing resistance ladder (NIST SP 800-63B-4, CISA), AiTM and why MFA that is not phishing-resistant does not protect the session cookie, a session that works from another client and stops working when bound to a device key, MFA fatigue and number matching, token theft and reuse detection, consent phishing in OAuth with the Entra consent policies and a Keycloak 26.8.2 grant viewed and revoked through the Admin API (and what happens to the refresh token), account recovery as the weak link measured before and after four controls, stuffing and spraying, privileged and service accounts, a 60-line detector with measured false positives, the compromised-account checklist, MITRE ATT&CK technique IDs and a table of threat, bypassed control, defense and signal.
Federation & SSO
SAML 2.0: Assertions, Bindings e Fluxos de SSO
SAML 2.0 medido no fio contra um Keycloak 26.8.2 local como IdP. O fluxo SP-initiated com Redirect e POST binding contra o IdP-initiated (sem InResponseTo), o AuthnRequest e o Response decodificados de base64 e deflate, a Assertion anotada elemento a elemento (Issuer, NameID, Conditions, AudienceRestriction, SubjectConfirmationData, AuthnStatement, AttributeStatement), a metadata XML, a assinatura XMLDSig (C14N, Reference por ID), a lista de validações obrigatórias do SP cada uma falhada de propósito, o ataque XML Signature Wrapping contra um verificador de brinquedo, mapeamento de atributos para papéis, Single Logout e SAML contra OIDC.
Gerenciamento de Sessão: Cookies, Fixação e Revogação
O que acontece depois do login, medido contra um servidor de sessão de brinquedo em Node 22 sem framework. ID de sessão de 128 bits contra contador, cada atributo do Set-Cookie (HttpOnly, Secure, Path, Domain, Max-Age, prefixos __Host- e __Secure-) com curl, fixação de sessão e a regeneração do ID no login, expiração deslizante contra absoluta, "lembrar-me" com seletor e validador com hash, CSRF com token sincronizado, double submit assinado e Sec-Fetch-Site, logout de verdade, sair de todos os dispositivos, revogação por troca de senha e por SCIM active:false, JWT como cookie de sessão contra os mesmos testes, padrão BFF, Redis compartilhado e a queda do armazenamento, com SameSite e o Continuous Access Evaluation do Entra lidos só na documentação.
Choosing a Federation Protocol: SAML, OIDC, Kerberos and LDAP
Decision layer over the protocol lessons: a matrix of LDAP, Kerberos, SAML, OIDC and SCIM by client type, network, IdP ownership, logout, attributes, cost, attack surface and library maturity, then identity brokering measured with three Keycloak 26.8.2 containers on one Docker network. A hub realm that stores no passwords delegates to one upstream over OIDC and another over SAML, and the app sees a single OIDC token. Measured: the wire flow, claim mapping from both upstreams with identity provider mappers, kc_idp_hint, home realm discovery by e-mail domain with Keycloak organizations, the first broker login account takeover by unverified e-mail (six runs, which settings close it), and what hub logout does to the upstream sessions. B2B, B2C and CIAM, workforce, inter-organization federation, BFF gateways and SAML to OIDC migration are prose, with Entra docs only. Ends with a scenario, protocol, reason and pitfall table.
Directory Services
LDAP: Diretórios, DN, Schema e Binds
LDAP medido contra um OpenLDAP 2.6.10 local. A árvore (DIT, DN, RDN), os erros de schema (MUST/MAY, estrutural contra auxiliar), todas as operações, escopos e filtros da RFC 4515, o custo de um índice em 50.000 entradas medido no log do servidor, bind anônimo, simples, SASL e o bug do "unauthenticated bind", LDAPS contra StartTLS vistos no fio, ACLs, hashes de userPassword ({SSHA} e {ARGON2}), paginação, referrals, o padrão busca-e-depois-bind e LDAP injection contra um script de brinquedo local com a defesa de escape.
Active Directory e Entra ID: Domínios, Florestas e Híbrido
O Active Directory medido contra um domínio compatível (Samba 4.22.11, lab.test, dois DCs) em Docker, e o Entra ID e o híbrido só pela documentação. Floresta, domínio, DC, Global Catalog, sites e DNS SRV, objetos e os quatro nomes de um usuário (DN, sAMAccountName, UPN, objectGUID e objectSid decodificados, com o RID), tipos e escopos de grupo, AGDLP, memberOf contra tokenGroups e o filtro LDAP_MATCHING_RULE_IN_CHAIN, bits de userAccountControl e filtro bit a bit, as duas portas (LDAP com StartTLS ou GSSAPI, Kerberos), replicação multi-master, pools de RID e FSMO medidos com dois DCs, GPO como objeto mais SYSVOL, política de senha padrão. Depois Entra ID (tenant, app registration contra enterprise application, permissões delegadas contra de aplicação, consentimento, Conditional Access, PIM, managed identities), sincronização híbrida (Entra Connect, Cloud Sync, source anchor ms-DS-ConsistencyGuid), PHS contra PTA contra federação, Seamless SSO, hybrid join, o atrito do UPN, segurança em prosa e uma tabela AD contra Entra.
Kerberos: Tickets, TGT, Delegação e NTLM
Kerberos medido contra um KDC MIT 1.21.3 de laboratório em Docker. Realm, principals, kinit, o TGT e os tickets de serviço no fio (tshark), pré-autenticação com timestamp cifrado, o que há dentro de um ticket, keytab, Apache Negotiate e sshd GSSAPI validando de verdade, falhas medidas (Clock skew too great, ticket expirado e renovação, SPN por IP, kvno de keytab velho), tipos de cifra, delegação (forwardable e unconstrained medidas; constrained e RBCD em prosa), trusts e Active Directory, ataques como classes de falha com defesas, NTLM medido com um verificador próprio (hash NT, desafio-resposta, relay) e a tabela final de tickets, quem cifra, ataque e defesa.
OAuth & OIDC
OAuth 2.0 do Zero: Papéis, Grants e Tokens
OAuth 2.0 medido no fio contra um Keycloak 26.8.2 local, só com curl, jq e openssl. Os quatro papéis, cliente público contra confidencial, authorization code com PKCE S256 passo a passo, client credentials, device code (RFC 8628), rotação de refresh token com detecção de reuso, o que o OAuth 2.1 removeu (implicit, ROPC, redirect curinga) e o ataque por trás de cada remoção, escopo contra audience, JWT (RFC 9068) contra token opaco, introspecção (RFC 7662) e revogação (RFC 7009) cronometradas, reuso de code revogando os tokens emitidos e invalid_grant, invalid_client e invalid_scope provocados de propósito.
OpenID Connect: ID Token, UserInfo, Discovery and Logout
OpenID Connect measured on the wire against a local Keycloak 26.8.2 with curl, jq and a 44-line Node 22 validator: what scope=openid adds, the ID token and the access token decoded side by side (aud is the client versus an API), the standard claims, discovery and JWKS, step-by-step ID token validation failing on a wrong nonce, wrong aud, tampered payload, alg none, expiry and at_hash, JWKS key rotation and caching, prompt, max_age and acr_values (and the silent acr downgrade), implicit and hybrid as history, and RP-initiated, front-channel and back-channel logout with what each one does not guarantee.
OAuth Token Exchange: Delegation and On-Behalf-Of
Why a service cannot forward the user's token, and the three real answers measured against Keycloak 26.8.2 with curl, jq and Node 22: the service's own credential, RFC 8693 token exchange as impersonation, and token exchange as delegation with may_act and a nested act claim. Covers audience restriction, the refusals (invalid_client, access_denied, invalid_scope, expired subject), resource silently ignored, widening scope by default and the downscope executor that stops it, why Keycloak stops at one delegation hop while an illustrative STS shows the A to B to C act chain, exchange cost versus a cache, audit, plus the Microsoft Entra on-behalf-of flow (docs only) and a comparison table.
Segurança no OAuth: BCP, DPoP, mTLS, PAR, RAR e Resource Indicators
O endurecimento do OAuth medido no fio contra um Keycloak 26.8.2 local e um resource server próprio em Node 22. O que a RFC 9700 exige e o que cada regra evita, o parâmetro iss contra mix-up (RFC 9207) checado pelo cliente, DPoP (RFC 9449) com cnf.jkt e um token roubado recusado por esquema Bearer, chave errada, jti repetido, htm, htu, ath e nonce, mTLS (RFC 8705) com cnf.x5t#S256 e certificado da mesma CA recusado, PAR (RFC 9126) tirando a requisição da URL, JAR, RAR (RFC 9396) recusado pelo Keycloak, resource indicators (RFC 8707) com aud por API e invalid_target, FAPI 2.0 e o que cada app realmente precisa.
Authorization Models
Provisioning & Lifecycle
Workload Identity
Workload Identity: Service Accounts, mTLS and SPIFFE
Machine identity instead of static secrets, measured where it runs locally. A throwaway CA and mTLS with openssl, curl and a small Node server (what the server reads from the certificate SAN, refusals for a wrong CA, expiry and a missing certificate, authentication versus authorization, handshake cost), then SPIFFE/SPIRE 1.16.0 in Docker: SPIFFE IDs, X.509 and JWT SVIDs decoded and verified against the bundle, node and workload attestation with join_token and unix selectors, two workloads doing mTLS with an allow list of SPIFFE IDs, rotation at half life and the fact that revocation is the TTL. Docs only: Kubernetes projected ServiceAccount tokens, GitHub Actions OIDC federation (with the trust condition tested, including the loose repo:org/* mistake), Azure, AWS and GCP workload identity, service meshes. Ends with the anti-pattern of passing user tokens between services, rotation, audit and attribution, and a table of mechanism, what it proves, credential lifetime, who validates and the trap.
Privileged Access: Secrets, Vaults and Just-in-Time
Privileged access and secrets, measured on HashiCorp Vault 2.2.2 in dev mode in Docker with curl, jq and the vault CLI. The problem of standing privilege and blast radius, the four parts of PAM (inventory, vault with check-out and check-in, session recording, just-in-time access), then the operation: KV v2 versions and metadata, HCL policies and three path traps, tokens with TTL, renew, expiry (403 with invalid token), revoke trees and orphans, dynamic Postgres credentials (issued, expired at the lease, revoked, and an open session that survives revocation until pg_terminate_backend is added), static role rotation and rotate-root, AppRole with response wrapping against secret zero (a second unwrap is evidence of interception), a JIT elevation approved by a second person with a 20 second token, short-lived signed SSH certificates, seal and unseal, the audit device with HMAC masked values and audit-hash, and break-glass: the Entra emergency access guidance, the MFA and Conditional Access lockout lesson, a break-glass read that raises an alert, and generate-root. Docs only: Entra PIM, Azure Key Vault, AWS Secrets Manager, CyberArk, BeyondTrust, OpenBao, Vault Enterprise control groups. Ends with a comparison table of Key Vault, Secrets Manager, Kubernetes Secrets and Vault, the PAM suite against secrets manager market, the BSL licence note, and what NIST SP 800-53 asks.