Skip to content

Instantly share code, notes, and snippets.

@M1ndBlast
Last active February 4, 2026 18:12
Show Gist options
  • Select an option

  • Save M1ndBlast/45d1c21a1d8aa3dfe81dd9fba543b8b9 to your computer and use it in GitHub Desktop.

Select an option

Save M1ndBlast/45d1c21a1d8aa3dfe81dd9fba543b8b9 to your computer and use it in GitHub Desktop.
PROXY SOCKS5
Host proxy
HostName ec2-54-185-246-184.us-west-2.compute.amazonaws.com
User MYUSER
IdentityFile "C:\Users\M1ndBlast\.ssh\MYUSER_key.pem"
set -euo pipefail
# 0) Crear usuario con home y shell normal
sudo useradd -m -s /bin/bash MYUSER
# 1) Bloquear password (solo llaves)
sudo passwd -l MYUSER >/dev/null
# 2) Crear carpeta .ssh y authorized_keys (propiedad del usuario)
sudo install -d -m 700 -o MYUSER -g MYUSER /home/MYUSER/.ssh
sudo tee /home/MYUSER/.ssh/authorized_keys >/dev/null <<'EOF'
[put pub file]
EOF
sudo chown MYUSER:MYUSER /home/MYUSER/.ssh/authorized_keys
sudo chmod 600 /home/MYUSER/.ssh/authorized_keys
# 3) Asegurar que no tenga sudo (Ubuntu: sudo, RHEL: wheel)
sudo deluser MYUSER sudo 2>/dev/null || true
sudo gpasswd -d MYUSER wheel 2>/dev/null || true
# 4) (Opcional pero recomendado) Forzar que este usuario use solo llaves
# No toca forwarding ni nada, solo bloquea password para ESTE usuario.
if ! sudo grep -qE '^Match User MYUSER$' /etc/ssh/sshd_config; then
sudo tee -a /etc/ssh/sshd_config >/dev/null <<'EOF'
Match User MYUSER
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
EOF
fi
# 5) Validar y recargar SSH
sudo sshd -t
sudo systemctl reload ssh 2>/dev/null || sudo systemctl reload sshd 2>/dev/null || sudo systemctl restart ssh || sudo systemctl restart sshd
echo "OK: usuario 'MYUSER' creado con acceso por llave y sin sudo."
param(
[Parameter(HelpMessage="Especifica la acción a realizar: on, off, reset, status (default: status)")]
[ValidateSet("on", "off", "reset", "status", IgnoreCase=$true)]
[string]$action = "status"
)
$sshhost = "proxy"
$socksport = 8888
$httpport = 7777
$envfile = Join-Path $HOME ".proxy_env.ps1"
$socksserver = "socks5://127.0.0.1:$socksport"
$httpserver = "http://127.0.0.1:$httpport"
$sshargs = "-C -N -D 0.0.0.0:$socksport $sshhost"
$pproxyargs = "-l $httpserver -r $socksserver"
$regpath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
$bypass = @(
# GS
"*.socio.gs",
"*.colaboracionsimba.net",
"3.12.57.198",
"*.onuriscp.com",
# Google Cloud
"*.googleapis.com",
"*.genai.googleapis.com",
# JetBrains
"*.jetbrains.com",
# "*.github.com",
# Port forwarding
#"*.ngrok.io",
# Office
"*.cloud.microsoft",
"*.static.microsoft",
"*.usercontent.microsoft",
"login.microsoftonline.com",
"*.login.microsoftonline.com",
"*.aadcdn.msftauth.net",
"*.msauth.net",
"officecdn.microsoft.com",
"officecdn-microsoft-com.akamaized.net",
# Whatsapp (con proxy no permite envio multimedia)
"*.whatsapp.com",
"*.whatsapp.net",
# Local intranet
"<local>",
"localhost",
"127.0.0.1",
"::1"
) -join ";"
function Get-SshTunnelProcess {
Get-CimInstance Win32_Process -Filter "Name = 'ssh.exe'" -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -like "*$sshargs*" }
}
function Get-PProxyProcess {
Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -like "*pproxy*" -and $_.CommandLine -like "*$pproxyargs*" }
}
function Start-SshTunnel {
if (Get-SshTunnelProcess) {
Write-Host "SSH ya está activo."
} else {
Write-Host "Iniciando túnel SSH a $socksserver..."
Start-Process -FilePath "ssh" `
-ArgumentList $sshargs `
-WindowStyle Hidden `
-RedirectStandardOutput "$env:TEMP\ssh.log" `
-RedirectStandardError "$env:TEMP\ssh.err.log"
}
}
function Start-PProxy {
if (Get-PProxyProcess) {
Write-Host "PPROXY ya está activo."
} else {
Write-Host "Iniciando pproxy en $httpserver..."
Start-Process -FilePath "conda" `
-ArgumentList "run -n base pproxy $pproxyargs" `
-WindowStyle Hidden `
-RedirectStandardOutput "$env:TEMP\pproxy.log" `
-RedirectStandardError "$env:TEMP\pproxy.err.log"
}
}
function Stop-SshTunnel {
Write-Host "Deteniendo SSH..."
$procs = Get-SshTunnelProcess
if ($procs) {
$procs | ForEach-Object {
try {
Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
} catch {}
}
}
}
function Stop-PProxy {
Write-Host "Deteniendo pproxy..."
$procs = Get-PProxyProcess
if ($procs) {
$procs | ForEach-Object {
try {
Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
} catch {}
}
}
}
function Set-WinInetProxy {
# Checar si los properties existen
if ((Get-ItemProperty -Path $regpath -Name ProxyEnable -ErrorAction SilentlyContinue).ProxyEnable -eq 1 -and
(Get-ItemProperty -Path $regpath -Name ProxyServer -ErrorAction SilentlyContinue).ProxyServer -eq $socksserver -and
(Get-ItemProperty -Path $regpath -Name ProxyOverride -ErrorAction SilentlyContinue).ProxyOverride -eq $bypass) {
Write-Host "Configuración del proxy ya existe en el registro."
return
}
Set-ItemProperty -Path $regpath -Name ProxyEnable -Value 1 -Type DWord
Set-ItemProperty -Path $regpath -Name ProxyServer -Value $socksserver
Set-ItemProperty -Path $regpath -Name ProxyOverride -Value $bypass
Write-Host "Proxy del sistema configurado: $socksserver"
}
function Unset-WinInetProxy {
if ((Get-ItemProperty -Path $regpath -Name ProxyEnable -ErrorAction SilentlyContinue).ProxyEnable -eq 0) {
Write-Host "El proxy del sistema ya está deshabilitado."
return
}
# Deshabilitar proxy
Set-ItemProperty -Path $regpath -Name ProxyEnable -Value 0 -Type DWord
try {
Remove-ItemProperty -Path $regpath -Name ProxyServer -ErrorAction SilentlyContinue
Remove-ItemProperty -Path $regpath -Name ProxyOverride -ErrorAction SilentlyContinue
} catch {}
Write-Host "Proxy del sistema deshabilitado."
}
function Set-EnvProxy {
$env:HTTP_PROXY = $httpserver
$env:HTTPS_PROXY = $httpserver
$env:NO_PROXY = $bypass -replace ';', ','
# Generar archivo para reutilizar en otras sesiones
$envcontent = @"
`$env:HTTP_PROXY = '$httpserver'
`$env:HTTPS_PROXY = '$httpserver'
`$env:NO_PROXY = '$($bypass -replace ';', ',')'
"@
Set-Content -Path $envfile -Value $envcontent -Encoding UTF8
Write-Host "Variables de entorno HTTP_PROXY y HTTPS_PROXY configuradas a $httpserver"
}
function Unset-EnvProxy {
Remove-Item Env:HTTP_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:HTTPS_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:NO_PROXY -ErrorAction SilentlyContinue
# Eliminar archivo de entorno si existe
if (Test-Path $envfile) {
Remove-Item $envfile -ErrorAction SilentlyContinue
}
Write-Host "Variables de entorno HTTP_PROXY, HTTPS_PROXY y NO_PROXY eliminadas."
}
function Show-Status {
Write-Host "=== PROXY SETTINGS ==="
$proxyStatus = Get-ItemProperty -Path $regpath | Select-Object ProxyEnable, ProxyServer, ProxyOverride
$proxyStatus | Format-List
Write-Host "=== PROXY SERVERS ==="
$sshProc = Get-SshTunnelProcess
if ($sshProc) {
Write-Host "SSH: ACTIVE $socksserver (PID: $($sshProc.ProcessId))"
} else {
Write-Host "SSH: INACTIVE"
}
$pproxyProc = Get-PProxyProcess
if ($pproxyProc) {
Write-Host "PPROXY: ACTIVE $httpserver (PID: $($pproxyProc.ProcessId))"
} else {
Write-Host "PPROXY: INACTIVE"
}
#archivo
if (Test-Path $EnvFile) {
Write-Host "ENV FILE: EXISTS (PATH: $EnvFile)"
} else {
Write-Host "ENV FILE: NO EXISTS."
}
Write-Host "======================="
}
switch ($Action) {
"on" {
Write-Host "Activando proxy..."
Start-SshTunnel
Start-PProxy
Set-WinInetProxy
Set-EnvProxy
}
"off" {
Write-Host "Desactivando proxy..."
Stop-PProxy
Stop-SshTunnel
Unset-WinInetProxy
Unset-EnvProxy
}
"reset" {
Write-Host "Reseteando proxy..."
Stop-PProxy
Stop-SshTunnel
Start-SshTunnel
Start-PProxy
Set-WinInetProxy
Set-EnvProxy
}
"status" {
Show-Status
}
default {
Write-Host "Uso: .\toggle-socks-proxy.ps1 -Action {on|off|reset|status}"
exit 1
}
}
#!/usr/bin/env bash
set -Eeuo pipefail
ACTION="${1:-status}"
FLAG="${2:-}"
BIND_ADDR="${3-127.0.0.1}"
if [[ "$FLAG" == "--all" ]]; then
BIND_ADDR="0.0.0.0"
elif [[ "$FLAG" == "--bind" ]]; then
BIND_ADDR="${BIND_ADDR:-127.0.0.1}"
else
BIND_ADDR="127.0.0.1"
fi
SSH_HOST="${SSH_HOST:-proxy}" # Host en ~/.ssh/config
SOCKS_PORT="${SOCKS_PORT:-8888}" # SOCKS local
HTTP_PORT="${HTTP_PORT:-7777}" # HTTP local (pproxy)
ENV_FILE="${ENV_FILE:-$HOME/.proxy_env}"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/proxy-toggle"
LOG_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/proxy-toggle/logs"
SSH_PID_FILE="$STATE_DIR/ssh.pid"
PPROXY_PID_FILE="$STATE_DIR/pproxy.pid"
NO_PROXY_LIST="${NO_PROXY_LIST:-localhost,127.0.0.1,::1,*.socio.gs,*.colaboracionsimba.net,*.onuriscp.com,10.57.113.51,*.googleapis.com,*.genai.googleapis.com,*.jetbrains.com,*.cloud.microsoft,*.static.microsoft,*.usercontent.microsoft,login.microsoftonline.com,*.login.microsoftonline.com,*.aadcdn.msftauth.net,*.msauth.net}"
mkdir -p "$STATE_DIR" "$LOG_DIR"
usage() {
cat <<EOF
Uso: $0 [--all] [--bind <ip>] {on|off|reset|status|env}
Acciones: on | off | reset | status | env
- on Arranca túnel SSH + pproxy y configura env/GNOME
- off Detiene ambos y limpia configuración
- reset off + on
- status Muestra estado
- env Imprime exports (para: eval "\$($0 env)")
Flags:
--all Expone el proxy en todas las interfaces (bind 0.0.0.0)
--bind <ip> Bind explícito (ej. 127.0.0.1, 0.0.0.0, 192.168.1.50)
Vars opcionales:
SSH_HOST SOCKS_PORT HTTP_PORT BIND_ADDR ENV_FILE NO_PROXY_LIST
EOF
}
is_running_pidfile() {
local pidfile="$1"
[[ -f "$pidfile" ]] || return 1
local pid
pid="$(cat "$pidfile" 2>/dev/null || true)"
[[ -n "${pid:-}" ]] || return 1
kill -0 "$pid" 2>/dev/null
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || {
echo "Falta comando requerido: $1" >&2
return 1
}
}
start_ssh_tunnel() {
require_cmd ssh
if is_running_pidfile "$SSH_PID_FILE"; then
echo "SSH túnel: ya activo (PID $(cat "$SSH_PID_FILE"))."
return 0
fi
echo "Iniciando túnel SSH a $SSH_HOST en $BIND_ADDR:$SOCKS_PORT..."
# ExitOnForwardFailure evita “creo que levantó” cuando no levantó.
ssh -f -N -C \
-D "$BIND_ADDR:$SOCKS_PORT" \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=60 \
-o ServerAliveCountMax=3 \
"$SSH_HOST"
# Obtener PID: pgrep acotado al puerto y bind (mejorable con ControlMaster, pero sirve)
local pid
pid="$(pgrep -f "ssh.*-D ${BIND_ADDR}:${SOCKS_PORT}.*${SSH_HOST}" | head -n1 || true)"
[[ -n "$pid" ]] || { echo "No pude detectar el PID del túnel SSH." >&2; return 1; }
echo "$pid" > "$SSH_PID_FILE"
}
stop_ssh_tunnel() {
if is_running_pidfile "$SSH_PID_FILE"; then
local pid
pid="$(cat "$SSH_PID_FILE")"
echo "Deteniendo SSH túnel (PID $pid)..."
kill "$pid" 2>/dev/null || true
fi
rm -f "$SSH_PID_FILE"
}
start_pproxy() {
# Preferir pproxy directo; si no, intentar con conda o python.
local cmd=()
if command -v pproxy >/dev/null 2>&1; then
cmd=(pproxy)
elif command -v conda >/dev/null 2>&1; then
cmd=(conda run -n base pproxy)
elif command -v python >/dev/null 2>&1; then
cmd=(python -m pproxy)
else
echo "No encontré 'pproxy' ni 'conda'. Instala pproxy o ajusta el comando." >&2
return 1
fi
if is_running_pidfile "$PPROXY_PID_FILE"; then
echo "pproxy: ya activo (PID $(cat "$PPROXY_PID_FILE"))."
return 0
fi
echo "Iniciando pproxy en $BIND_ADDR:$HTTP_PORT (-> socks5://$BIND_ADDR:$SOCKS_PORT)..."
local logfile="$LOG_DIR/pproxy.log"
"${cmd[@]}" \
-l "http://$BIND_ADDR:$HTTP_PORT" \
-r "socks5://$BIND_ADDR:$SOCKS_PORT" \
>>"$logfile" 2>&1 &
echo $! > "$PPROXY_PID_FILE"
}
stop_pproxy() {
if is_running_pidfile "$PPROXY_PID_FILE"; then
local pid
pid="$(cat "$PPROXY_PID_FILE")"
echo "Deteniendo pproxy (PID $pid)..."
kill "$pid" 2>/dev/null || true
fi
rm -f "$PPROXY_PID_FILE"
}
write_env_file() {
cat > "$ENV_FILE" <<EOF
export HTTP_PROXY=http://$BIND_ADDR:$HTTP_PORT
export HTTPS_PROXY=http://$BIND_ADDR:$HTTP_PORT
export ALL_PROXY=socks5://$BIND_ADDR:$SOCKS_PORT
export NO_PROXY="$NO_PROXY_LIST"
export http_proxy=http://$BIND_ADDR:$HTTP_PORT
export https_proxy=http://$BIND_ADDR:$HTTP_PORT
export all_proxy=socks5://$BIND_ADDR:$SOCKS_PORT
export no_proxy="$NO_PROXY_LIST"
EOF
}
apply_gnome_proxy() {
command -v gsettings >/dev/null 2>&1 || return 0
# Si el schema no existe, no hacemos nada.
gsettings list-schemas | grep -q '^org.gnome.system.proxy$' || return 0
echo "Configurando proxy GNOME (si aplica)..."
gsettings set org.gnome.system.proxy mode 'manual'
gsettings set org.gnome.system.proxy.socks host "$BIND_ADDR"
gsettings set org.gnome.system.proxy.socks port "$SOCKS_PORT"
# ignore-hosts espera lista tipo "['a','b']"
local formatted
formatted=$(printf "['%s']" "$(echo "$NO_PROXY_LIST" | sed "s/,/','/g")")
gsettings set org.gnome.system.proxy ignore-hosts "$formatted"
}
disable_gnome_proxy() {
command -v gsettings >/dev/null 2>&1 || return 0
gsettings list-schemas | grep -q '^org.gnome.system.proxy$' || return 0
echo "Desactivando proxy GNOME..."
gsettings set org.gnome.system.proxy mode 'none'
}
set_env_proxy() {
write_env_file
apply_gnome_proxy
echo "ENV listo en $ENV_FILE. Para aplicarlo en la terminal actual:"
echo " source \"$ENV_FILE\""
}
unset_env_proxy() {
disable_gnome_proxy
rm -f "$ENV_FILE"
echo "ENV eliminado ($ENV_FILE)."
}
print_env() {
# Útil para: eval "$($0 env)"
cat <<EOF
export HTTP_PROXY=http://$BIND_ADDR:$HTTP_PORT
export HTTPS_PROXY=http://$BIND_ADDR:$HTTP_PORT
export ALL_PROXY=socks5://$BIND_ADDR:$SOCKS_PORT
export NO_PROXY="$NO_PROXY_LIST"
export http_proxy=http://$BIND_ADDR:$HTTP_PORT
export https_proxy=http://$BIND_ADDR:$HTTP_PORT
export all_proxy=socks5://$BIND_ADDR:$SOCKS_PORT
export no_proxy="$NO_PROXY_LIST"
EOF
}
status_proxy() {
echo "=== Estado del proxy ==="
echo "SSH túnel: $(is_running_pidfile "$SSH_PID_FILE" && echo "ACTIVO (PID $(cat "$SSH_PID_FILE"))" || echo "INACTIVO")"
echo "pproxy: $(is_running_pidfile "$PPROXY_PID_FILE" && echo "ACTIVO (PID $(cat "$PPROXY_PID_FILE"))" || echo "INACTIVO")"
echo "ENV file: $ENV_FILE $([[ -f "$ENV_FILE" ]] && echo "(existe)" || echo "(no existe)")"
echo "Bind: $BIND_ADDR SOCKS:$SOCKS_PORT HTTP:$HTTP_PORT"
}
case "$ACTION" in
on)
start_ssh_tunnel
start_pproxy
set_env_proxy
;;
off)
stop_pproxy
stop_ssh_tunnel
unset_env_proxy
;;
reset)
stop_pproxy
stop_ssh_tunnel
start_ssh_tunnel
start_pproxy
set_env_proxy
;;
env)
print_env
;;
status)
status_proxy
;;
*)
usage
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment