使用ngrok突破防火牆或NAT限制
自建ngrok服務器
### 編譯 ngrokd (Server) , ngrok (Client)
- 下載 ngrok 原始碼
1 2 cd /usr/src/ git clone https://github.com/inconshreveable/ngrok
- 使用openssl 建立 SSL 憑證(自簽)
1 2 3 4 5 openssl genrsa -out rootCA.key 2048 openssl req -new -x509 -nodes -key rootCA.key -days 10000 -subj "/CN=ngrok.aligogo.pw" -out rootCA.pem openssl genrsa -out server.key 2048 openssl req -new -key server.key -subj "/CN=ngrok.aligogo.pw" -out server.csr openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -days 10000 -out server.crt
- 分別複製 憑證及key到 此目錄下的server及client
1 2 3 cp -p rootCA.pem assets/client/tls/ngrokroot.crt cp -p server.key assets/server/tls/snakeoil.key cp -p server.crt assets/server/tls/snakeoil.crt
編譯。 編譯完在 /usr/src/ngrok/bin/1 2 make release-server make release-client
注意: 編譯 ARM 客戶端 (手機用) GOOS=linux GOARCH=arm make release-client 編譯 Mac 客戶端 (Macbook用) GOOS=darwin GOARCH=amd64 make release-client 編譯 windows 客戶端 (電腦用) GOOS=windows GOARCH=amd64 make release-client 或是 GOOS=windows GOARCH=386 make release-client
在Server端BB 啟動(Centos6_x86_64)
### ngrokd
- 啟動ngrokd。指定 httpAddr、httpsAddr 分別是 ngrok 用來轉發 http、https 服務的端口
1 ./ngrokd -domain="ngrok.aligogo.pw" -httpAddr=":8081" -httpsAddr=":8082"
另外,ngrokd 預設還會開一個 4443 port 用來跟客戶端通訊 (可以使用 此參數指定 -tunnelAddr=”:xxx”), 將 tcp 8081 ,8082 ,4443, 22222 加入防火牆
1 2 3 4 iptables -I INPUT 5 -p tcp --dport 4443 -j ACCEPT iptables -I INPUT 5 -p tcp --dport 8081 -j ACCEPT iptables -I INPUT 5 -p tcp --dport 8082 -j ACCEPT iptables -I INPUT 5 -p tcp --dport 22222 -j ACCEPT
在Client端 AA (Centos6_x86_64) 啟動ngrok去連接 ngrok.aligogo.pw:4443
- 目標: 讓外部能連接內部 sshd
- 在 Client AA 先確定是否有開啟 sshd
與 ngrok 同目錄建立 ngrok.cfg (Server 防火牆要開 port (ex. 58800 (供RDP轉送)、22222 (供SSH轉送)))1 2 3 4 5 6 7 8 9 10 11 server_addr: "ngrok.aligogo.pw:4443" trust_host_root_certs: false tunnels: rdp: remote_port: 58800 proto: tcp: 3389 ssh: remote_port: 22222 proto: tcp: 22
啟動 ngrok
1 ./ngrok -config=./ngrok.cfg start ssh
1 2 3 4 5 6 7 8 ngrok (Ctrl+C to quit) Tunnel Status online Version 1.7/1.7 Forwarding tcp://ngrok.aligogo.pw:22222 -> 127.0.0.1:22 Web Interface 127.0.0.1:4040 # Conn 0 Avg Conn Time 0.00ms
1 ssh -p 22222 ngrok.aligogo.pw
在Client端CC (Windows 2003) 啟動ngrok 去連接 ngrok.aligogo.pw:4443
- 目標: 讓外部能連接內部 RDP 3389
- 因為是 Windows ngrok 需要重新編譯
1 GOOS=windows GOARCH=386 make release-client (for 32位元電腦)
1 GOOS=windows GOARCH=amd64 make release-client (for 64位元電腦)
1 ngrok.exe -config=ngrok.cfg start rdp
參考資料