Skip to content

Instantly share code, notes, and snippets.

@maple3142
Last active September 16, 2024 08:18
Show Gist options
  • Save maple3142/e46ab5ce8697476db13b4d9dc0b32f64 to your computer and use it in GitHub Desktop.
Save maple3142/e46ab5ce8697476db13b4d9dc0b32f64 to your computer and use it in GitHub Desktop.
poor man's ngrok with cloudflared and mitmproxy

Poor man's ngrok

Prequisites

  • zsh
  • python3
  • tmux
  • cloudflared
  • mitmproxy

Create tunnel

You can skip this if you want to use *.trycloudflare.com free subdomain.

CF_TUNNEL=ctf
cloudflared login
cloudflared tunnel create "$CF_TUNNEL"
cloudflared tunnel route dns "$CF_TUNNEL" "$YOUR_SUBDOMAIN"

Install

Put this into your ~/.zshrc:

if (( $+commands[python3] && $+commands[tmux] && $+commands[cloudflared] && $+commands[mitmweb] )) then
    tunnel() {
        CF_TUNNEL=ctf  # leave blank if you want to use *.trycloudflare.com
        TUNNEL_CMD=$([[ $CF_TUNNEL = "" ]] && echo "" || echo "run $CF_TUNNEL")
        if [[ $# -eq 1 ]]; then
            host='localhost'
            port=$1
        elif [[ $# -eq 2 ]]; then
            host=$1
            port=$2
        else
            echo "Syntax: $0 [port] or $0 [host] [port]"
            return 1
        fi
        sess="tunnel-$host-$port"
        if tmux has-session -t $sess >/dev/null 2>&1; then
            tmux at -t $sess
            return 0
        fi
        proxy_port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1])')
        tmux new -s "$sess" \
            "mitmweb --mode reverse:http://$host:$port -p $proxy_port --no-web-open-browser --web-port 4040"\; \
            split-window -v \
            "cloudflared tunnel --url http://localhost:$proxy_port $TUNNEL_CMD"\; \
            split-window -v \
            "zsh -c 'echo Press enter to stop; read; tmux kill-session'"\; \
            select-layout even-vertical
    }
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment