add --allow-private-dst support for docker, bot and creator app

This commit is contained in:
kulikov0 committed 2026-09-15 18:04:12 +02:00
1 parent ca0966bc33
commit d171a757aa
16 files changed
+129 -32

No files matched your search

+2
View File
@@ -120,6 +120,8 @@
<input type="password" id="upstreamPass" placeholder="optional"> <input type="password" id="upstreamPass" placeholder="optional">
<h2>Logging</h2> <h2>Logging</h2>
<label class="popup-check"><input type="checkbox" id="debugLogging"><span>Debug logging</span></label> <label class="popup-check"><input type="checkbox" id="debugLogging"><span>Debug logging</span></label>
<h2>Local network</h2>
<label class="popup-check"><input type="checkbox" id="allowPrivateDst"><span>Let the joiner reach my local network</span></label>
<h2>Clear cookies</h2> <h2>Clear cookies</h2>
<div class="clear-cookies-row"> <div class="clear-cookies-row">
<button type="button" class="btn-clear-cookies" data-platform="vk">VK</button> <button type="button" class="btn-clear-cookies" data-platform="vk">VK</button>
+1
View File
@@ -70,6 +70,7 @@ export enum IPC {
STOP_BOT = 'stop-bot', STOP_BOT = 'stop-bot',
SET_UPSTREAM_PROXY = 'set-upstream-proxy', SET_UPSTREAM_PROXY = 'set-upstream-proxy',
SET_DEBUG_LOGGING = 'set-debug-logging', SET_DEBUG_LOGGING = 'set-debug-logging',
SET_ALLOW_PRIVATE_DST = 'set-allow-private-dst',
CLEAR_COOKIES = 'clear-cookies', CLEAR_COOKIES = 'clear-cookies',
GET_DION_CREDENTIALS = 'get-dion-credentials', GET_DION_CREDENTIALS = 'get-dion-credentials',
SET_DION_CREDENTIALS = 'set-dion-credentials', SET_DION_CREDENTIALS = 'set-dion-credentials',
+10 -4
View File
@@ -40,6 +40,7 @@ export class HeadlessLauncher {
private binaryPaths = new Map<Platform, string>(); private binaryPaths = new Map<Platform, string>();
private upstreamProxy: UpstreamProxy = { socks: '', user: '', pass: '' }; private upstreamProxy: UpstreamProxy = { socks: '', user: '', pass: '' };
private debugLogging = false; private debugLogging = false;
private allowPrivateDst = false;
constructor( constructor(
private host: LauncherHost, private host: LauncherHost,
@@ -76,6 +77,10 @@ export class HeadlessLauncher {
this.debugLogging = enabled; this.debugLogging = enabled;
} }
setAllowPrivateDst(enabled: boolean): void {
this.allowPrivateDst = enabled;
}
sendLog(tabId: string, msg: string): void { sendLog(tabId: string, msg: string): void {
const win = this.host.mainWindow; const win = this.host.mainWindow;
if (win && !win.isDestroyed()) { if (win && !win.isDestroyed()) {
@@ -101,7 +106,7 @@ export class HeadlessLauncher {
: RelayMode.VKVideoCreator; : RelayMode.VKVideoCreator;
} }
const relayArgs = ['--mode', relayMode, '--ws-port', String(port)]; const relayArgs = ['--mode', relayMode, '--ws-port', String(port)];
this.appendUpstreamArgs(relayArgs); this.appendEgressArgs(relayArgs);
if (this.debugLogging) relayArgs.push('--debug'); if (this.debugLogging) relayArgs.push('--debug');
const proc = spawn(this.relayPath, relayArgs, { const proc = spawn(this.relayPath, relayArgs, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
@@ -174,7 +179,7 @@ export class HeadlessLauncher {
if (joinTarget && config.joinFlag) { if (joinTarget && config.joinFlag) {
spawnArgs.push(config.joinFlag, joinTarget); spawnArgs.push(config.joinFlag, joinTarget);
} }
this.appendUpstreamArgs(spawnArgs); this.appendEgressArgs(spawnArgs);
if (this.debugLogging) spawnArgs.push('--debug'); if (this.debugLogging) spawnArgs.push('--debug');
const proc = spawn(this.binaryPaths.get(platform)!, spawnArgs, { const proc = spawn(this.binaryPaths.get(platform)!, spawnArgs, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
@@ -252,7 +257,7 @@ export class HeadlessLauncher {
if (joinTarget) { if (joinTarget) {
spawnArgs.push('--room', joinTarget); spawnArgs.push('--room', joinTarget);
} }
this.appendUpstreamArgs(spawnArgs); this.appendEgressArgs(spawnArgs);
if (this.debugLogging) spawnArgs.push('--debug'); if (this.debugLogging) spawnArgs.push('--debug');
const proc = spawn(this.bitrixPath, spawnArgs, { const proc = spawn(this.bitrixPath, spawnArgs, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
@@ -276,7 +281,8 @@ export class HeadlessLauncher {
}); });
} }
private appendUpstreamArgs(args: string[]): void { private appendEgressArgs(args: string[]): void {
if (this.allowPrivateDst) args.push('--allow-private-dst');
if (!this.upstreamProxy.socks) return; if (!this.upstreamProxy.socks) return;
args.push('--upstream-socks', this.upstreamProxy.socks); args.push('--upstream-socks', this.upstreamProxy.socks);
if (this.upstreamProxy.user) args.push('--upstream-user', this.upstreamProxy.user); if (this.upstreamProxy.user) args.push('--upstream-user', this.upstreamProxy.user);
+4
View File
@@ -108,6 +108,10 @@ export function registerIpcHandlers(tabManager: TabManager): void {
tabManager.setDebugLogging(enabled); tabManager.setDebugLogging(enabled);
}); });
ipcMain.handle(IPC.SET_ALLOW_PRIVATE_DST, (_e, enabled: boolean) => {
tabManager.setAllowPrivateDst(enabled);
});
ipcMain.handle(IPC.CLEAR_COOKIES, (_e, platform: string) => { ipcMain.handle(IPC.CLEAR_COOKIES, (_e, platform: string) => {
return tabManager.clearPlatformCookies(platform as Platform); return tabManager.clearPlatformCookies(platform as Platform);
}); });
+4
View File
@@ -157,6 +157,10 @@ export class TabManager {
this.launcher.setDebugLogging(enabled); this.launcher.setDebugLogging(enabled);
} }
setAllowPrivateDst(enabled: boolean): void {
this.launcher.setAllowPrivateDst(enabled);
}
startRelay(tabId: string, tab: TabState): void { startRelay(tabId: string, tab: TabState): void {
this.launcher.startRelay(tabId, tab); this.launcher.startRelay(tabId, tab);
} }
+3
View File
@@ -29,6 +29,9 @@ import { IPC } from '../constants';
setDebugLogging(enabled: boolean) { setDebugLogging(enabled: boolean) {
return ipcRenderer.invoke(IPC.SET_DEBUG_LOGGING, enabled); return ipcRenderer.invoke(IPC.SET_DEBUG_LOGGING, enabled);
}, },
setAllowPrivateDst(enabled: boolean) {
return ipcRenderer.invoke(IPC.SET_ALLOW_PRIVATE_DST, enabled);
},
clearCookies(platform: string) { clearCookies(platform: string) {
return ipcRenderer.invoke(IPC.CLEAR_COOKIES, platform); return ipcRenderer.invoke(IPC.CLEAR_COOKIES, platform);
}, },
+4
View File
@@ -98,6 +98,8 @@ function bindSettingsEvents(): void {
tm.saveUpstreamProxy(); tm.saveUpstreamProxy();
tm.debugLogging = (document.getElementById('debugLogging') as HTMLInputElement).checked; tm.debugLogging = (document.getElementById('debugLogging') as HTMLInputElement).checked;
tm.saveDebugLogging(); tm.saveDebugLogging();
tm.allowPrivateDst = (document.getElementById('allowPrivateDst') as HTMLInputElement).checked;
tm.saveAllowPrivateDst();
closeSettings(); closeSettings();
}); });
document.querySelectorAll('.btn-clear-cookies').forEach((btn) => { document.querySelectorAll('.btn-clear-cookies').forEach((btn) => {
@@ -253,6 +255,7 @@ function openSettings(): void {
(document.getElementById('upstreamUser') as HTMLInputElement).value = tm.upstreamProxy.user; (document.getElementById('upstreamUser') as HTMLInputElement).value = tm.upstreamProxy.user;
(document.getElementById('upstreamPass') as HTMLInputElement).value = tm.upstreamProxy.pass; (document.getElementById('upstreamPass') as HTMLInputElement).value = tm.upstreamProxy.pass;
(document.getElementById('debugLogging') as HTMLInputElement).checked = tm.debugLogging; (document.getElementById('debugLogging') as HTMLInputElement).checked = tm.debugLogging;
(document.getElementById('allowPrivateDst') as HTMLInputElement).checked = tm.allowPrivateDst;
document.getElementById('clearCookiesStatus')!.textContent = ''; document.getElementById('clearCookiesStatus')!.textContent = '';
} }
@@ -285,6 +288,7 @@ function init(): void {
savedCalls.bindEvents(); savedCalls.bindEvents();
window.bridge.setUpstreamProxy(tm.upstreamProxy); window.bridge.setUpstreamProxy(tm.upstreamProxy);
window.bridge.setAllowPrivateDst(tm.allowPrivateDst);
window.bridge.onRelayLog((tabId: string, msg: string) => { window.bridge.onRelayLog((tabId: string, msg: string) => {
tm.appendRelayLog(tabId, msg); tm.appendRelayLog(tabId, msg);
+7
View File
@@ -23,6 +23,7 @@ export class RendererTabManager {
botSettings: BotSettings; botSettings: BotSettings;
upstreamProxy: UpstreamProxy; upstreamProxy: UpstreamProxy;
debugLogging: boolean; debugLogging: boolean;
allowPrivateDst: boolean;
private onRender: () => void; private onRender: () => void;
constructor(onRender: () => void) { constructor(onRender: () => void) {
@@ -36,6 +37,7 @@ export class RendererTabManager {
? JSON.parse(savedProxy) ? JSON.parse(savedProxy)
: { socks: '', user: '', pass: '' }; : { socks: '', user: '', pass: '' };
this.debugLogging = localStorage.getItem('debugLogging') === 'true'; this.debugLogging = localStorage.getItem('debugLogging') === 'true';
this.allowPrivateDst = localStorage.getItem('allowPrivateDst') === 'true';
} }
createTab(): string { createTab(): string {
@@ -258,6 +260,11 @@ export class RendererTabManager {
window.bridge.setDebugLogging(this.debugLogging); window.bridge.setDebugLogging(this.debugLogging);
} }
saveAllowPrivateDst(): void {
localStorage.setItem('allowPrivateDst', String(this.allowPrivateDst));
window.bridge.setAllowPrivateDst(this.allowPrivateDst);
}
startSavedCall(call: SavedCall): void { startSavedCall(call: SavedCall): void {
this.createTab(); this.createTab();
this.switchToHeadless(call.platform); this.switchToHeadless(call.platform);
+1
View File
@@ -184,6 +184,7 @@ export interface Bridge {
stopBot(): Promise<void>; stopBot(): Promise<void>;
setUpstreamProxy(proxy: UpstreamProxy): Promise<void>; setUpstreamProxy(proxy: UpstreamProxy): Promise<void>;
setDebugLogging(enabled: boolean): Promise<void>; setDebugLogging(enabled: boolean): Promise<void>;
setAllowPrivateDst(enabled: boolean): Promise<void>;
clearCookies(platform: string): Promise<number>; clearCookies(platform: string): Promise<number>;
getDionCredentials(): Promise<DionCredentials>; getDionCredentials(): Promise<DionCredentials>;
setDionCredentials(email: string, password: string): Promise<void>; setDionCredentials(email: string, password: string): Promise<void>;
+3 -1
View File
@@ -152,7 +152,7 @@
| `--upstream-socks <host:port>` | да | да | да | да | да | Гнать трафик joiner-а через локальный SOCKS5 прокси, например VPN-клиент | | `--upstream-socks <host:port>` | да | да | да | да | да | Гнать трафик joiner-а через локальный SOCKS5 прокси, например VPN-клиент |
| `--upstream-user <user>` | да | да | да | да | да | Логин для upstream SOCKS5 | | `--upstream-user <user>` | да | да | да | да | да | Логин для upstream SOCKS5 |
| `--upstream-pass <pass>` | да | да | да | да | да | Пароль для upstream SOCKS5 | | `--upstream-pass <pass>` | да | да | да | да | да | Пароль для upstream SOCKS5 |
| `--allow-private-dst` | да | да | да | да | да | Разрешить joiner-у ходить в локальную сеть creator-а (по умолчанию такие адреса блокируются) | | `--allow-private-dst` | да | да | да | да | да | Разрешить joiner-у ходить в локальную сеть creator-а, по умолчанию такие адреса блокируются. Loopback и link-local, включая metadata ip `169.254.169.254`, остаются закрыты и с этим флагом |
| `--debug` | да | да | да | да | да | Подробные логи | | `--debug` | да | да | да | да | да | Подробные логи |
| `--version` | да | да | да | да | да | Вывести версию и выйти | | `--version` | да | да | да | да | да | Вывести версию и выйти |
@@ -304,6 +304,7 @@ Standalone Go-бинарник `headless-vk-bot` - то же самое, что
| `--bitrix-cookies <path>` | Путь к Bitrix куки (нужен для `/bitrix` и для join по ссылке `bitrix24` + `/video/`) | | `--bitrix-cookies <path>` | Путь к Bitrix куки (нужен для `/bitrix` и для join по ссылке `bitrix24` + `/video/`) |
| `--sessions-dir <dir>` | Папка для логов запущенных creators. Опционально - без флага логи не пишутся, stdout/stderr creators отбрасываются | | `--sessions-dir <dir>` | Папка для логов запущенных creators. Опционально - без флага логи не пишутся, stdout/stderr creators отбрасываются |
| `--resources <mode>` | Режим ресурсов, передаётся каждому запускаемому creator: `default` / `moderate` / `unlimited`. По умолчанию `default`. `custom` не поддерживается, так как у каждого бинарника свой набор флагов настройки | | `--resources <mode>` | Режим ресурсов, передаётся каждому запускаемому creator: `default` / `moderate` / `unlimited`. По умолчанию `default`. `custom` не поддерживается, так как у каждого бинарника свой набор флагов настройки |
| `--allow-private-dst` | Передаётся каждому запускаемому creator: разрешить joiner-у ходить в локальную сеть creator-а. По умолчанию выключено |
| `--version` | Вывести версию и выйти | | `--version` | Вывести версию и выйти |
При получении команды бот запускает соответствующий creator с `--write-file <tmp>`, ждёт появления линка в файле (до 60 секунд) и присылает его в чат. `--user-id` принимает список через запятую; если указан, команды от пользователей не из списка игнорируются. При получении команды бот запускает соответствующий creator с `--write-file <tmp>`, ждёт появления линка в файле (до 60 секунд) и присылает его в чат. `--user-id` принимает список через запятую; если указан, команды от пользователей не из списка игнорируются.
@@ -387,6 +388,7 @@ docker compose pull && docker compose up -d
| `UPSTREAM_SOCKS` | нет | - | `--upstream-socks` | | `UPSTREAM_SOCKS` | нет | - | `--upstream-socks` |
| `UPSTREAM_USER` | нет | - | `--upstream-user` | | `UPSTREAM_USER` | нет | - | `--upstream-user` |
| `UPSTREAM_PASS` | нет | - | `--upstream-pass` | | `UPSTREAM_PASS` | нет | - | `--upstream-pass` |
| `ALLOW_PRIVATE_DST` | нет | `0` | `--allow-private-dst`, включается значением `1` |
> `cookies-dion.json`, `cookies-bitrix.json` и `cookies-wbstream.json` монтируются без `:ro` - creator перезаписывает их при обновлении токена, поэтому на хосте они должны принадлежать uid 999 (иначе `save cookies failed: permission denied`). VK и Telemost только читаются. > `cookies-dion.json`, `cookies-bitrix.json` и `cookies-wbstream.json` монтируются без `:ro` - creator перезаписывает их при обновлении токена, поэтому на хосте они должны принадлежать uid 999 (иначе `save cookies failed: permission denied`). VK и Telemost только читаются.
+1
View File
@@ -42,5 +42,6 @@ set -- \
[ -n "${UPSTREAM_SOCKS:-}" ] && set -- "$@" --upstream-socks "$UPSTREAM_SOCKS" [ -n "${UPSTREAM_SOCKS:-}" ] && set -- "$@" --upstream-socks "$UPSTREAM_SOCKS"
[ -n "${UPSTREAM_USER:-}" ] && set -- "$@" --upstream-user "$UPSTREAM_USER" [ -n "${UPSTREAM_USER:-}" ] && set -- "$@" --upstream-user "$UPSTREAM_USER"
[ -n "${UPSTREAM_PASS:-}" ] && set -- "$@" --upstream-pass "$UPSTREAM_PASS" [ -n "${UPSTREAM_PASS:-}" ] && set -- "$@" --upstream-pass "$UPSTREAM_PASS"
[ "${ALLOW_PRIVATE_DST:-0}" = "1" ] && set -- "$@" --allow-private-dst
exec /usr/local/bin/headless-vk-bot "$@" exec /usr/local/bin/headless-vk-bot "$@"
+23 -16
View File
@@ -75,6 +75,8 @@ type bot struct {
upstreamUser string upstreamUser string
upstreamPass string upstreamPass string
allowPrivateDst bool
server, key, ts string server, key, ts string
mu sync.Mutex mu sync.Mutex
@@ -379,6 +381,9 @@ func (b *bot) spawn(platform, joinTarget string) (*session, error) {
args = append(args, "--upstream-pass", b.upstreamPass) args = append(args, "--upstream-pass", b.upstreamPass)
} }
} }
if b.allowPrivateDst {
args = append(args, "--allow-private-dst")
}
cmd := exec.Command(bin, args...) cmd := exec.Command(bin, args...)
if logF != nil { if logF != nil {
cmd.Stdout = logF cmd.Stdout = logF
@@ -505,6 +510,7 @@ func main() {
upstreamSocks := flag.String("upstream-socks", "", "forward to spawned creators: route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client") upstreamSocks := flag.String("upstream-socks", "", "forward to spawned creators: route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username forwarded to spawned creators") upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username forwarded to spawned creators")
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password forwarded to spawned creators") upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password forwarded to spawned creators")
allowPrivateDst := flag.Bool("allow-private-dst", false, "forward to spawned creators: let the joiner reach private/internal addresses through them")
flag.Parse() flag.Parse()
if *token == "" { if *token == "" {
@@ -533,22 +539,23 @@ func main() {
} }
b := &bot{ b := &bot{
token: *token, token: *token,
groupID: *groupID, groupID: *groupID,
userIDs: allowedUsers, userIDs: allowedUsers,
binsDir: *binsDir, binsDir: *binsDir,
vkCookies: *vkCookies, vkCookies: *vkCookies,
tmCookies: *tmCookies, tmCookies: *tmCookies,
wbCookies: *wbCookies, wbCookies: *wbCookies,
dionCookies: *dionCookies, dionCookies: *dionCookies,
bitrixCookies: *bitrixCookies, bitrixCookies: *bitrixCookies,
sessionsDir: *sessionsDir, sessionsDir: *sessionsDir,
resources: *resources, resources: *resources,
upstreamSocks: *upstreamSocks, upstreamSocks: *upstreamSocks,
upstreamUser: *upstreamUser, upstreamUser: *upstreamUser,
upstreamPass: *upstreamPass, upstreamPass: *upstreamPass,
sessions: map[string]*session{}, allowPrivateDst: *allowPrivateDst,
awaitingJoin: map[int64]bool{}, sessions: map[string]*session{},
awaitingJoin: map[int64]bool{},
} }
sig := make(chan os.Signal, 1) sig := make(chan os.Signal, 1)
+3 -3
View File
@@ -333,7 +333,7 @@ func (u *TunnelRelay) sendDCFrame(connID uint32, mt byte, payload []byte) {
func (u *TunnelRelay) connectTCP(connID uint32, addr string) { func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
log.Printf("[dc] CONNECT %d -> %s", connID, common.MaskAddr(addr)) log.Printf("[dc] CONNECT %d -> %s", connID, common.MaskAddr(addr))
if common.DstBlocked(addr) { if common.DstBlocked(addr) {
log.Printf("[dc] CONNECT %d blocked %s", connID, common.MaskAddr(addr)) log.Printf("[dc] CONNECT %d blocked %s, private destinations need --allow-private-dst", connID, common.MaskAddr(addr))
u.sendDCFrame(connID, tunnel.MsgConnectErr, []byte(common.ErrPrivateDst.Error())) u.sendDCFrame(connID, tunnel.MsgConnectErr, []byte(common.ErrPrivateDst.Error()))
return return
} }
@@ -408,8 +408,8 @@ func (u *TunnelRelay) handleUDP(connID uint32, payload []byte) {
resp := make([]byte, common.UDPBufSize) resp := make([]byte, common.UDPBufSize)
if common.DstBlocked(addr) { if common.DstBlocked(addr) {
if common.Debug { if suppressed, ok := common.ClaimBlockedDstLog(); ok {
log.Printf("[dc] UDP %d blocked %s", connID, common.MaskAddr(addr)) log.Printf("[dc] UDP %d blocked %s, private destinations need --allow-private-dst, suppressed=%d", connID, common.MaskAddr(addr), suppressed)
} }
return return
} }
+54 -4
View File
@@ -3,22 +3,50 @@ package common
import ( import (
"errors" "errors"
"net" "net"
"sync"
"syscall" "syscall"
"time" "time"
) )
const blockedDstLogInterval = 10 * time.Second
var AllowPrivateDst bool var AllowPrivateDst bool
var ErrPrivateDst = errors.New("destination not allowed") var ErrPrivateDst = errors.New("destination not allowed")
var (
blockedDstMu sync.Mutex
blockedDstLastLog time.Time
blockedDstSuppressed int
)
func ClaimBlockedDstLog() (int, bool) {
blockedDstMu.Lock()
defer blockedDstMu.Unlock()
now := time.Now()
if !blockedDstLastLog.IsZero() && now.Sub(blockedDstLastLog) < blockedDstLogInterval {
blockedDstSuppressed++
return 0, false
}
suppressed := blockedDstSuppressed
blockedDstSuppressed = 0
blockedDstLastLog = now
return suppressed, true
}
// cgnat is caught by neither IsGlobalUnicast nor IsPrivate // cgnat is caught by neither IsGlobalUnicast nor IsPrivate
var _, cgnat, _ = net.ParseCIDR("100.64.0.0/10") var _, cgnat, _ = net.ParseCIDR("100.64.0.0/10")
func IsPrivateDst(addr string) bool { func hostFromAddr(addr string) string {
host, _, err := net.SplitHostPort(addr) host, _, err := net.SplitHostPort(addr)
if err != nil { if err != nil {
host = addr return addr
} }
return host
}
func IsPrivateDst(addr string) bool {
host := hostFromAddr(addr)
if host == "" { if host == "" {
// ":80" dials the local machine // ":80" dials the local machine
return true return true
@@ -30,7 +58,29 @@ func IsPrivateDst(addr string) bool {
return isPrivateIP(ip) return isPrivateIP(ip)
} }
func DstBlocked(addr string) bool { return !AllowPrivateDst && IsPrivateDst(addr) } func DstBlocked(addr string) bool {
host := hostFromAddr(addr)
if host == "" {
return true
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ipBlocked(ip)
}
func ipBlocked(ip net.IP) bool {
if isNeverAllowedIP(ip) {
return true
}
return !AllowPrivateDst && isPrivateIP(ip)
}
// AllowPrivateDst unlocks rfc1918 and cgnat only, the metadata ip and the creator's own loopback stay closed
func isNeverAllowedIP(ip net.IP) bool {
return ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsMulticast()
}
func isPrivateIP(ip net.IP) bool { func isPrivateIP(ip net.IP) bool {
return !ip.IsGlobalUnicast() || ip.IsPrivate() || cgnat.Contains(ip) return !ip.IsGlobalUnicast() || ip.IsPrivate() || cgnat.Contains(ip)
@@ -61,7 +111,7 @@ func DialUDP(addr string) (*net.UDPConn, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !AllowPrivateDst && isPrivateIP(udpAddr.IP) { if ipBlocked(udpAddr.IP) {
return nil, ErrPrivateDst return nil, ErrPrivateDst
} }
return net.DialUDP("udp", nil, udpAddr) return net.DialUDP("udp", nil, udpAddr)
+6 -1
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"io" "io"
"log" "log"
@@ -171,7 +172,11 @@ func (c *dcCreatorRelay) handleUDP(connID uint32, payload []byte) {
conn, err := common.DialUDP(addr) conn, err := common.DialUDP(addr)
if err != nil { if err != nil {
if common.Debug { if errors.Is(err, common.ErrPrivateDst) {
if suppressed, ok := common.ClaimBlockedDstLog(); ok {
log.Printf("dc-creator: UDP %d blocked %s, private destinations need --allow-private-dst, suppressed=%d", connID, common.MaskAddr(addr), suppressed)
}
} else if common.Debug {
log.Printf("dc-creator: UDP dial %s failed: %s", common.MaskAddr(addr), common.MaskError(err)) log.Printf("dc-creator: UDP dial %s failed: %s", common.MaskAddr(addr), common.MaskError(err))
} }
return return
+3 -3
View File
@@ -388,8 +388,8 @@ func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
// per datagram, an already open session carries a fresh dst every time // per datagram, an already open session carries a fresh dst every time
if common.DstBlocked(addr) { if common.DstBlocked(addr) {
if common.Debug { if suppressed, ok := common.ClaimBlockedDstLog(); ok {
rb.logFn("relay[creator]: UDP %d blocked %s", connID, common.MaskAddr(addr)) rb.logFn("relay[creator]: UDP %d blocked %s, private destinations need --allow-private-dst, suppressed=%d", connID, common.MaskAddr(addr), suppressed)
} }
return return
} }
@@ -471,7 +471,7 @@ func (rb *RelayBridge) dialCreatorUDP(addr string) (*creatorUDP, error) {
func (rb *RelayBridge) connectTCP(connID uint32, addr string) { func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
rb.logFn("relay: CONNECT %d -> %s", connID, common.MaskAddr(addr)) rb.logFn("relay: CONNECT %d -> %s", connID, common.MaskAddr(addr))
if common.DstBlocked(addr) { if common.DstBlocked(addr) {
rb.logFn("relay: CONNECT %d blocked %s", connID, common.MaskAddr(addr)) rb.logFn("relay: CONNECT %d blocked %s, private destinations need --allow-private-dst", connID, common.MaskAddr(addr))
rb.send(connID, MsgConnectErr, []byte(common.ErrPrivateDst.Error())) rb.send(connID, MsgConnectErr, []byte(common.ErrPrivateDst.Error()))
return return
} }