| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | "golang.org/x/sys/windows" |
| 19 | ) |
| 20 | |
| 21 | type windowsCoreRecord struct { |
| 22 | PID uint32 `json:"pid"` |
| 23 | Executable string `json:"executable"` |
| 24 | Created int64 `json:"created"` |
| 25 | } |
| 26 | |
| 27 | func windowsCoreRecordPath(profile string) string { |
| 28 | return filepath.Join(Dir(profile), "managed-process.json") |
| 29 | } |
| 30 | |
| 31 | func coreEnvironment(dir string) []string { |
| 32 | env := []string{"HOME=" + dir, "USERPROFILE=" + dir} |
| 33 | for _, key := range []string{"SystemRoot", "WINDIR", "TEMP", "TMP"} { |
| 34 | if value := os.Getenv(key); value != "" { |
| 35 | env = append(env, key+"="+value) |
| 36 | } |
| 37 | } |
| 38 | return env |
| 39 | } |
| 40 | |
| 41 | func identifyCore(handle windows.Handle) (string, int64, error) { |
| 42 | name := make([]uint16, 32768) |
| 43 | size := uint32(len(name)) |
| 44 | if err := windows.QueryFullProcessImageName(handle, 0, &name[0], &size); err != nil { |
| 45 | return "", 0, err |
| 46 | } |
| 47 | var created, exited, kernel, user windows.Filetime |
| 48 | if err := windows.GetProcessTimes(handle, &created, &exited, &kernel, &user); err != nil { |
| 49 | return "", 0, err |
| 50 | } |
| 51 | return windows.UTF16ToString(name[:size]), created.Nanoseconds(), nil |
| 52 | } |
| 53 | |
| 54 | |
| 55 | |
| 56 | func stopWindowsCore(profile string) error { |
| 57 | path := windowsCoreRecordPath(profile) |
| 58 | if _, err := os.Lstat(path); os.IsNotExist(err) { |
| 59 | return nil |
| 60 | } |
| 61 | if err := host.CheckPrivateFile(path); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | b, err := os.ReadFile(path) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | var record windowsCoreRecord |
| 69 | if len(b) > 4096 || json.Unmarshal(b, &record) != nil || record.PID == 0 || record.Created == 0 { |
| 70 | return errors.New("Cage 代理进程记录无效") |
| 71 | } |
| 72 | core, err := CorePath() |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | if !strings.EqualFold(filepath.Clean(core), filepath.Clean(record.Executable)) { |
| 77 | return errors.New("Cage 代理进程不属于当前安装目录") |
| 78 | } |
| 79 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_TERMINATE|windows.SYNCHRONIZE, false, record.PID) |
| 80 | if errors.Is(err, windows.ERROR_INVALID_PARAMETER) { |
| 81 | return os.Remove(path) |
| 82 | } |
| 83 | if errors.Is(err, windows.ERROR_ACCESS_DENIED) && !recordedCoreRunning(record) { |
| 84 | |
| 85 | |
| 86 | return removeStaleCore(profile, path) |
| 87 | } |
| 88 | if err != nil { |
| 89 | return err |
| 90 | } |
| 91 | defer windows.CloseHandle(handle) |
| 92 | image, created, err := identifyCore(handle) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | if !sameCore(record, image, created) { |
| 97 | |
| 98 | |
| 99 | return removeStaleCore(profile, path) |
| 100 | } |
| 101 | var code uint32 |
| 102 | if err := windows.GetExitCodeProcess(handle, &code); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | if code == 259 { |
| 106 | if err := windows.TerminateProcess(handle, 0); err != nil { |
| 107 | return err |
| 108 | } |
| 109 | state, err := windows.WaitForSingleObject(handle, 5000) |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | if state != windows.WAIT_OBJECT_0 { |
| 114 | return errors.New("Cage 代理进程未能及时停止") |
| 115 | } |
| 116 | } |
| 117 | _ = os.Remove(Socket(profile)) |
| 118 | return os.Remove(path) |
| 119 | } |
| 120 | |
| 121 | func sameCore(record windowsCoreRecord, image string, created int64) bool { |
| 122 | return strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) && created == record.Created |
| 123 | } |
| 124 | |
| 125 | func recordedCoreRunning(record windowsCoreRecord) bool { |
| 126 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, record.PID) |
| 127 | if err != nil { |
| 128 | return false |
| 129 | } |
| 130 | defer windows.CloseHandle(handle) |
| 131 | image, created, err := identifyCore(handle) |
| 132 | return err == nil && sameCore(record, image, created) |
| 133 | } |
| 134 | |
| 135 | func removeStaleCore(profile, path string) error { |
| 136 | _ = os.Remove(Socket(profile)) |
| 137 | if err := os.Remove(path); err != nil && !os.IsNotExist(err) { |
| 138 | return err |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | func startWindowsCore(ctx context.Context, profile string, s Store) error { |
| 144 | name, err := PhysicalInterface(ctx) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | path := filepath.Join(Dir(profile), "config.yaml") |
| 149 | bound, _ := BoundInterface(path) |
| 150 | if bound == name && Running(ctx, profile, s) { |
| 151 | return nil |
| 152 | } |
| 153 | if err := Validate(ctx, profile, s); err != nil { |
| 154 | return err |
| 155 | } |
| 156 | if err := stopWindowsCore(profile); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | l, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", s.Port)) |
| 160 | if err != nil { |
| 161 | return errors.New("Cage 代理端口已被占用,请更换独立端口") |
| 162 | } |
| 163 | l.Close() |
| 164 | core, err := CorePath() |
| 165 | if err != nil { |
| 166 | return err |
| 167 | } |
| 168 | if err := host.EnsurePrivateDir(filepath.Dir(Socket(profile))); err != nil { |
| 169 | return err |
| 170 | } |
| 171 | b, err := s.Runtime(profile) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | b, err = BindInterface(b, name) |
| 176 | if err != nil { |
| 177 | return err |
| 178 | } |
| 179 | if err := Write(path, b); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | _ = os.Remove(Socket(profile)) |
| 183 | log := diagnostics.New(profile).Stream("proxy", "warn") |
| 184 | |
| 185 | cmd := exec.Command(core, "-d", Dir(profile), "-f", path) |
| 186 | cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log |
| 187 | cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_NO_WINDOW} |
| 188 | if err := cmd.Start(); err != nil { |
| 189 | _ = log.Close() |
| 190 | return err |
| 191 | } |
| 192 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(cmd.Process.Pid)) |
| 193 | if err != nil { |
| 194 | _ = cmd.Process.Kill() |
| 195 | _ = cmd.Wait() |
| 196 | return err |
| 197 | } |
| 198 | image, created, err := identifyCore(handle) |
| 199 | windows.CloseHandle(handle) |
| 200 | if err != nil { |
| 201 | _ = cmd.Process.Kill() |
| 202 | _ = cmd.Wait() |
| 203 | return err |
| 204 | } |
| 205 | record, _ := json.Marshal(windowsCoreRecord{PID: uint32(cmd.Process.Pid), Executable: image, Created: created}) |
| 206 | if err := Write(windowsCoreRecordPath(profile), record); err != nil { |
| 207 | _ = cmd.Process.Kill() |
| 208 | _ = cmd.Wait() |
| 209 | return err |
| 210 | } |
| 211 | go func() { |
| 212 | err := cmd.Wait() |
| 213 | _ = log.Close() |
| 214 | if err != nil { |
| 215 | _ = diagnostics.New(profile).Record("error", "proxy", "core exited: "+err.Error()) |
| 216 | } |
| 217 | }() |
| 218 | ticker := time.NewTicker(100 * time.Millisecond) |
| 219 | defer ticker.Stop() |
| 220 | timeout := time.NewTimer(15 * time.Second) |
| 221 | defer timeout.Stop() |
| 222 | for { |
| 223 | select { |
| 224 | case <-ctx.Done(): |
| 225 | _ = stopWindowsCore(profile) |
| 226 | return ctx.Err() |
| 227 | case <-timeout.C: |
| 228 | _ = stopWindowsCore(profile) |
| 229 | return errors.New("代理核心启动超时,请查看私有代理日志") |
| 230 | case <-ticker.C: |
| 231 | if Running(ctx, profile, s) { |
| 232 | if err := host.ProtectFile(Socket(profile)); err != nil { |
| 233 | _ = stopWindowsCore(profile) |
| 234 | return err |
| 235 | } |
| 236 | return nil |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func windowsPhysicalInterface(ctx context.Context) (string, error) { |
| 243 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 244 | defer cancel() |
| 245 | |
| 246 | |
| 247 | const script = `$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $candidates=@(Get-NetAdapter -Physical | Where-Object Status -eq 'Up' | ForEach-Object { $a=$_; $ip=Get-NetIPAddress -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.AddressState -eq 'Preferred' -and $_.IPAddress -notlike '169.254.*' }; $routes=Get-NetRoute -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue; if ($ip) { $routes | Where-Object { $_.NextHop -ne '0.0.0.0' } | ForEach-Object { [pscustomobject]@{Name=$a.Name;Index=$a.ifIndex;Metric=($_.RouteMetric+$_.InterfaceMetric)} } } }); $best=$candidates | Sort-Object Metric,Index | Select-Object -First 1; if (!$best) { exit 2 }; $best | ConvertTo-Json -Compress` |
| 248 | root := os.Getenv("SystemRoot") |
| 249 | if root == "" { |
| 250 | root = `C:\Windows` |
| 251 | } |
| 252 | cmd := exec.CommandContext(ctx, filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", script) |
| 253 | cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} |
| 254 | out, err := cmd.Output() |
| 255 | if err != nil { |
| 256 | var exited *exec.ExitError |
| 257 | if errors.As(err, &exited) && exited.ExitCode() == 2 { |
| 258 | return "", errors.New("未找到可用的物理 IPv4 网卡。请连接以太网或 Wi-Fi;仅有虚拟网卡的 Windows 虚拟机和云主机暂不可用。Cage 外网保持关闭") |
| 259 | } |
| 260 | return "", errors.New("无法读取 Windows 物理网卡信息,请确认系统网络服务正常后重试;Cage 外网保持关闭") |
| 261 | } |
| 262 | var selected struct { |
| 263 | Name string |
| 264 | Index int |
| 265 | } |
| 266 | if json.Unmarshal(out, &selected) != nil || selected.Name == "" || selected.Index <= 0 { |
| 267 | return "", errors.New("Windows 物理网卡信息无效") |
| 268 | } |
| 269 | iface, err := net.InterfaceByIndex(selected.Index) |
| 270 | if err != nil || iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { |
| 271 | return "", errors.New("物理网卡已断开,请重试") |
| 272 | } |
| 273 | return iface.Name, nil |
| 274 | } |