From 1093aafdd2425ded73ec29d63e0e8ce66dfa5f9e Mon Sep 17 00:00:00 2001 From: mzz2017 Date: Tue, 25 Jan 2022 21:11:57 +0800 Subject: [PATCH] feat(macOS,windows): support system proxy. Thanks @Johnshall #338 --- gui/src/components/modalSetting.vue | 15 +- service/common/httpClient/httpClient.go | 2 +- service/conf/report/curl.go | 3 +- service/core/iptables/dropSpoofing.go | 16 +- service/core/iptables/iptables.go | 62 ++-- service/core/iptables/redirect.go | 14 +- service/core/iptables/systemProxy_macos.go | 71 +++++ service/core/iptables/systemProxy_other.go | 22 ++ service/core/iptables/systemProxy_windows.go | 290 +++++++++++++++++++ service/core/iptables/tproxy.go | 14 +- service/core/specialMode/specialMode.go | 2 +- service/core/v2ray/asset/dat/gfwlist.go | 2 +- service/core/v2ray/transparent.go | 52 +++- service/core/v2ray/v2rayTmpl.go | 31 +- service/db/configure/const.go | 1 + 15 files changed, 518 insertions(+), 79 deletions(-) create mode 100644 service/core/iptables/systemProxy_macos.go create mode 100644 service/core/iptables/systemProxy_other.go create mode 100644 service/core/iptables/systemProxy_windows.go diff --git a/gui/src/components/modalSetting.vue b/gui/src/components/modalSetting.vue index 73a93b11..2aeb3fc7 100644 --- a/gui/src/components/modalSetting.vue +++ b/gui/src/components/modalSetting.vue @@ -57,16 +57,16 @@ - - - - @@ -102,8 +102,9 @@ - - + + + @@ -440,7 +441,7 @@ export default { this.pacAutoUpdateTime = new Date(this.pacAutoUpdateTime); this.showDoh = localStorage["dohValid"] === "yes"; if (this.lite) { - this.transparent = "close"; + this.transparentType = "system_proxy" this.showSpecialMode = false; } }); diff --git a/service/common/httpClient/httpClient.go b/service/common/httpClient/httpClient.go index a6fce9fc..3c424ea5 100644 --- a/service/common/httpClient/httpClient.go +++ b/service/common/httpClient/httpClient.go @@ -61,7 +61,7 @@ func GetHttpClientWithv2rayAPac() (client *http.Client, err error) { } func GetHttpClientAutomatically() (c *http.Client, err error) { - if s := configure.GetSettingNotNil(); !v2ray.ProcessManager.Running() || configure.GetConnectedServers() == nil || s.Transparent != configure.TransparentClose { + if !v2ray.ProcessManager.Running() || configure.GetConnectedServers() == nil || v2ray.IsTransparentOn() { return http.DefaultClient, nil } setting := configure.GetSettingNotNil() diff --git a/service/conf/report/curl.go b/service/conf/report/curl.go index f0be4918..9123fddf 100644 --- a/service/conf/report/curl.go +++ b/service/conf/report/curl.go @@ -3,6 +3,7 @@ package report import ( "fmt" "github.com/v2rayA/v2rayA/common/httpClient" + "github.com/v2rayA/v2rayA/core/v2ray" "github.com/v2rayA/v2rayA/db/configure" "io" "net" @@ -46,7 +47,7 @@ func (r *CurlReporter) TransparentReport() (ok bool, report string) { defer func() { report = fmt.Sprintf("Transparent Proxy(%v): %v", setting.TransparentType, report) }() - if setting.Transparent == configure.TransparentClose { + if !v2ray.IsTransparentOn() { return true, "Transparent Proxy is not enabled" } cli := http.Client{ diff --git a/service/core/iptables/dropSpoofing.go b/service/core/iptables/dropSpoofing.go index bc6b4ac0..32e276ff 100644 --- a/service/core/iptables/dropSpoofing.go +++ b/service/core/iptables/dropSpoofing.go @@ -1,10 +1,10 @@ package iptables -type dropSpoofing struct{ iptablesSetter } +type dropSpoofing struct{} var DropSpoofing dropSpoofing -func (r *dropSpoofing) GetSetupCommands() SetupCommands { +func (r *dropSpoofing) GetSetupCommands() Setter { commands := ` iptables -w 2 -N DROP_SPOOFING iptables -w 2 -A DROP_SPOOFING -p udp --sport 53 -m string --algo bm --hex-string "|00047f|" --from 60 --to 180 -j DROP @@ -33,10 +33,13 @@ ip6tables -w 2 -I INPUT -j DROP_SPOOFING ip6tables -w 2 -I FORWARD -j DROP_SPOOFING ` } - return SetupCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } -func (r *dropSpoofing) GetCleanCommands() CleanCommands { +func (r *dropSpoofing) GetCleanCommands() Setter { commands := ` iptables -w 2 -D INPUT -j DROP_SPOOFING iptables -w 2 -D FORWARD -j DROP_SPOOFING @@ -51,5 +54,8 @@ ip6tables -w 2 -F DROP_SPOOFING ip6tables -w 2 -X DROP_SPOOFING ` } - return CleanCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } diff --git a/service/core/iptables/iptables.go b/service/core/iptables/iptables.go index b9a15425..40086fd0 100644 --- a/service/core/iptables/iptables.go +++ b/service/core/iptables/iptables.go @@ -15,18 +15,26 @@ const watcherInterval = 3 * time.Second var watcher *LocalIPWatcher var mutex sync.Mutex -type SetupCommands string -type CleanCommands string +type Setter struct { + Cmds string + Func func() error +} -type iptablesSetter interface { - GetSetupCommands() SetupCommands - GetCleanCommands() CleanCommands +func NewErrorSetter(err error) Setter { + return Setter{Func: func() error { + return err + }} +} + +type proxySetter interface { + GetSetupCommands() Setter + GetCleanCommands() Setter AddIPWhitelist(cidr string) RemoveIPWhitelist(cidr string) } // watch interface changes and add specific IPs to whitelist on iptables -func SetWatcher(setter iptablesSetter) { +func SetWatcher(setter proxySetter) { if watcher != nil { watcher.Close() } @@ -40,31 +48,35 @@ func CloseWatcher() { } } -func (c SetupCommands) Setup(preprocess func(c *SetupCommands)) (err error) { +func (c Setter) Run(stopAtError bool) error { mutex.Lock() defer mutex.Unlock() - if preprocess != nil { - preprocess(&c) - } - commands := string(c) + commands := c.Cmds if common.IsDocker() { commands = strings.ReplaceAll(commands, "iptables", "iptables-legacy") commands = strings.ReplaceAll(commands, "ip6tables", "ip6tables-legacy") } - err = cmds.ExecCommands(commands, true) - if err != nil { - return + var errs []error + if len(commands) > 0 { + e := cmds.ExecCommands(commands, true) + if e != nil { + errs = append(errs, e) + if stopAtError && len(errs) > 0 { + return errs[0] + } + } } - return -} - -func (c CleanCommands) Clean() { - mutex.Lock() - defer mutex.Unlock() - commands := string(c) - if common.IsDocker() { - commands = strings.ReplaceAll(commands, "iptables", "iptables-legacy") - commands = strings.ReplaceAll(commands, "ip6tables", "ip6tables-legacy") + if c.Func != nil { + e := c.Func() + if e != nil { + errs = append(errs, e) + if stopAtError && len(errs) > 0 { + return errs[0] + } + } } - _ = cmds.ExecCommands(commands, false) + if len(errs) > 0 { + return errs[0] + } + return nil } diff --git a/service/core/iptables/redirect.go b/service/core/iptables/redirect.go index f6375db2..9a017fde 100644 --- a/service/core/iptables/redirect.go +++ b/service/core/iptables/redirect.go @@ -28,7 +28,7 @@ func (r *redirect) RemoveIPWhitelist(cidr string) { cmds.ExecCommands(commands, false) } -func (r *redirect) GetSetupCommands() SetupCommands { +func (r *redirect) GetSetupCommands() Setter { commands := ` iptables -w 2 -t nat -N V2RAY iptables -w 2 -t nat -A V2RAY -d 0.0.0.0/32 -j RETURN @@ -75,10 +75,13 @@ ip6tables -w 2 -t nat -I PREROUTING -p tcp -j V2RAY ip6tables -w 2 -t nat -I OUTPUT -p tcp -j V2RAY ` } - return SetupCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } -func (r *redirect) GetCleanCommands() CleanCommands { +func (r *redirect) GetCleanCommands() Setter { commands := ` iptables -w 2 -t nat -F V2RAY iptables -w 2 -t nat -D PREROUTING -p tcp -j V2RAY @@ -93,5 +96,8 @@ ip6tables -w 2 -t nat -D OUTPUT -p tcp -j V2RAY ip6tables -w 2 -t nat -X V2RAY ` } - return CleanCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } diff --git a/service/core/iptables/systemProxy_macos.go b/service/core/iptables/systemProxy_macos.go new file mode 100644 index 00000000..f0237718 --- /dev/null +++ b/service/core/iptables/systemProxy_macos.go @@ -0,0 +1,71 @@ +//go:build darwin +// +build darwin + +package iptables + +import ( + "fmt" + "os/exec" + "strconv" + "strings" +) + +type systemProxy struct{} + +var SystemProxy systemProxy + +// GetNetworkServices 用于获取MacOS设备的 networkservices +func GetNetworkServices() ([]string, error) { + cmd := exec.Command("/usr/sbin/networksetup", "-listallnetworkservices") + stdoutStderr, err := cmd.CombinedOutput() + if err != nil { + return nil, fmt.Errorf("cannot get network services: %v", err) + } + lines := strings.Split(string(stdoutStderr), "\n") + var services []string + for i := 1; i < len(lines); i++ { + lines[i] = strings.TrimSpace(lines[i]) + if len(lines[i]) == 0 || strings.Contains(lines[i], "*") { + continue + } + services = append(services, lines[i]) + } + return services, nil +} + +func (p *systemProxy) AddIPWhitelist(cidr string) {} + +func (p *systemProxy) RemoveIPWhitelist(cidr string) {} + +func (p *systemProxy) GetSetupCommands() Setter { + networkServices, err := GetNetworkServices() + if err != nil { + return NewErrorSetter(err) + } + var commands string + for _, service := range networkServices { + commands += fmt.Sprintf("/usr/sbin/networksetup -setwebproxystate %v on\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setsecurewebproxystate %v on\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setwebproxy %v 127.0.0.1 32345\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setsecurewebproxy %v 127.0.0.1 32345\n", strconv.Quote(service)) + } + return Setter{ + Cmds: commands, + } +} + +func (p *systemProxy) GetCleanCommands() Setter { + networkServices, err := GetNetworkServices() + if err != nil { + return NewErrorSetter(err) + } + + commands := "" + for _, service := range networkServices { + commands += fmt.Sprintf("/usr/sbin/networksetup -setautoproxystate %v off\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setwebproxystate %v off\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setsecurewebproxystate %v off\n", strconv.Quote(service)) + commands += fmt.Sprintf("/usr/sbin/networksetup -setsocksfirewallproxystate %v off\n", strconv.Quote(service)) + } + return Setter{Cmds: commands} +} diff --git a/service/core/iptables/systemProxy_other.go b/service/core/iptables/systemProxy_other.go new file mode 100644 index 00000000..fe55182b --- /dev/null +++ b/service/core/iptables/systemProxy_other.go @@ -0,0 +1,22 @@ +//go:build linux || openbsd || freebsd +// +build linux openbsd freebsd + +package iptables + +import "fmt" + +type systemProxy struct{} + +var SystemProxy systemProxy + +func (p *systemProxy) AddIPWhitelist(cidr string) {} + +func (p *systemProxy) RemoveIPWhitelist(cidr string) {} + +func (p *systemProxy) GetSetupCommands() Setter { + return NewErrorSetter(fmt.Errorf("does not support to configure system proxy on your OS")) +} + +func (p *systemProxy) GetCleanCommands() Setter { + return Setter{} +} diff --git a/service/core/iptables/systemProxy_windows.go b/service/core/iptables/systemProxy_windows.go new file mode 100644 index 00000000..b9af6426 --- /dev/null +++ b/service/core/iptables/systemProxy_windows.go @@ -0,0 +1,290 @@ +//go:build windows +// +build windows + +package iptables + +import ( + "fmt" + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" + "syscall" + "unsafe" +) + +const ( + errnoERROR_IO_PENDING = 997 + INTERNET_OPTION_SETTINGS_CHANGED = 39 +) + +var ( + errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) + modwininet = syscall.NewLazyDLL("wininet.dll") + procInternetSetOptionW = modwininet.NewProc("InternetSetOptionW") +) + +// errnoErr returns common boxed Errno values, to prevent +// allocations at runtime. +func errnoErr(e syscall.Errno) error { + switch e { + case 0: + return nil + case errnoERROR_IO_PENDING: + return errERROR_IO_PENDING + } + // TODO: add more here, after collecting data on the common + // error values see on Windows. (perhaps when running + // all.bat?) + return e +} + +var ( + modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") + modkernel32 = windows.NewLazySystemDLL("kernel32.dll") + + procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") + procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") + procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") + procRevertToSelf = modadvapi32.NewProc("RevertToSelf") +) + +func GetCurrentThread() (pseudoHandle windows.Handle, err error) { + r0, _, e1 := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) + pseudoHandle = windows.Handle(r0) + if pseudoHandle == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func OpenThreadToken(h windows.Handle, access uint32, self bool, token *windows.Token) (err error) { + var _p0 uint32 + if self { + _p0 = 1 + } else { + _p0 = 0 + } + r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(h), uintptr(access), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func ImpersonateSelf() (err error) { + r0, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(2), 0, 0) + if r0 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func RevertToSelf() (err error) { + r0, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) + if r0 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func OpenCurrentThreadToken() (windows.Token, error) { + if e := ImpersonateSelf(); e != nil { + return 0, e + } + defer RevertToSelf() + t, e := GetCurrentThread() + if e != nil { + return 0, e + } + var tok windows.Token + e = OpenThreadToken(t, windows.TOKEN_QUERY, true, &tok) + if e != nil { + return 0, e + } + return tok, nil +} + +func HasAdminRights() (bool, error) { + // https://github.com/golang/go/issues/28804 + var sid *windows.SID + err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, 2, windows.SECURITY_BUILTIN_DOMAIN_RID, windows.DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid) + if err != nil { + return false, err + } + defer windows.FreeSid(sid) + + token, err := OpenCurrentThreadToken() + if err != nil { + return false, err + } + + member, err := token.IsMember(sid) + if err != nil { + return false, err + } + return member, nil +} + +func InternetOptionSettingsChanged() (syscall.Handle, error) { + // https://github.com/Diving-Fish/maimaidx-prober/blob/1673cff975e6bbb14eeeda6260af131ac036f974/proxy/lib/wininet_windows.go#L18 + // https://docs.microsoft.com/en-us/windows/win32/wininet/option-flags + p1 := uint16(0) + p2 := uint64(INTERNET_OPTION_SETTINGS_CHANGED) + p3 := uint16(0) + p4 := uint64(0) + r1, _, e1 := syscall.Syscall6( + procInternetSetOptionW.Addr(), + 4, + uintptr(p1), + uintptr(p2), + uintptr(p3), + uintptr(p4), + 0, + 0, + ) + if r1 == 0 { + if e1 != 0 { + return 0, e1 + } else { + return 0, syscall.EINVAL + } + } + return syscall.Handle(r1), nil +} + +const profileListPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList" + +func getProfileListSubKeyNames() ([]string, error) { + // https://github.com/ninoseki/ninoseki.github.io/blob/0e911fe146c0de7b2fa4449ff9c2ac1ebe755b67/docs/_posts/2020-07-25-windows-registry-with-go.md + k, err := registry.OpenKey(registry.LOCAL_MACHINE, profileListPath, registry.ENUMERATE_SUB_KEYS) + if err != nil { + return nil, fmt.Errorf("unable to open registry key %q: %v", profileListPath, err) + } + defer k.Close() + return k.ReadSubKeyNames(0) +} + +type systemProxy struct{} + +var SystemProxy systemProxy + +func (p *systemProxy) AddIPWhitelist(cidr string) {} + +func (p *systemProxy) RemoveIPWhitelist(cidr string) {} + +type todo struct { + Key registry.Key + Prefix string +} + +func (p *systemProxy) GetSetupCommands() Setter { + return Setter{ + Func: func() error { + hasAdminRights, err := HasAdminRights() + if err != nil { + return err + } + var todolist []todo + if hasAdminRights { + // https://docs.microsoft.com/en-us/windows/win32/services/services-and-the-registry + // A service should not access HKEY_CURRENT_USER or HKEY_CLASSES_ROOT, especially when impersonating a user. + sids, err := getProfileListSubKeyNames() + if err != nil { + return err + } + for _, sid := range sids { + todolist = append(todolist, todo{ + Key: registry.USERS, + Prefix: sid + `\`, + }) + } + } else { + todolist = append(todolist, todo{ + Key: registry.CURRENT_USER, + Prefix: "", + }) + } + for _, todo := range todolist { + key, _, err := registry.CreateKey(todo.Key, todo.Prefix+`SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.ALL_ACCESS) + if err != nil { + return err + } + defer key.Close() + _ = key.DeleteValue("AutoConfigURL") + if err = key.SetDWordValue("ProxyEnable", 1); err != nil { + return err + } + if err = key.SetStringValue("ProxyServer", "127.0.0.1:32345"); err != nil { + return err + } + } + _, _ = InternetOptionSettingsChanged() + return nil + }, + } +} + +func (p *systemProxy) GetCleanCommands() Setter { + return Setter{ + Func: func() error { + hasAdminRights, err := HasAdminRights() + if err != nil { + return err + } + var todolist []todo + if hasAdminRights { + // https://docs.microsoft.com/en-us/windows/win32/services/services-and-the-registry + // A service should not access HKEY_CURRENT_USER or HKEY_CLASSES_ROOT, especially when impersonating a user. + sids, err := getProfileListSubKeyNames() + if err != nil { + return err + } + for _, sid := range sids { + todolist = append(todolist, todo{ + Key: registry.USERS, + Prefix: sid + `\`, + }) + } + } else { + todolist = append(todolist, todo{ + Key: registry.CURRENT_USER, + Prefix: "", + }) + } + + var errs []error + for _, todo := range todolist { + key, _, err := registry.CreateKey(todo.Key, todo.Prefix+`SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.ALL_ACCESS) + if err != nil { + errs = append(errs, err) + continue + } + defer key.Close() + if err = key.SetDWordValue("ProxyEnable", 0); err != nil { + errs = append(errs, err) + continue + } + } + _, _ = InternetOptionSettingsChanged() + if len(errs) > 0 { + return errs[0] + } + return nil + }, + } +} diff --git a/service/core/iptables/tproxy.go b/service/core/iptables/tproxy.go index 7c833345..d77d8cdb 100644 --- a/service/core/iptables/tproxy.go +++ b/service/core/iptables/tproxy.go @@ -40,7 +40,7 @@ func (t *tproxy) RemoveIPWhitelist(cidr string) { cmds.ExecCommands(commands, false) } -func (t *tproxy) GetSetupCommands() SetupCommands { +func (t *tproxy) GetSetupCommands() Setter { commands := ` ip rule add fwmark 0x40/0xc0 table 100 ip route add local 0.0.0.0/0 dev lo table 100 @@ -149,10 +149,13 @@ ip6tables -w 2 -t mangle -A TP_MARK -p udp -m conntrack --ctstate NEW -j MARK -- ip6tables -w 2 -t mangle -A TP_MARK -j CONNMARK --save-mark ` } - return SetupCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } -func (t *tproxy) GetCleanCommands() CleanCommands { +func (t *tproxy) GetCleanCommands() Setter { commands := ` ip rule del fwmark 0x40/0xc0 table 100 ip route del local 0.0.0.0/0 dev lo table 100 @@ -185,5 +188,8 @@ ip6tables -w 2 -t mangle -F TP_MARK ip6tables -w 2 -t mangle -X TP_MARK ` } - return CleanCommands(commands) + return Setter{ + Cmds: commands, + Func: nil, + } } diff --git a/service/core/specialMode/specialMode.go b/service/core/specialMode/specialMode.go index 7e68b5cb..2f4eb048 100644 --- a/service/core/specialMode/specialMode.go +++ b/service/core/specialMode/specialMode.go @@ -26,7 +26,7 @@ func ShouldLocalDnsListen() bool { if setting.Transparent == configure.TransparentClose { return false } - if setting.TransparentType == configure.TransparentTproxy { + if setting.TransparentType != configure.TransparentRedirect { return false } if conf.GetEnvironmentConfig().Lite { diff --git a/service/core/v2ray/asset/dat/gfwlist.go b/service/core/v2ray/asset/dat/gfwlist.go index 27581cbe..93961ffb 100644 --- a/service/core/v2ray/asset/dat/gfwlist.go +++ b/service/core/v2ray/asset/dat/gfwlist.go @@ -169,7 +169,7 @@ func CheckAndUpdateGFWList() (localGFWListVersionAfterUpdate string, err error) setting := configure.GetSettingNotNil() if v2ray.ProcessManager.Running() && //正在使用GFWList模式再重启 (setting.Transparent == configure.TransparentGfwlist || - setting.Transparent == configure.TransparentClose && setting.RulePortMode == configure.GfwlistMode) { + !v2ray.IsTransparentOn() && setting.RulePortMode == configure.GfwlistMode) { err = v2ray.UpdateV2RayConfig() } return diff --git a/service/core/v2ray/transparent.go b/service/core/v2ray/transparent.go index 53bc241b..e9c53b09 100644 --- a/service/core/v2ray/transparent.go +++ b/service/core/v2ray/transparent.go @@ -14,13 +14,14 @@ import ( func DeleteTransparentProxyRules() { removeResolvHijacker() iptables.CloseWatcher() - iptables.Tproxy.GetCleanCommands().Clean() - iptables.Redirect.GetCleanCommands().Clean() - iptables.DropSpoofing.GetCleanCommands().Clean() + iptables.Tproxy.GetCleanCommands().Run(false) + iptables.Redirect.GetCleanCommands().Run(false) + iptables.SystemProxy.GetCleanCommands().Run(false) + iptables.DropSpoofing.GetCleanCommands().Run(false) time.Sleep(100 * time.Millisecond) } -func WriteTransparentProxyRules(preprocess func(c *iptables.SetupCommands)) (err error) { +func WriteTransparentProxyRules() (err error) { defer func() { if err != nil { log.Warn("WriteTransparentProxyRules: %v", err) @@ -28,26 +29,34 @@ func WriteTransparentProxyRules(preprocess func(c *iptables.SetupCommands)) (err } }() if specialMode.ShouldUseSupervisor() { - if err = iptables.DropSpoofing.GetSetupCommands().Setup(preprocess); err != nil { + if err = iptables.DropSpoofing.GetSetupCommands().Run(true); err != nil { log.Warn("DropSpoofing can't be enable: %v", err) return err } } setting := configure.GetSettingNotNil() - if setting.TransparentType == configure.TransparentTproxy { - if err = iptables.Tproxy.GetSetupCommands().Setup(preprocess); err != nil { + switch setting.TransparentType { + case configure.TransparentTproxy: + if err = iptables.Tproxy.GetSetupCommands().Run(true); err != nil { if strings.Contains(err.Error(), "TPROXY") && strings.Contains(err.Error(), "No chain") { err = fmt.Errorf("you does not compile xt_TPROXY in kernel") } return fmt.Errorf("not support \"tproxy\" mode of transparent proxy: %w", err) } iptables.SetWatcher(&iptables.Tproxy) - } else if setting.TransparentType == configure.TransparentRedirect { - if err = iptables.Redirect.GetSetupCommands().Setup(preprocess); err != nil { + case configure.TransparentRedirect: + if err = iptables.Redirect.GetSetupCommands().Run(true); err != nil { return fmt.Errorf("not support \"redirect\" mode of transparent proxy: %w", err) } iptables.SetWatcher(&iptables.Redirect) + case configure.TransparentSystemProxy: + if err = iptables.SystemProxy.GetSetupCommands().Run(true); err != nil { + return fmt.Errorf("not support \"system proxy\" mode of transparent proxy: %w", err) + } + default: + return fmt.Errorf("undefined \"%v\" mode of transparent proxy", setting.TransparentType) } + if specialMode.ShouldLocalDnsListen() { if couldListenLocalhost, e := specialMode.CouldLocalDnsListen(); couldListenLocalhost { if e != nil { @@ -64,9 +73,6 @@ func WriteTransparentProxyRules(preprocess func(c *iptables.SetupCommands)) (err } func CheckAndSetupTransparentProxy(checkRunning bool, setting *configure.Setting) (err error) { - if conf.GetEnvironmentConfig().Lite { - return nil - } if setting != nil { setting.FillEmpty() } else { @@ -74,16 +80,30 @@ func CheckAndSetupTransparentProxy(checkRunning bool, setting *configure.Setting } if (!checkRunning || ProcessManager.Running()) && setting.Transparent != configure.TransparentClose { DeleteTransparentProxyRules() - err = WriteTransparentProxyRules(func(c *iptables.SetupCommands) { - - }) + if setting.TransparentType != configure.TransparentSystemProxy { + return nil + } + err = WriteTransparentProxyRules() } return } func CheckAndStopTransparentProxy() { - if conf.GetEnvironmentConfig().Lite { + if !IsTransparentOn() { return } DeleteTransparentProxyRules() } + +func IsTransparentOn() bool { + setting := configure.GetSettingNotNil() + if setting.Transparent == configure.TransparentClose { + return false + } + if conf.GetEnvironmentConfig().Lite && + setting.TransparentType == configure.TransparentTproxy || + setting.TransparentType == configure.TransparentRedirect { + return false + } + return true +} diff --git a/service/core/v2ray/v2rayTmpl.go b/service/core/v2ray/v2rayTmpl.go index 7e3345d5..ed2ec6e7 100644 --- a/service/core/v2ray/v2rayTmpl.go +++ b/service/core/v2ray/v2rayTmpl.go @@ -464,7 +464,7 @@ func (t *Template) setDNSRouting(routing []coreObj.RoutingRule, supportUDP map[s t.Routing.Rules = append(t.Routing.Rules, dnsOut) } if !supportUDP[firstOutboundTag] { - // find a outbound that supports UDP and redirect all leaky UDP traffic to it + // find an outbound that supports UDP and redirect all leaky UDP traffic to it var found bool for outbound, support := range supportUDP { if support { @@ -490,7 +490,7 @@ func (t *Template) setDNSRouting(routing []coreObj.RoutingRule, supportUDP map[s ) } } else { - if setting.Transparent != configure.TransparentClose { + if IsTransparentOn() { t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{ Type: "field", @@ -825,7 +825,7 @@ func (t *Template) setTransparentRouting() (err error) { } return nil } -func (t *Template) AppendDokodemo(tproxy *string, port int, tag string) { +func (t *Template) AppendDokodemoTProxy(tproxy string, port int, tag string) { dokodemo := coreObj.Inbound{ Listen: "0.0.0.0", Port: port, @@ -837,11 +837,8 @@ func (t *Template) AppendDokodemo(tproxy *string, port int, tag string) { Settings: &coreObj.InboundSettings{Network: "tcp,udp"}, Tag: tag, } - if tproxy != nil { - dokodemo.StreamSettings = &coreObj.StreamSettings{Sockopt: &coreObj.Sockopt{Tproxy: tproxy}} - dokodemo.Settings.FollowRedirect = true - - } + dokodemo.StreamSettings = &coreObj.StreamSettings{Sockopt: &coreObj.Sockopt{Tproxy: &tproxy}} + dokodemo.Settings.FollowRedirect = true t.Inbounds = append(t.Inbounds, dokodemo) } @@ -1031,13 +1028,19 @@ func (t *Template) setInbound() error { t.Inbounds = append(t.Inbounds[:i], t.Inbounds[i+1:]...) } } - if t.Setting.Transparent != configure.TransparentClose { - var tproxy string + if IsTransparentOn() { switch t.Setting.TransparentType { case configure.TransparentTproxy, configure.TransparentRedirect: - tproxy = string(t.Setting.TransparentType) + t.AppendDokodemoTProxy(string(t.Setting.TransparentType), 32345, "transparent") + case configure.TransparentSystemProxy: + t.Inbounds = append(t.Inbounds, coreObj.Inbound{ + Port: 32345, + Protocol: "http", + Listen: "127.0.0.1", + Tag: "transparent", + }) } - t.AppendDokodemo(&tproxy, 32345, "transparent") + } if specialMode.ShouldLocalDnsListen() { if couldListenLocalhost, _ := specialMode.CouldLocalDnsListen(); couldListenLocalhost { @@ -1516,7 +1519,7 @@ func NewTemplate(serverInfos []serverInfo, setting *configure.Setting) (t *Templ return nil, err } //transparent routing - if t.Setting.Transparent != configure.TransparentClose { + if IsTransparentOn() { if err = t.setTransparentRouting(); err != nil { return nil, err } @@ -1702,7 +1705,7 @@ func NewEmptyTemplate(setting *configure.Setting) (t *Template) { } func (t *Template) checkAndSetMark(o *coreObj.OutboundObject, mark int) { - if t.Setting.Transparent == configure.TransparentClose { + if !IsTransparentOn() { return } if o.StreamSettings == nil { diff --git a/service/db/configure/const.go b/service/db/configure/const.go index 1107d75d..7298c400 100644 --- a/service/db/configure/const.go +++ b/service/db/configure/const.go @@ -24,6 +24,7 @@ const ( TransparentTproxy = TransparentType("tproxy") TransparentRedirect = TransparentType("redirect") + TransparentSystemProxy = TransparentType("system_proxy") Default = DefaultYesNo("default") Yes = DefaultYesNo("yes")