sábado, 31 de outubro de 2026

pass + GPG + git-remote-gcrypt: Encrypted Password Store Sync with GitHub

The idea was simple: keep my passwords in the terminal with pass, version the encrypted files with Git, and maintain an encrypted backup on GitHub. The interesting part is that storing .gpg files in a Git repository is not quite the same as encrypting the entire repository.

I wanted both: individual passwords encrypted locally with GPG, and a remote Git repository encrypted again before anything is uploaded. The final setup uses pass + GnuPG + Git + git-remote-gcrypt + SSH.

This write-up covers the installation from scratch, synchronization, restoration on another machine, and the GPG/WSL problems I encountered along the way.

Environment: GNU/Linux (Ubuntu/WSL2)
Password manager: pass
Local encryption: GnuPG
Version control: Git
Remote encryption: git-remote-gcrypt
Transport: OpenSSH
Remote: GitHub

1. How the whole thing works

There are two separate encryption layers.

                +-------------------------+
                |       pass CLI          |
                |  generate/show/insert   |
                +------------+------------+
                             |
                             v
                +-------------------------+
                |       GnuPG             |
                |  Encrypt each password  |
                +------------+------------+
                             |
                             v
                +-------------------------+
                |  ~/.password-store      |
                |  *.gpg + Git history    |
                +------------+------------+
                             |
                             v
                +-------------------------+
                |   git-remote-gcrypt     |
                |  Encrypt Git objects    |
                +------------+------------+
                             |
                             v
                +-------------------------+
                |    SSH transport        |
                |        GitHub           |
                +-------------------------+

pass encrypts individual password entries. Git tracks changes. git-remote-gcrypt encrypts the repository representation stored on GitHub.

SSH handles authentication and transport. It does not replace GPG encryption, and a normal Git push of encrypted password files does not automatically encrypt the rest of the Git history.

2. Installing the dependencies

On Ubuntu or Debian:

sudo apt update

sudo apt install -y \
    pass \
    gnupg \
    git \
    git-remote-gcrypt \
    openssh-client \
    pinentry-curses

Check the binaries:

pass version
gpg --version
git --version
command -v git-remote-gcrypt
command -v pinentry-curses

For Gentoo, the installation process is different, but the architecture is exactly the same: install the corresponding packages using Portage.

3. Creating or selecting a GPG key

If you already have a GPG key, do not generate another one just for this tutorial. List your existing keys:

gpg --list-secret-keys \
    --keyid-format LONG \
    --fingerprint

A key listing normally contains a primary key, its fingerprint, a user ID, and a subkey capable of encryption.

If you do not have a key, generate one:

gpg --full-generate-key

Choose a suitable supported algorithm, specify your identity and protect the private key with a strong passphrase.

The primary fingerprint identifies the key that will be used for the password store and the encrypted remote.

gpg --list-secret-keys \
    --with-subkey-fingerprint

For the remaining commands, replace SEU_FINGERPRINT_GPG with your real fingerprint.

4. Initializing pass

A new password store can be initialized with:

fingerprint_gpg="SEU_FINGERPRINT_GPG"

pass init "$fingerprint_gpg"

The default directory is:

~/.password-store/

The .gpg-id file records which GPG recipient is authorized to encrypt passwords.

Now create a test entry:

pass generate laboratorio/conta-teste 20

Read it:

pass show laboratorio/conta-teste

Or copy it to the clipboard, if clipboard support is available:

pass -c laboratorio/conta-teste

The password store now contains a GPG-encrypted file. No plaintext password needs to be committed to Git.

5. Preparing Git

Configure the Git identity, if you have not done so:

git config --global user.name "Seu Nome"

git config --global user.email \
    "seu-email@example.com"

Initialize Git integration inside the password store:

pass git init

cd ~/.password-store

git branch -M main

git status -sb

The pass git command operates on the repository associated with the password store.

When Git integration is enabled, commands such as pass generate, pass insert and pass rm can record changes automatically.

If you already have a Git repository with an established history, do not blindly reinitialize it or overwrite its remote.

6. Configuring GitHub SSH authentication

Check whether you already have a working SSH key:

ls -la ~/.ssh

ssh -T git@github.com

If no suitable key exists, generate a dedicated Ed25519 key:

ssh-keygen -t ed25519 \
    -f ~/.ssh/id_ed25519_pass_backup \
    -C "pass-backup"

Add its public key to your GitHub account under Settings / SSH and GPG keys.

Only upload the public key:

cat ~/.ssh/id_ed25519_pass_backup.pub

Never upload the private key.

If you created the dedicated key, configure SSH to select it:

nano ~/.ssh/config

Add a GitHub host entry:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_pass_backup
    IdentitiesOnly yes

Preserve any existing SSH configuration and adjust the host entry if you already use multiple GitHub identities.

Then:

chmod 600 ~/.ssh/config

ssh -T git@github.com

On the first connection, verify the GitHub host-key fingerprint against the official GitHub documentation before accepting it.

7. Creating an empty GitHub repository

Create a new private repository named, for example:

password-store-backup

Do not initialize it with a README, license or .gitignore. An empty repository simplifies the first encrypted push.

A private repository is useful as an additional access-control layer, but privacy settings are not the encryption mechanism used in this setup.

8. Configuring git-remote-gcrypt

This is the part that distinguishes the setup from simply pushing .gpg files to GitHub.

Inside the password store:

cd ~/.password-store

usuario_github="SEU_USUARIO_GITHUB"
repositorio_github="password-store-backup"
fingerprint_gpg="SEU_FINGERPRINT_GPG"

git remote add origin \
    "gcrypt::git@github.com:${usuario_github}/${repositorio_github}.git"

git config remote.origin.gcrypt-participants \
    "$fingerprint_gpg"

git config remote.origin.gcrypt-publish-participants \
    false

git config gcrypt.require-explicit-force-push \
    true

The gcrypt:: prefix tells Git to use the git-remote-gcrypt transport helper.

The participants setting identifies which GPG keys are allowed to read and authenticate the encrypted repository.

Publishing participant identities is disabled here to avoid unnecessarily exposing recipient key identifiers.

The final setting requires an explicit force push. There is a reason for this, explained below.

9. First encrypted push

For a newly created, empty GitHub repository:

cd ~/.password-store

git status -sb

git log -3 --oneline

git push --force -u origin main

Important: this first push assumes the remote repository is empty and belongs exclusively to this password store. Do not reuse this command blindly against an existing repository.

During the upload, git-remote-gcrypt encrypts the repository objects and creates a signed, encrypted remote manifest.

A successful execution should include messages similar to:

gcrypt: Encrypting to: ...
gcrypt: Requesting manifest signature

To github.com:USER/password-store-backup.git
 * [new branch] main -> main

At this point, GitHub stores the encrypted representation of the Git repository, rather than an ordinary readable Git history.

10. Synchronizing new passwords

Generate another test password:

pass generate -c laboratorio/segunda-conta 24

With Git integration enabled, pass records the encrypted file in the local repository.

But a successful local commit does not prove that the GitHub backup has been updated.

Always distinguish these states:

GPG encryption       -> Local password protected
Git commit           -> Local history updated
gcrypt push          -> Remote backup updated
gcrypt fetch         -> Remote history verified

For subsequent synchronization, first fetch the remote:

cd ~/.password-store

git fetch origin main

git status -sb

git log --oneline origin/main..main

Check that the remote branch is an ancestor of the local branch:

git merge-base --is-ancestor origin/main main \
    && echo "Historico compativel" \
    || echo "Historico divergente"

If the history is compatible, the remote has not changed concurrently, and you are certain no other client is writing to the same repository, the explicit push is:

git push --force origin main

Finally, fetch again and verify:

git fetch origin main
git status -sb

When both branches are synchronized:

## main...origin/main
About force push:

git-remote-gcrypt has a known limitation: its push implementation effectively behaves like a forced update. Requiring --force makes that behavior explicit but does not make concurrent writes safe. A fetch followed by an ancestry check still has a race window. For this reason, avoid simultaneous pushes from multiple devices and reconcile divergent histories before publishing.

11. The WSL / gpg-agent problem

One problem I ran into was intermittent failure to decrypt the remote manifest.

The error looked like this:

gcrypt: Decrypting manifest
gpg: public key decryption failed: No such file or directory
gpg: decryption failed: No such file or directory
gcrypt: Failed to decrypt manifest!

The interesting part was that the same GPG key could encrypt and decrypt local files. The secret keys were present, and the GPG agent was running.

So the first thing to check is not whether the key exists, but whether the key actually works:

gpg --list-secret-keys \
    --with-keygrip

export GPG_TTY="$(tty)"

gpg-connect-agent updatestartuptty /bye

A simple round-trip test:

fingerprint_gpg="SEU_FINGERPRINT_GPG"

printf 'teste de criptografia\n' |
    gpg --encrypt \
        --trust-model always \
        --recipient "$fingerprint_gpg" |
    gpg --decrypt

If the plaintext comes back, local encryption and decryption are working.

In my WSL environment, the runtime directory reported by the shell differed from the directory containing the actual GPG agent socket:

XDG_RUNTIME_DIR=/mnt/wslg/runtime-dir

GPG agent socket:
/run/user/1000/gnupg/S.gpg-agent

Running the remote operation with the Linux user runtime made the manifest decrypt successfully:

cd ~/.password-store

XDG_RUNTIME_DIR="/run/user/$(id -u)" \
    git ls-remote origin refs/heads/main

That was a successful diagnostic workaround in this environment, not a universal fix for every GPG error.

I would not globally overwrite XDG_RUNTIME_DIR in ~/.bashrc just to accommodate gcrypt. WSLg also uses its runtime directory for graphical integration.

If this specific workaround is necessary, apply it only to the Git commands involving gcrypt.

12. Configuring pinentry-curses

For terminal-based GPG authentication, configure pinentry-curses:

mkdir -p ~/.gnupg
chmod 700 ~/.gnupg

nano ~/.gnupg/gpg-agent.conf

Add or update the pinentry setting, avoiding duplicate pinentry-program directives:

pinentry-program /usr/bin/pinentry-curses
default-cache-ttl 28800
max-cache-ttl 86400

Restart the agent:

chmod 600 ~/.gnupg/gpg-agent.conf

gpgconf --kill gpg-agent
gpgconf --launch gpg-agent

export GPG_TTY="$(tty)"

gpg-connect-agent updatestartuptty /bye

These cache values determine how long the agent may retain authentication material. Shorter values reduce exposure on shared or unattended machines.

13. Do not blindly trust automatic hooks

I initially experimented with a Git post-commit hook to synchronize every password change automatically.

The problem is that a failed post-commit hook does not reverse the commit that already happened.

That means the terminal can display a successful password generation and local commit even though the remote sync failed.

[main abc1234] Add generated password
gcrypt: Failed to decrypt manifest!

Local commit: yes
Remote synchronization: no

For a password backup, silently assuming that the remote is synchronized is worse than requiring one extra command.

My preference is to keep the Git commit automatic but make the remote synchronization a separate, explicitly verified operation. If a hook is used, it must clearly report failures, retain pending commits and avoid unattended force pushes.

14. Restoring the password store on another machine

The most important requirement is not the GitHub account. It is access to the correct GPG private key.

On the new Linux machine, install the same tools:

sudo apt install -y \
    pass \
    gnupg \
    git \
    git-remote-gcrypt \
    openssh-client

Restore your GPG private key from a secure backup and configure GitHub SSH authentication.

Then clone the encrypted repository:

usuario_github="SEU_USUARIO_GITHUB"
repositorio_github="password-store-backup"

git clone \
    "gcrypt::git@github.com:${usuario_github}/${repositorio_github}.git" \
    "$HOME/.password-store"

The clone operation requires access to the corresponding GPG private key to decrypt the remote.

The restored .gpg-id file should already identify the intended GPG recipients. Do not unnecessarily reinitialize the store, because changing recipients can trigger reencryption of its entries.

Validate:

pass ls

git -C ~/.password-store status -sb

At this point the encrypted entries should be available, provided the correct private key was imported.

15. Backing up the private key

The GitHub repository is not a substitute for a GPG key backup. Losing the private key can make the encrypted repository permanently unreadable.

Store a protected backup outside GitHub and outside the password-store repository, preferably on encrypted offline media.

For example, export the key into a directory on removable encrypted storage:

fingerprint_gpg="SEU_FINGERPRINT_GPG"
diretorio_backup="/CAMINHO/DO/ARMAZENAMENTO-SEGURO"

umask 077

gpg --export-secret-keys \
    --output "$diretorio_backup/chave-privada.gpg" \
    "$fingerprint_gpg"

Only run this after replacing the backup path with an actual secure destination. Protect the exported file, keep an independent recovery copy and test restoration in a controlled environment.

Never commit exported secret keys to Git.

16. Security considerations

This setup protects the confidentiality of password entries and the repository contents stored remotely, but it does not solve every threat.

  • Compromise of the unlocked local machine can expose passwords.
  • A stolen GPG private key plus its passphrase can expose the backup.
  • Clipboard contents may be accessible to other local processes.
  • SSH authentication and GitHub permissions still matter.
  • Forced pushes can overwrite concurrent updates.
  • Remote deletion or account loss still requires independent backups.
  • GPG agent caching is a convenience/security trade-off.

Encrypted synchronization is not the same thing as complete endpoint security, and an encrypted GitHub repository is not a complete disaster-recovery strategy.

17. Final verification

A few commands are enough to verify the most important components:

echo "=== GPG ==="
gpg --list-secret-keys

echo "=== SSH ==="
ssh -T git@github.com

echo "=== PASSWORD STORE ==="
pass ls

echo "=== GIT STATUS ==="
git -C ~/.password-store status -sb

echo "=== REMOTE ==="
git -C ~/.password-store \
    ls-remote origin refs/heads/main

A valid remote branch and a clean synchronized Git status indicate that the encrypted remote is readable and the local branch is aligned with its remote-tracking reference.

If remote decryption fails, investigate that error before generating more commits or attempting a force push.

Conclusion

The final result is a terminal-based password manager with encrypted local entries, Git versioning, SSH authentication and an additional encryption layer for the remote repository.

What I like about this setup is that GitHub does not need to be trusted with the plaintext repository contents. The keys remain under my control, and the repository can be restored on another machine without depending on a proprietary password-manager backend.

What still matters is operational discipline: verify synchronization, maintain backups of the private keys, and avoid pretending that an automatic Git hook guarantees a successful remote upload.

The useful lesson wasn't just getting pass to work with GitHub. It was separating the different failure domains: GPG encryption, local Git history, SSH transport and encrypted remote synchronization.


References:
passwordstore.org
GnuPG
Git Documentation
git-remote-gcrypt
GitHub SSH Authentication

sábado, 19 de setembro de 2026

Debugging NordLynx: A Dead COM Class and a Self-Feeding Routing Loop

Reinstalled VMware Workstation over an old VMware Player install, and NordLynx - NordVPN's WireGuard interface - stopped coming up entirely. No adapter, no tunnel, nothing. The client just sat there retrying. Took a proper diagnostic pass to find out it wasn't actually a VPN problem at all - it was two unrelated local issues stacked on top of each other, and the second one only showed up once the first was fixed.

Execute:

~ # Get-PnpDevice -Class Net | Where-Object {$_.FriendlyName -match 'VMware|TAP|Nord|WireGuard|OpenVPN'} | Format-List Status,FriendlyName,Problem

Root Cause #1 - A Stale COM Registration:

That command turned up CM_PROB_NEED_CLASS_CONFIG (error 56) on the VMware, TAP and NordLynx adapters. Not a driver crash - the class installer itself couldn't finish configuring them. Digging into setupapi.dev.log showed repeated post-install timeouts, and NordVPN's Telio backend was throwing error 4319 trying to bring the tunnel interface up.

The actual fault was in the registry, not in any driver: HKLM\SOFTWARE\Classes\CLSID\{3d09c1ca-...}\InprocServer32 still pointed at vmware-network.dll under the old VMware Player path, which no longer existed after the Workstation install. Every class-configuration step for those adapters routes through that CLSID, so every one of them failed the same way - VMware's own virtual adapters, the TAP driver, and NordLynx, none of which have anything to do with each other except sharing that broken pointer.

~ # reg.exe export 'HKLM\SOFTWARE\Classes\CLSID\{3d09c1ca-2bcc-40b7-b9bb-3f3ec143a87b}' vmware-bridge-com-before.reg /y ~ # Set-Item -LiteralPath $key -Value 'C:\Program Files (x86)\VMware\VMware Workstation\vmnetbridge.dll' ~ # Restart-Service NetSetupSvc

Backed up the key first, confirmed the replacement DLL was actually signed before pointing anything at it, then restarted NetSetupSvc to force it to retry the pending class configuration. Eight seconds later, VMnet1, VMnet8, TAP and NordLynx all flipped from problem code 56 to CM_PROB_NONE in the same pass. One broken registry pointer had been quietly blocking every virtual adapter on the box.

Root Cause #2 - Feeding WireGuard Its Own Packets:

The adapter now existed, but the handshake still wouldn't complete. Pktmon capture showed the UDP/51820 handshake packets arriving back on NordLynx itself instead of going out the physical interface - the tunnel trying to route through itself, which obviously never finishes a handshake.

Turned out Windows was sharing the public Wi-Fi connection to the private one through ICS, which silently flips on IPv4 forwarding on the shared adapter. Combined with WireGuard-NT's known interaction between forwarding/WeakHostSend and interface selection via IP_PKTINFO - documented in the wireguard-nt TODO - the box ended up routing the tunnel's own outbound packets back into itself instead of out to the internet.

Confirmed the hypothesis first with a temporary /32 host route straight to the endpoint on the physical adapter - tunnel connected immediately, proving forwarding was the actual cause and not something else. Removed the test route right after, then fixed it properly: disabled forwarding on the shared adapter and turned off the ICS sharing itself, persisted with netsh after the first attempt through Set-NetIPInterface -PolicyStore PersistentStore failed silently on the policy store lookup.

~ # Set-NetIPInterface -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -Forwarding Disabled -PolicyStore ActiveStore

Validating It Wasn't A Fluke:

One clean connection doesn't rule out coincidence. Ran three separate connect cycles, each preceded by a confirmed disconnect, each one checking that the HTTPS request used to verify egress was actually bound to the tunnel's IPv4 address - not just "internet works," but "internet works specifically through NordLynx." Connect times: 6.44s, 4.02s, 4.80s. Last cycle independently confirmed exit country BR, São Paulo, and the client reporting protected: true.

Worth noting for anyone reading this as a kill-switch writeup instead of what it actually is: NordVPN's own kill switch was already disabled in config (InternetKillSwitch:IsEnabled=False), and stayed that way — nothing here touches it. What I did add is app-level: a startup script that checks for an Up adapter, a valid route, and a tunnel-bound HTTPS response before letting anything else launch, with a 10-second window and an independent watchdog that forces a disconnect if validation doesn't land in time. It's a local safety net for my own launch sequence, not a replacement for the client's kill switch.

What this actually was: Not a VPN bug. Not a driver bug either, really - a stale registry pointer left over from switching VMware editions, plus a Windows feature (ICS) doing exactly what it's designed to do in a context that broke WireGuard's routing assumptions. Two unrelated things, same symptom.

What I didn't touch: No generic network reset, no removing physical adapters, no reinstalling the VPN client, no permanent DNS or firewall changes. Firewall profiles and BFE stayed untouched throughout. Every registry key and interface state I changed got exported first - vmware-bridge-com-before.reg, ics-sharing-before.xml, the interface XML dumps - specifically so this is reversible if something regresses.

What's still open: VMware's bridged networking component is registered but vmnetbridge.sys is missing from the drivers folder, so bridged mode itself is still broken - separate from the COM fix, which only restored the configuration path, not the driver. Didn't chase that one down this time; NAT mode covers what I need for now.

quinta-feira, 2 de julho de 2026

Write-Up: Análise de Segurança e Engenharia Reversa em Aplicação React/Supabase







Neste artigo, documento o processo de análise de segurança e auditoria técnica realizado em uma aplicação web moderna baseada em React (Vite) no frontend e Supabase / Vercel na infraestrutura. O objetivo foi mapear a superfície de ataque exposta e validar os controles de autenticação, autorização e persistência de dados.

1. Reconhecimento Externo e Infraestrutura (Black-Box)

O teste foi iniciado por um reconhecimento externo da aplicação, sem a utilização de credenciais. A análise das respostas HTTP permitiu identificar o seguinte cenário:

  • Hospedagem e Backend: Aplicação hospedada na Vercel com backend gerenciado pelo Supabase.

  • Criptografia em Trânsito: Redirecionamento forçado de HTTP para HTTPS ativo, com cifras TLS válidas.

  • Ausência de Cabeçalhos Defensivos (Hardening): O servidor falha em omitir ou configurar cabeçalhos de segurança cruciais, deixando a aplicação sem as seguintes proteções:

    • Content-Security-Policy (CSP)

    • X-Frame-Options (Proteção contra Clickjacking/carregamento em iframe)

    • X-Content-Type-Options

    • Referrer-Policy

    • Permissions-Policy

2. Análise de Código Fonte Cliente (React/Vite)

Por se tratar de um build em React estruturado via Vite, boa parte da lógica de negócio do frontend estava exposta nos bundles de produção do JavaScript público. A varredura estática nesses arquivos revelou:

  • Mapeamento de Endpoints: Identificação das rotas /api/auth/signup, /api/auth/event, /api/auth/admin-create-user e /api/ai.

  • Mapeamento de Banco de Dados: Exposição dos nomes de tabelas internas como profiles, authorized_users, generated_contents, term_plans e teacher_schools.

  • Vazamento de Metadados: Exposição de informações internas de desenvolvimento no lado do cliente, incluindo metadados de build, repositório Git, hashes de commits e identificadores internos da Vercel.

  • Service Worker: O arquivo de service worker expunha caminhos para scripts de teste, páginas de recuperação de ambiente, bundles depreciados e arquivos de diagnóstico, fornecendo mais inteligência sobre a estrutura do banco.

3. Falha de Provisionamento de Recursos

Para testar a superfície autenticada, foi criada uma conta comum de testes sob o nome de Gentoober HCK. Após a validação do e-mail direto pelo Supabase, observou-se uma falha de lógica de negócios no provisionamento:

⚠️ Falha de Escopo: A nova conta comum recebeu, de forma automatizada e sem contrapartida financeira, o plano GOLD, 9.999 créditos e acesso irrestrito a todas as funcionalidades do sistema. Qualquer usuário mal-intencionado poderia automatizar a criação de contas para inflacionar o consumo de recursos computacionais.

4. Quebra de Isolamento: Row Level Security (RLS) no Supabase

O Supabase delega o controle de acesso diretamente ao banco de dados através de políticas de Row Level Security (RLS). Testou-se a eficácia dessas políticas utilizando o token de sessão da conta comum (Gentoober HCK).

Leitura Horizontal Indevida

A conta de teste não possuía nenhum conteúdo próprio associado. Ao remover os filtros de proprietário nas requisições da API, o banco permitiu a leitura horizontal de dados de terceiros:

  • Exposição: Foi possível ler os UUIDs, tipos e datas de 45 registros de conteúdos gerados, 3 planejamentos e 2 vínculos de professores.

Escrita e Exclusão Arbitrária (Bypass Completo)

A falha de RLS mostrou-se bidirecional. Foi possível injetar um registro sintético de teste na tabela generated_contents apontando o UUID de outro usuário como proprietário (Retorno HTTP 201). Posteriormente, utilizando a mesma conta comum, foi possível deletar o marcador sintético.

Nota de Segurança: O teste comprovou que um atacante poderia ler, inserir e apagar registros no contexto de qualquer usuário da aplicação. Nenhum dado legítimo foi alterado durante a validação.

5. Atribuição em Massa (Mass Assignment)

Testou-se a capacidade de alterar campos privilegiados do perfil através do token comum.

  • Controle Positivo: Tentativas de alterar a role para admin ou definir is_admin como true foram rejeitadas por uma regra severa que valida os e-mails administrativos na origem.

  • Controle Negativo (Falha): Campos financeiros e de controle de consumo não possuíam a mesma validação. Foi possível atualizar diretamente os campos credits para 1.000.000 e is_unlimited para true, obtendo recursos infinitos a partir do contexto do cliente.

6. Vazamento de Credenciais de Alta Gravidade (Tomada de Conta)

Ao consultar a tabela authorized_users utilizando o token do usuário comum, a API retornou indevidamente os registros de contas administrativas.

O sistema apresentou uma falha grave de armazenamento de segredos:

  • Vulnerabilidade: A tabela expôs o e-mail do administrador, seu papel no sistema e sua access_key armazenada em texto claro (plain text).

  • Impacto: Utilizando a chave obtida diretamente no endpoint oficial do Supabase, obteve-se uma sessão válida (HTTP 200), confirmando o comprometimento completo do perfil administrativo (role=admin / is_admin=true).

A validação foi corroborada pela execução bem-sucedida da função RPC restrita get_all_profiles_secure, que antes rejeitava o usuário comum e, sob a nova sessão, retornou o contador exato de 19 perfis cadastrados.

7. Desconexão de Lógica: Fluxo de Senhas

Analisando o comportamento do frontend, detectou-se uma falha de sincronia na arquitetura de autenticação:

  • O login da aplicação utiliza o módulo nativo do Supabase (signInWithPassword).

  • No entanto, a tela de alteração de senha atualiza exclusivamente o campo access_key na tabela customizada authorized_users.

Consequência: A interface reporta ao usuário que a credencial foi alterada com sucesso, mas a senha antiga mantida pelo módulo de autenticação do Supabase permanece ativa e funcional, inviabilizando a revogação real de acessos comprometidos.

8. Abuso de APIs Públicas e Vetores de Custo

Proxy de Inteligência Artificial Sem Autenticação

O endpoint /api/ai processa as requisições enviadas aos modelos de inteligência artificial. Testes sem o envio de cabeçalhos de autorização (Authorization Token) demonstraram que a API aceita requisições anônimas, retornando HTTP 200 e gerando o conteúdo processado.

  • Risco Comercial: Aliado a uma política de CORS permissiva (Access-Control-Allow-Origin: *), qualquer agente externo pode utilizar o endpoint como um proxy gratuito de IA, transferindo todo o custo financeiro do consumo de tokens para o dono da aplicação.

Injeção de Logs de Eventos

O endpoint /api/auth/event aceita o envio de eventos de autenticação (como logins) de forma anônima e sem validação de integridade. Isso viabiliza a inserção em massa de registros falsos, inutilizando logs para auditoria Forense ou tratamento de incidentes.

9. Varredura Automatizada e Falsos Positivos

Uma varredura automatizada de escopo estrito (focada em configurações de TLS e cabeçalhos) confirmou a ausência das defesas de hardening citadas no item 1.

A ferramenta apontou a ausência do cabeçalho HSTS (HTTP Strict Transport Security). Contudo, a validação manual via curl -I comprovou que o cabeçalho estava sendo enviado corretamente pelo servidor da Vercel, caracterizando o alerta da ferramenta como um falso positivo.

Conclusão e Recomendações

A aplicação possui sérias fragilidades estruturais, principalmente na camada de persistência (Supabase) devido à falta de isolamento por RLS, uso de chaves em texto claro e falta de validação em funções de proxy no backend. A correção imediata exige a reestruturação das políticas de banco de dados e a migração de segredos para variáveis de ambiente seguras.



domingo, 27 de agosto de 2023

Running a "stealth" ssh session (Stealth SSH)

Had an authorized assessment where I needed to hop in and out of a bunch of machines fast, without stacking unknown hosts in my known_hosts and without the terminal complaining about color or size every time i dropped into some minimal shell. One line fixed it.

Run:


~ # ssh -tt \ -o UserKnownHostsFile=/dev/null \ -o StrictHostKeyChecking=no \ user@host 'TERM=xterm-256color exec bash -i'

How this command works:
  1. -tt → forces double pseudo-terminal allocation. gives you a full terminal — color, resizing, interactive commands — even against shells that normally choke on TTY.
  2. -o UserKnownHostsFile=/dev/null → tells SSH not to write anything to known_hosts. no local trail piling up from every test box you touch.
  3. -o StrictHostKeyChecking=no → skips host key checking. worth a pause here: this check exists specifically to catch man-in-the-middle attacks, so this flag turns off the one thing that would warn you if the connection was being intercepted. only makes sense on a network you already trust — authorized test environments, or internal automation against hosts that rotate IPs often enough that babysitting known_hosts isn't worth it.
  4. 'TERM=xterm-256color exec bash -i' → sets a full color terminal and drops straight into an interactive bash, bypassing whatever default shell the server has configured.

one thing worth being straight about, since "stealth" in the title oversells it a bit: this only clears your side of the trail — your local known_hosts. nothing changes on the server. auth.log logs the login normally, last shows the session, and remote shell history stays on unless you handle that separately. real stealth means thinking about both ends of the connection, not just the client.

When to use it: pentesting / red team work, so you don't pollute known_hosts jumping between client environments. automation that needs a clean interactive shell. lab environments where IPs rotate often enough that host key checking is more friction than protection.

Other considerations: only use this on authorized networks, no exceptions. prefer key-based auth over passwords, always. on the server side, set up Match in sshd_config to limit what each account can actually run. for a session that survives a dropped connection, pair this with tmux or screen on the remote end.

sexta-feira, 25 de agosto de 2023

Encrypted swap-file

Everyone swaps laptops eventually and forgets one detail: disk encryption doesn't cover swap. You encrypt the whole root partition, sleep fine, then forget the kernel dumps memory pages into an unencrypted file the moment RAM gets tight. If someone grabs your disk after a hibernate, or even after a heavy session that forced swap, that data is sitting there, plain.

Here's how I closed that gap on my own [Gentoo] setup.

Execute:


~ # dd bs=4M count=2560 if=/dev/zero of=swapfile conv=fsync oflag=direct status=progress && chattr +C swapfile && \ lsattr swapfile && chmod 0600 swapfile && ls -l swapfile && cryptsetup luksFormat swapfile ~ # cryptsetup luksOpen swapfile swap_crypt && mkswap /dev/mapper/swap_crypt && swapon /dev/mapper/swap_crypt

How this command works:

on systems with strong privacy requirements, running swap on disk without encryption is a real risk (RAM data exposed on hibernation or physical extraction).

  1. dd bs=4M count=2560 ... → creates a 10GB file (block size × count = total size, adjust count for whatever size you need).
  2. chattr +C swapfile → disables Copy-on-Write. this only does anything on Btrfs — on ext4 the command runs and silently does nothing, so check your filesystem first instead of trusting the flag blindly.
  3. chmod 0600 → strict permissions (rw for the owner only).
  4. cryptsetup luksFormat → creates an encrypted LUKS container.
  5. cryptsetup luksOpen + mkswap + swapon → opens it, formats it as swap, and activates it.

Advantages: protects in-memory data against cold boot attacks and disk forensics — anyone pulling the drive lands on ciphertext instead of raw pages.

Risks: performance overhead from encryption (more noticeable on spinning disks than SSDs) and extra complexity at boot.

To make it persistent: configure it in /etc/crypttab and /etc/fstab (Gentoo/OpenRC) or set up a systemd unit. either way, the LUKS container has to be open before swapon runs — that ordering is the part that actually breaks if you get it wrong.

pass + GPG + git-remote-gcrypt: Encrypted Password Store Sync with GitHub

The idea was simple: keep my passwords in the terminal with pass , version the encrypted files with Git, and maintain an encrypted backu...