| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "runtime" |
| 17 | "strings" |
| 18 | "time" |
| 19 | "unsafe" |
| 20 | |
| 21 | "github.com/Microsoft/go-winio" |
| 22 | "github.com/google/uuid" |
| 23 | "golang.org/x/sys/windows" |
| 24 | ) |
| 25 | |
| 26 | func windowsHostManagerCall(ctx context.Context, id uuid.UUID, operation string, memory, cpus int, result any) error { |
| 27 | request := windowsHostManagerRequest{Version: windowsHostManagerVersion, VMID: id, Operation: operation, MemoryGiB: memory, CPUs: cpus} |
| 28 | return windowsHostManagerRequestCall(ctx, request, result) |
| 29 | } |
| 30 | |
| 31 | func windowsHostManagerRequestCall(ctx context.Context, request windowsHostManagerRequest, result any) error { |
| 32 | id := request.VMID |
| 33 | if err := request.validate(); err != nil { |
| 34 | return errors.New("Windows 客机管理参数无效") |
| 35 | } |
| 36 | ctx, cancel := context.WithTimeout(ctx, 3*time.Minute) |
| 37 | defer cancel() |
| 38 | connect, finish := context.WithTimeout(ctx, 10*time.Second) |
| 39 | level := winio.PipeImpLevelIdentification |
| 40 | if request.Storage != nil && request.Storage.Action == "attach" { |
| 41 | |
| 42 | level = winio.PipeImpLevelImpersonation |
| 43 | } |
| 44 | connection, err := winio.DialPipeAccessImpLevel(connect, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level) |
| 45 | finish() |
| 46 | if err != nil && ctx.Err() == nil { |
| 47 | if startErr := startRegisteredWindowsHostManager(id); startErr == nil { |
| 48 | retry, finish := context.WithTimeout(ctx, 10*time.Second) |
| 49 | connection, err = winio.DialPipeAccessImpLevel(retry, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level) |
| 50 | finish() |
| 51 | } |
| 52 | } |
| 53 | if err != nil { |
| 54 | if ctx.Err() != nil { |
| 55 | return ctx.Err() |
| 56 | } |
| 57 | return errors.New("Windows 系统管理助手尚未连接,请在 Cage 安装流程中完成系统授权或恢复助手;原虚拟机和数据已保留") |
| 58 | } |
| 59 | defer connection.Close() |
| 60 | stop := context.AfterFunc(ctx, func() { _ = connection.Close() }) |
| 61 | defer stop() |
| 62 | if deadline, ok := ctx.Deadline(); ok { |
| 63 | _ = connection.SetDeadline(deadline) |
| 64 | } |
| 65 | if err := verifyWindowsHostManagerPeer(connection, id); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | if err := json.NewEncoder(connection).Encode(request); err != nil { |
| 69 | return errors.New("Windows 系统管理请求没有完整送达") |
| 70 | } |
| 71 | line, err := bufio.NewReaderSize(connection, windowsHostManagerWireLimit).ReadSlice('\n') |
| 72 | if err != nil { |
| 73 | if ctx.Err() != nil { |
| 74 | return ctx.Err() |
| 75 | } |
| 76 | return errors.New("Windows 系统管理结果没有完整返回,现有环境已保留") |
| 77 | } |
| 78 | var response windowsHostManagerResponse |
| 79 | decoder := json.NewDecoder(bytes.NewReader(line)) |
| 80 | decoder.DisallowUnknownFields() |
| 81 | if decoder.Decode(&response) != nil || decoder.Decode(new(any)) != io.EOF || response.Version != windowsHostManagerVersion || response.VMID != id { |
| 82 | return errors.New("Windows 系统管理响应身份或格式不匹配") |
| 83 | } |
| 84 | if err := verifyWindowsHostManagerPeer(connection, id); err != nil { |
| 85 | return err |
| 86 | } |
| 87 | if !response.OK || response.Error != "" { |
| 88 | if response.Error == "storage_pending" { |
| 89 | return errors.New("Windows 客机有待恢复的存储迁移,请重新打开原工作台完成恢复") |
| 90 | } |
| 91 | if response.Error == "vm_running" { |
| 92 | return errors.New("请等待 Windows 客机完整关机,再迁移环境存储") |
| 93 | } |
| 94 | if response.Error == "unauthorized" || response.Error == "permission_denied" { |
| 95 | return errors.New("当前系统用户没有这台 Cage 客机的管理授权") |
| 96 | } |
| 97 | if response.Error == "binding_mismatch" || response.Error == "layout_mismatch" || response.Error == "binding_invalid" { |
| 98 | return errors.New("Windows 客机的登记配置已变化,请核对原虚拟机;现有数据已保留") |
| 99 | } |
| 100 | return errors.New("Windows 系统管理操作未完成,请重试或在设置中导出诊断包;现有环境已保留") |
| 101 | } |
| 102 | if len(response.Result) == 0 || bytes.Equal(bytes.TrimSpace(response.Result), []byte("null")) || result == nil || json.Unmarshal(response.Result, result) != nil { |
| 103 | return errors.New("Windows 系统管理响应缺少实际读回结果") |
| 104 | } |
| 105 | return nil |
| 106 | } |
| 107 | |
| 108 | func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error { |
| 109 | f, ok := connection.(interface{ Fd() uintptr }) |
| 110 | if !ok { |
| 111 | return errors.New("Windows 系统管理通道无法核验") |
| 112 | } |
| 113 | var pid uint32 |
| 114 | if windows.GetNamedPipeServerProcessId(windows.Handle(f.Fd()), &pid) != nil || pid == 0 { |
| 115 | return errors.New("Windows 系统管理进程无法核验") |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) |
| 121 | if err != nil { |
| 122 | return errors.New("Windows 系统管理服务身份无法读取") |
| 123 | } |
| 124 | defer windows.CloseServiceHandle(manager) |
| 125 | name, _ := windows.UTF16PtrFromString("CageHV-" + id.String()) |
| 126 | service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_QUERY_STATUS) |
| 127 | if err != nil { |
| 128 | return errors.New("Windows 系统管理服务未登记或当前用户不可读取") |
| 129 | } |
| 130 | defer windows.CloseServiceHandle(service) |
| 131 | var status windows.SERVICE_STATUS_PROCESS |
| 132 | var needed uint32 |
| 133 | if windows.QueryServiceStatusEx(service, windows.SC_STATUS_PROCESS_INFO, (*byte)(unsafe.Pointer(&status)), uint32(unsafe.Sizeof(status)), &needed) != nil || status.ProcessId != pid || status.CurrentState != windows.SERVICE_RUNNING { |
| 134 | return errors.New("Windows 系统管理通道不属于当前已登记服务") |
| 135 | } |
| 136 | return verifyWindowsHostManagerService(service, id) |
| 137 | } |
| 138 | |
| 139 | func verifyWindowsHostManagerService(service windows.Handle, id uuid.UUID) error { |
| 140 | binaryPath, account, err := windowsHostServiceConfig(service) |
| 141 | if err != nil { |
| 142 | return errors.New("Windows 系统管理服务配置无法核验") |
| 143 | } |
| 144 | if !strings.EqualFold(account, "LocalSystem") && !strings.EqualFold(account, `NT AUTHORITY\SYSTEM`) { |
| 145 | return errors.New("Windows 系统管理服务未使用受限系统入口") |
| 146 | } |
| 147 | program, err := windows.KnownFolderPath(windows.FOLDERID_ProgramFiles, 0) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | expected := filepath.Join(program, "Cage Host Manager", id.String(), "Cage.HyperVManager.exe") |
| 152 | data, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, 0) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | binding := filepath.Join(data, "Cage", "HyperVManager", id.String(), "binding.json") |
| 157 | arguments, err := windows.DecomposeCommandLine(binaryPath) |
| 158 | if err != nil || len(arguments) != 4 || !strings.EqualFold(filepath.Clean(arguments[0]), filepath.Clean(expected)) || arguments[1] != "service" || arguments[2] != "--binding" || !strings.EqualFold(filepath.Clean(arguments[3]), filepath.Clean(binding)) { |
| 159 | return errors.New("Windows 系统管理程序不属于已登记的安装位置") |
| 160 | } |
| 161 | if err := checkWindowsSystemOwnedObject(binding); err != nil { |
| 162 | return err |
| 163 | } |
| 164 | for current := expected; !strings.EqualFold(current, program); current = filepath.Dir(current) { |
| 165 | if current == filepath.Dir(current) { |
| 166 | return fmt.Errorf("Windows 系统管理程序路径无效") |
| 167 | } |
| 168 | if err := checkWindowsSystemOwnedObject(current); err != nil { |
| 169 | return err |
| 170 | } |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 | |
| 175 | |
| 176 | |
| 177 | func startRegisteredWindowsHostManager(id uuid.UUID) error { |
| 178 | binding, err := LoadWindowsHostManagerBinding(WindowsHostManagerBindingPath(id)) |
| 179 | if err != nil { |
| 180 | return err |
| 181 | } |
| 182 | user, err := windows.GetCurrentProcessToken().GetTokenUser() |
| 183 | if err != nil || user.User.Sid.String() != binding.HostSID { |
| 184 | return errors.New("unauthorized") |
| 185 | } |
| 186 | manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | defer windows.CloseServiceHandle(manager) |
| 191 | name, _ := windows.UTF16PtrFromString(WindowsHostManagerServiceName(id)) |
| 192 | service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_START) |
| 193 | if err != nil { |
| 194 | return err |
| 195 | } |
| 196 | defer windows.CloseServiceHandle(service) |
| 197 | if err = verifyWindowsHostManagerService(service, id); err != nil { |
| 198 | return err |
| 199 | } |
| 200 | err = windows.StartService(service, 0, nil) |
| 201 | if errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { |
| 202 | return nil |
| 203 | } |
| 204 | return err |
| 205 | } |
| 206 | |
| 207 | func windowsHostServiceConfig(service windows.Handle) (string, string, error) { |
| 208 | |
| 209 | |
| 210 | |
| 211 | size := uint32(1024) |
| 212 | for size <= windowsHostManagerWireLimit { |
| 213 | buffer := make([]byte, size) |
| 214 | config := (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&buffer[0])) |
| 215 | var needed uint32 |
| 216 | err := windows.QueryServiceConfig(service, config, size, &needed) |
| 217 | if err == nil { |
| 218 | binaryPath, account := windows.UTF16PtrToString(config.BinaryPathName), windows.UTF16PtrToString(config.ServiceStartName) |
| 219 | runtime.KeepAlive(buffer) |
| 220 | return binaryPath, account, nil |
| 221 | } |
| 222 | runtime.KeepAlive(buffer) |
| 223 | if !errors.Is(err, windows.ERROR_INSUFFICIENT_BUFFER) || needed <= size { |
| 224 | return "", "", err |
| 225 | } |
| 226 | size = needed |
| 227 | } |
| 228 | return "", "", errors.New("Windows service configuration exceeds limit") |
| 229 | } |
| 230 | |
| 231 | func checkWindowsSystemOwnedObject(path string) error { |
| 232 | info, err := os.Lstat(path) |
| 233 | if err != nil { |
| 234 | return errors.New("Windows 系统管理程序或目录不可读") |
| 235 | } |
| 236 | ptr, err := windows.UTF16PtrFromString(path) |
| 237 | if err != nil { |
| 238 | return err |
| 239 | } |
| 240 | attributes, err := windows.GetFileAttributes(ptr) |
| 241 | if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || !info.Mode().IsRegular() && !info.IsDir() { |
| 242 | return errors.New("Windows 系统管理程序不能经过目录链接") |
| 243 | } |
| 244 | sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) |
| 245 | if err != nil { |
| 246 | return errors.New("Windows 系统管理程序权限不可读") |
| 247 | } |
| 248 | owner, _, err := sd.Owner() |
| 249 | if err != nil || owner == nil || !owner.IsWellKnown(windows.WinLocalSystemSid) && !owner.IsWellKnown(windows.WinBuiltinAdministratorsSid) { |
| 250 | return errors.New("Windows 系统管理程序未受系统权限保护") |
| 251 | } |
| 252 | acl, _, err := sd.DACL() |
| 253 | if err != nil || acl == nil || acl.AceCount == 0 { |
| 254 | return errors.New("Windows 系统管理程序没有访问限制") |
| 255 | } |
| 256 | const fileDeleteChild = 0x40 |
| 257 | const writes = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | fileDeleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL |
| 258 | for i := uint32(0); i < uint32(acl.AceCount); i++ { |
| 259 | var ace *windows.ACCESS_ALLOWED_ACE |
| 260 | if windows.GetAce(acl, i, &ace) != nil { |
| 261 | return errors.New("Windows 系统管理程序权限无法核验") |
| 262 | } |
| 263 | if ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE { |
| 264 | continue |
| 265 | } |
| 266 | if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { |
| 267 | return errors.New("Windows 系统管理程序含未支持的权限规则") |
| 268 | } |
| 269 | principal := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) |
| 270 | if ace.Mask&writes != 0 && !principal.IsWellKnown(windows.WinLocalSystemSid) && !principal.IsWellKnown(windows.WinBuiltinAdministratorsSid) { |
| 271 | return errors.New("Windows 系统管理程序可被普通用户修改") |
| 272 | } |
| 273 | } |
| 274 | return nil |
| 275 | } |