| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "crypto/rand" |
| 10 | "crypto/sha256" |
| 11 | "crypto/subtle" |
| 12 | "encoding/base64" |
| 13 | "encoding/json" |
| 14 | "errors" |
| 15 | "io" |
| 16 | "net" |
| 17 | "os" |
| 18 | "path/filepath" |
| 19 | "runtime" |
| 20 | "slices" |
| 21 | "strings" |
| 22 | "sync" |
| 23 | "time" |
| 24 | "unsafe" |
| 25 | |
| 26 | "github.com/Microsoft/go-winio" |
| 27 | "github.com/google/uuid" |
| 28 | "github.com/sylvinus/agent-vm/internal/paths" |
| 29 | "golang.org/x/sys/windows" |
| 30 | ) |
| 31 | |
| 32 | const enrollmentWireLimit = 16 << 10 |
| 33 | |
| 34 | type enrollmentProcess struct { |
| 35 | handle windows.Handle |
| 36 | pid uint32 |
| 37 | started uint64 |
| 38 | image string |
| 39 | } |
| 40 | |
| 41 | func enrollmentProcessFromHandle(handle windows.Handle) (enrollmentProcess, error) { |
| 42 | var value enrollmentProcess |
| 43 | pid, err := windows.GetProcessId(handle) |
| 44 | if err != nil || pid == 0 { |
| 45 | return value, errors.New("enrollment_process_invalid") |
| 46 | } |
| 47 | var created, exited, kernel, user windows.Filetime |
| 48 | if windows.GetProcessTimes(handle, &created, &exited, &kernel, &user) != nil { |
| 49 | return value, errors.New("enrollment_process_invalid") |
| 50 | } |
| 51 | buffer := make([]uint16, 32768) |
| 52 | size := uint32(len(buffer)) |
| 53 | if windows.QueryFullProcessImageName(handle, 0, &buffer[0], &size) != nil || size == 0 || size >= uint32(len(buffer)) { |
| 54 | return value, errors.New("enrollment_process_invalid") |
| 55 | } |
| 56 | value = enrollmentProcess{handle: handle, pid: pid, started: uint64(created.HighDateTime)<<32 | uint64(created.LowDateTime), image: windows.UTF16ToString(buffer[:size])} |
| 57 | return value, nil |
| 58 | } |
| 59 | |
| 60 | func (process enrollmentProcess) alive() bool { |
| 61 | if process.handle == 0 { |
| 62 | return false |
| 63 | } |
| 64 | state, err := windows.WaitForSingleObject(process.handle, 0) |
| 65 | if err != nil || state != uint32(windows.WAIT_TIMEOUT) { |
| 66 | return false |
| 67 | } |
| 68 | fresh, err := enrollmentProcessFromHandle(process.handle) |
| 69 | return err == nil && fresh.pid == process.pid && fresh.started == process.started && strings.EqualFold(fresh.image, process.image) |
| 70 | } |
| 71 | |
| 72 | type windowsHostEnrollment struct { |
| 73 | options WindowsHostEnrollmentOptions |
| 74 | installation Installation |
| 75 | instance, stage string |
| 76 | owner enrollmentProcess |
| 77 | admin enrollmentProcess |
| 78 | guestSID string |
| 79 | finalized bool |
| 80 | mu sync.Mutex |
| 81 | } |
| 82 | |
| 83 | func newWindowsHostEnrollment(options WindowsHostEnrollmentOptions) (*windowsHostEnrollment, error) { |
| 84 | token := windows.GetCurrentProcessToken() |
| 85 | user, err := token.GetTokenUser() |
| 86 | if err != nil || token.IsElevated() || user.User.Sid.String() != options.HostSID || options.ParentPID == 0 || options.VMID == uuid.Nil || options.InstallationID == uuid.Nil || |
| 87 | !filepath.IsAbs(options.Profile) || !filepath.IsAbs(options.State) || strings.ContainsAny(options.Profile+options.State, "\x00\r\n") || |
| 88 | !(strings.HasPrefix(options.HostSID, "S-1-5-21-") || strings.HasPrefix(options.HostSID, "S-1-12-1-")) || |
| 89 | !strings.HasPrefix(options.Pipe, "Cage.Enroll.") || len(options.Pipe) > 180 || strings.ContainsAny(options.Pipe, "\\/:\x00\r\n") { |
| 90 | return nil, errors.New("enrollment_original_user_required") |
| 91 | } |
| 92 | var basic struct{ ExitStatus, PEB, Affinity, Priority, PID, Parent uintptr } |
| 93 | var returned uint32 |
| 94 | if windows.NtQueryInformationProcess(windows.CurrentProcess(), windows.ProcessBasicInformation, unsafe.Pointer(&basic), uint32(unsafe.Sizeof(basic)), &returned) != nil || uint32(basic.Parent) != options.ParentPID { |
| 95 | return nil, errors.New("enrollment_parent_invalid") |
| 96 | } |
| 97 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, options.ParentPID) |
| 98 | if err != nil { |
| 99 | return nil, errors.New("enrollment_parent_invalid") |
| 100 | } |
| 101 | owner, err := enrollmentProcessFromHandle(handle) |
| 102 | if err != nil { |
| 103 | windows.CloseHandle(handle) |
| 104 | return nil, err |
| 105 | } |
| 106 | var parentToken windows.Token |
| 107 | if windows.OpenProcessToken(handle, windows.TOKEN_QUERY, &parentToken) != nil { |
| 108 | windows.CloseHandle(handle) |
| 109 | return nil, errors.New("enrollment_parent_invalid") |
| 110 | } |
| 111 | parentUser, err := parentToken.GetTokenUser() |
| 112 | parentToken.Close() |
| 113 | system, systemErr := windows.GetSystemDirectory() |
| 114 | expected := filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe") |
| 115 | if err != nil || parentUser.User.Sid.String() != options.HostSID || systemErr != nil || !strings.EqualFold(owner.image, expected) || !owner.alive() { |
| 116 | windows.CloseHandle(handle) |
| 117 | return nil, errors.New("enrollment_parent_invalid") |
| 118 | } |
| 119 | profile, err := paths.Resolve(options.Profile) |
| 120 | if err != nil { |
| 121 | windows.CloseHandle(handle) |
| 122 | return nil, errors.New("enrollment_profile_invalid") |
| 123 | } |
| 124 | state, err := paths.Resolve(options.State) |
| 125 | if err != nil { |
| 126 | windows.CloseHandle(handle) |
| 127 | return nil, errors.New("enrollment_profile_invalid") |
| 128 | } |
| 129 | anchor, err := paths.Resolve(filepath.Join(profile, "state")) |
| 130 | if err != nil || !strings.EqualFold(anchor, state) { |
| 131 | windows.CloseHandle(handle) |
| 132 | return nil, errors.New("enrollment_profile_invalid") |
| 133 | } |
| 134 | options.Profile, options.State = profile, state |
| 135 | installation, err := LoadInstallation(profile) |
| 136 | if err != nil || installation == nil || installation.System != Windows11 || installation.ID != options.InstallationID { |
| 137 | windows.CloseHandle(handle) |
| 138 | return nil, errors.New("enrollment_installation_changed") |
| 139 | } |
| 140 | instance := filepath.Join(state, "windows-"+strings.ReplaceAll(options.InstallationID.String(), "-", "")) |
| 141 | value := &windowsHostEnrollment{options: options, installation: *installation, instance: instance, stage: filepath.Join(instance, "cage-workbench", "pair"), owner: owner} |
| 142 | if err = value.assertScope(); err != nil { |
| 143 | windows.CloseHandle(handle) |
| 144 | return nil, err |
| 145 | } |
| 146 | if _, err = os.Lstat(WindowsProfilePath(profile)); !errors.Is(err, os.ErrNotExist) { |
| 147 | windows.CloseHandle(handle) |
| 148 | return nil, errors.New("enrollment_existing_profile_preserved") |
| 149 | } |
| 150 | if binding, err := LoadWindowsProfile(value.stage); err != nil { |
| 151 | windows.CloseHandle(handle) |
| 152 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 153 | } else if binding != nil { |
| 154 | if err = value.bindingValid(*binding); err != nil { |
| 155 | windows.CloseHandle(handle) |
| 156 | return nil, err |
| 157 | } |
| 158 | value.guestSID = binding.GUIUserSID |
| 159 | } |
| 160 | return value, nil |
| 161 | } |
| 162 | |
| 163 | func (value *windowsHostEnrollment) assertScope() error { |
| 164 | if !value.owner.alive() { |
| 165 | return errors.New("enrollment_parent_exited") |
| 166 | } |
| 167 | current, err := LoadInstallation(value.options.Profile) |
| 168 | if err != nil || current == nil || *current != value.installation { |
| 169 | return errors.New("enrollment_installation_changed") |
| 170 | } |
| 171 | receipt, err := os.ReadFile(filepath.Join(value.options.Profile, "windows-install-vm.txt")) |
| 172 | if err == nil && len(receipt) > 80 { |
| 173 | return errors.New("enrollment_vm_changed") |
| 174 | } |
| 175 | id, parse := uuid.Parse(strings.TrimSpace(string(receipt))) |
| 176 | if err != nil || parse != nil || id != value.options.VMID { |
| 177 | return errors.New("enrollment_vm_changed") |
| 178 | } |
| 179 | state, err := paths.Resolve(filepath.Join(value.options.Profile, "state")) |
| 180 | if err != nil || !strings.EqualFold(state, value.options.State) { |
| 181 | return errors.New("enrollment_profile_changed") |
| 182 | } |
| 183 | return nil |
| 184 | } |
| 185 | |
| 186 | func (value *windowsHostEnrollment) bindingValid(binding WindowsProfile) error { |
| 187 | if binding.VMID != value.options.VMID || !strings.EqualFold(filepath.Clean(binding.InstanceDirectory), value.instance) || |
| 188 | !strings.EqualFold(filepath.Clean(binding.RelayExecutable), filepath.Join(value.stage, "Cage.GuestClipboard.exe")) || |
| 189 | !strings.EqualFold(filepath.Clean(binding.PairingFile), filepath.Join(value.stage, "pairing.dpapi")) || |
| 190 | binding.NetworkPairingFile != "" && !strings.EqualFold(filepath.Clean(binding.NetworkPairingFile), filepath.Join(value.stage, "packet.dpapi")) || |
| 191 | value.guestSID != "" && binding.GUIUserSID != value.guestSID { |
| 192 | return errors.New("enrollment_binding_changed") |
| 193 | } |
| 194 | return nil |
| 195 | } |
| 196 | |
| 197 | func (value *windowsHostEnrollment) authorizeAdmin(request windowsHostEnrollmentRequest) error { |
| 198 | if value.admin.handle != 0 || request.PID == 0 || request.ProcessHandle == 0 || request.ProcessHandle > 0x7fffffffffffffff { |
| 199 | return errors.New("enrollment_admin_invalid") |
| 200 | } |
| 201 | handle := windows.Handle(request.ProcessHandle) |
| 202 | process, err := enrollmentProcessFromHandle(handle) |
| 203 | system, systemErr := windows.GetSystemDirectory() |
| 204 | if err != nil || systemErr != nil || process.pid != request.PID || !strings.EqualFold(process.image, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe")) || !process.alive() { |
| 205 | windows.CloseHandle(handle) |
| 206 | return errors.New("enrollment_admin_invalid") |
| 207 | } |
| 208 | value.admin = process |
| 209 | return nil |
| 210 | } |
| 211 | |
| 212 | func cryptHostEnrollment(data []byte, vm uuid.UUID, sid string, protect bool) ([]byte, error) { |
| 213 | input := make([]byte, len(data)) |
| 214 | copy(input, data) |
| 215 | defer clear(input) |
| 216 | entropy := sha256.Sum256([]byte("Cage.HyperV.v1:" + vm.String() + ":" + sid)) |
| 217 | in := windows.DataBlob{Size: uint32(len(input)), Data: &input[0]} |
| 218 | salt := windows.DataBlob{Size: 32, Data: &entropy[0]} |
| 219 | var output windows.DataBlob |
| 220 | var err error |
| 221 | if protect { |
| 222 | err = windows.CryptProtectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output) |
| 223 | } else { |
| 224 | err = windows.CryptUnprotectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output) |
| 225 | } |
| 226 | runtime.KeepAlive(input) |
| 227 | runtime.KeepAlive(entropy) |
| 228 | if output.Data != nil { |
| 229 | defer func() { |
| 230 | if output.Size <= enrollmentWireLimit { |
| 231 | clear(unsafe.Slice(output.Data, int(output.Size))) |
| 232 | } |
| 233 | windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data))) |
| 234 | }() |
| 235 | } |
| 236 | if err != nil || output.Data == nil || output.Size == 0 || output.Size > enrollmentWireLimit { |
| 237 | return nil, errors.New("enrollment_current_user_crypto_failed") |
| 238 | } |
| 239 | result := append([]byte(nil), unsafe.Slice(output.Data, int(output.Size))...) |
| 240 | return result, nil |
| 241 | } |
| 242 | |
| 243 | func (value *windowsHostEnrollment) privateKey(path string) ([]byte, error) { |
| 244 | info, err := os.Lstat(path) |
| 245 | if err != nil || !info.Mode().IsRegular() || info.Size() < 1 || info.Size() > enrollmentWireLimit { |
| 246 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 247 | } |
| 248 | name, _ := windows.UTF16PtrFromString(path) |
| 249 | attributes, err := windows.GetFileAttributes(name) |
| 250 | if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { |
| 251 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 252 | } |
| 253 | sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) |
| 254 | if err != nil { |
| 255 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 256 | } |
| 257 | owner, _, err := sd.Owner() |
| 258 | control, _, controlErr := sd.Control() |
| 259 | acl, _, aclErr := sd.DACL() |
| 260 | if err != nil || owner == nil || owner.String() != value.options.HostSID || controlErr != nil || control&windows.SE_DACL_PROTECTED == 0 || aclErr != nil || acl == nil { |
| 261 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 262 | } |
| 263 | for i := uint32(0); i < uint32(acl.AceCount); i++ { |
| 264 | var ace *windows.ACCESS_ALLOWED_ACE |
| 265 | if windows.GetAce(acl, i, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { |
| 266 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 267 | } |
| 268 | sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) |
| 269 | if sid.String() != value.options.HostSID && !sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) && !sid.IsWellKnown(windows.WinLocalSystemSid) { |
| 270 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 271 | } |
| 272 | } |
| 273 | data, err := os.ReadFile(path) |
| 274 | if err != nil { |
| 275 | return nil, errors.New("enrollment_existing_pairing_preserved") |
| 276 | } |
| 277 | return data, nil |
| 278 | } |
| 279 | |
| 280 | func (value *windowsHostEnrollment) storeKey(ctx context.Context, kind, sid string, key []byte) error { |
| 281 | if ctx.Err() != nil { |
| 282 | return errors.New("enrollment_cancelled") |
| 283 | } |
| 284 | if len(key) != 32 || !windowsGUISID.MatchString(sid) || value.guestSID != "" && value.guestSID != sid { |
| 285 | return errors.New("enrollment_guest_changed") |
| 286 | } |
| 287 | if err := value.assertScope(); err != nil { |
| 288 | return err |
| 289 | } |
| 290 | if !value.admin.alive() { |
| 291 | return errors.New("enrollment_admin_exited") |
| 292 | } |
| 293 | value.guestSID = sid |
| 294 | name := "pairing.dpapi" |
| 295 | if kind == "deliver-packet" { |
| 296 | name = "packet.dpapi" |
| 297 | } |
| 298 | path := filepath.Join(value.stage, name) |
| 299 | if _, err := os.Lstat(path); err == nil { |
| 300 | data, err := value.privateKey(path) |
| 301 | if err != nil { |
| 302 | return err |
| 303 | } |
| 304 | old, err := cryptHostEnrollment(data, value.options.VMID, sid, false) |
| 305 | if err != nil { |
| 306 | return err |
| 307 | } |
| 308 | defer clear(old) |
| 309 | if subtle.ConstantTimeCompare(old, key) != 1 { |
| 310 | return errors.New("enrollment_existing_pairing_preserved") |
| 311 | } |
| 312 | return nil |
| 313 | } else if !errors.Is(err, os.ErrNotExist) { |
| 314 | return errors.New("enrollment_existing_pairing_preserved") |
| 315 | } |
| 316 | stage, err := paths.Resolve(value.stage) |
| 317 | if err != nil || !strings.EqualFold(stage, value.stage) { |
| 318 | return errors.New("enrollment_profile_changed") |
| 319 | } |
| 320 | data, err := cryptHostEnrollment(key, value.options.VMID, sid, true) |
| 321 | if err != nil { |
| 322 | return err |
| 323 | } |
| 324 | sd, err := windows.SecurityDescriptorFromString("O:" + value.options.HostSID + "D:P(A;;FA;;;" + value.options.HostSID + ")(A;;FA;;;SY)(A;;FA;;;BA)") |
| 325 | if err != nil { |
| 326 | return errors.New("enrollment_permissions_invalid") |
| 327 | } |
| 328 | attributes := windows.SecurityAttributes{Length: uint32(unsafe.Sizeof(windows.SecurityAttributes{})), SecurityDescriptor: sd} |
| 329 | pathPtr, _ := windows.UTF16PtrFromString(path) |
| 330 | if ctx.Err() != nil || !value.admin.alive() { |
| 331 | return errors.New("enrollment_cancelled") |
| 332 | } |
| 333 | handle, err := windows.CreateFile(pathPtr, windows.FILE_WRITE_DATA|windows.READ_CONTROL|windows.WRITE_DAC|windows.DELETE, 0, &attributes, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL, 0) |
| 334 | runtime.KeepAlive(sd) |
| 335 | if err != nil { |
| 336 | return errors.New("enrollment_pairing_not_saved") |
| 337 | } |
| 338 | file := os.NewFile(uintptr(handle), path) |
| 339 | completed := false |
| 340 | defer func() { |
| 341 | if !completed { |
| 342 | discard := byte(1) |
| 343 | _ = windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1) |
| 344 | } |
| 345 | file.Close() |
| 346 | }() |
| 347 | if _, err = file.Write(data); err == nil { |
| 348 | err = file.Sync() |
| 349 | } |
| 350 | if err != nil { |
| 351 | return errors.New("enrollment_pairing_not_saved") |
| 352 | } |
| 353 | if err = value.assertScope(); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if ctx.Err() != nil { |
| 357 | return errors.New("enrollment_cancelled") |
| 358 | } |
| 359 | if !value.admin.alive() { |
| 360 | return errors.New("enrollment_admin_exited") |
| 361 | } |
| 362 | completed = true |
| 363 | return nil |
| 364 | } |
| 365 | |
| 366 | func (value *windowsHostEnrollment) finalize(ctx context.Context) error { |
| 367 | if value.finalized { |
| 368 | return nil |
| 369 | } |
| 370 | ctx, cancel := context.WithTimeout(ctx, 35*time.Second) |
| 371 | defer cancel() |
| 372 | binding, err := LoadWindowsProfile(value.stage) |
| 373 | if err != nil || binding == nil || value.bindingValid(*binding) != nil || binding.GUIUserSID != value.guestSID || binding.NetworkPairingFile == "" { |
| 374 | return errors.New("enrollment_binding_not_ready") |
| 375 | } |
| 376 | for _, name := range []string{"pairing.dpapi", "packet.dpapi"} { |
| 377 | data, err := value.privateKey(filepath.Join(value.stage, name)) |
| 378 | if err != nil { |
| 379 | return err |
| 380 | } |
| 381 | key, err := cryptHostEnrollment(data, value.options.VMID, value.guestSID, false) |
| 382 | if err != nil { |
| 383 | return err |
| 384 | } |
| 385 | valid := len(key) == 32 |
| 386 | clear(key) |
| 387 | if !valid { |
| 388 | return errors.New("enrollment_binding_not_ready") |
| 389 | } |
| 390 | } |
| 391 | var ready bool |
| 392 | for ctx.Err() == nil { |
| 393 | if !value.admin.alive() { |
| 394 | return errors.New("enrollment_admin_exited") |
| 395 | } |
| 396 | if err = value.assertScope(); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | request, requestErr := WindowsRelayCommand(ctx, value.stage, "status") |
| 400 | if requestErr != nil { |
| 401 | return errors.New("enrollment_relay_not_ready") |
| 402 | } |
| 403 | var output boundedEnrollmentOutput |
| 404 | request.Stdout = &output |
| 405 | request.Stderr = io.Discard |
| 406 | if request.Run() == nil { |
| 407 | var report struct { |
| 408 | Version int `json:"version"` |
| 409 | OS string `json:"os"` |
| 410 | VMID string `json:"vm_id"` |
| 411 | SID string `json:"gui_user_sid"` |
| 412 | Available bool `json:"available"` |
| 413 | Capabilities []string `json:"capabilities"` |
| 414 | Browser struct { |
| 415 | Installed bool `json:"installed"` |
| 416 | EditorInstalled bool `json:"editor_installed"` |
| 417 | } `json:"browser"` |
| 418 | Components map[string]struct { |
| 419 | Installed bool `json:"installed"` |
| 420 | Ready bool `json:"ready"` |
| 421 | } `json:"components"` |
| 422 | } |
| 423 | if json.Unmarshal(output.Bytes(), &report) == nil && report.Version == 1 && report.OS == "windows" && report.VMID == value.options.VMID.String() && report.SID == value.guestSID && report.Available && report.Browser.Installed && report.Browser.EditorInstalled { |
| 424 | ready = true |
| 425 | for _, name := range []string{"cli", "terminal", "project-mount", "desktop"} { |
| 426 | component := report.Components[name] |
| 427 | ready = ready && slices.Contains(report.Capabilities, name) && component.Installed && component.Ready |
| 428 | } |
| 429 | if ready { |
| 430 | break |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | select { |
| 435 | case <-ctx.Done(): |
| 436 | case <-time.After(time.Second): |
| 437 | } |
| 438 | } |
| 439 | if !ready || ctx.Err() != nil || !value.admin.alive() { |
| 440 | return errors.New("enrollment_components_not_ready") |
| 441 | } |
| 442 | if err = value.assertScope(); err != nil { |
| 443 | return err |
| 444 | } |
| 445 | var state WindowsVMResourceState |
| 446 | if err = windowsHostManagerCall(ctx, value.options.VMID, "resources", 0, 0, &state); err != nil || state.State != "Running" { |
| 447 | return errors.New("enrollment_manager_not_ready") |
| 448 | } |
| 449 | if err = value.assertScope(); err != nil { |
| 450 | return err |
| 451 | } |
| 452 | if !value.admin.alive() || ctx.Err() != nil { |
| 453 | return errors.New("enrollment_cancelled") |
| 454 | } |
| 455 | if err = BindWindowsProfile(value.options.Profile, *binding); err != nil { |
| 456 | return errors.New("enrollment_profile_not_published") |
| 457 | } |
| 458 | value.finalized = true |
| 459 | return nil |
| 460 | } |
| 461 | |
| 462 | type boundedEnrollmentOutput struct{ bytes.Buffer } |
| 463 | |
| 464 | func (value *boundedEnrollmentOutput) Write(data []byte) (int, error) { |
| 465 | if value.Len()+len(data) > 64<<10 { |
| 466 | return 0, errors.New("enrollment_response_limit") |
| 467 | } |
| 468 | return value.Buffer.Write(data) |
| 469 | } |
| 470 | |
| 471 | func (value *windowsHostEnrollment) connection(ctx context.Context, conn net.Conn, cancel context.CancelFunc) { |
| 472 | defer conn.Close() |
| 473 | _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) |
| 474 | fd, ok := conn.(interface{ Fd() uintptr }) |
| 475 | var pid uint32 |
| 476 | if !ok || windows.GetNamedPipeClientProcessId(windows.Handle(fd.Fd()), &pid) != nil { |
| 477 | return |
| 478 | } |
| 479 | value.mu.Lock() |
| 480 | owner := pid == value.owner.pid && value.owner.alive() |
| 481 | admin := pid == value.admin.pid && value.admin.alive() |
| 482 | value.mu.Unlock() |
| 483 | challenge := make([]byte, 32) |
| 484 | if _, err := rand.Read(challenge); err != nil { |
| 485 | return |
| 486 | } |
| 487 | defer clear(challenge) |
| 488 | write := func(reply windowsHostEnrollmentReply) { reply.Version = 1; _ = json.NewEncoder(conn).Encode(reply) } |
| 489 | write(windowsHostEnrollmentReply{OK: owner || admin, Authorized: owner || admin, Challenge: base64.StdEncoding.EncodeToString(challenge)}) |
| 490 | if !owner && !admin { |
| 491 | return |
| 492 | } |
| 493 | reader := bufio.NewReaderSize(conn, enrollmentWireLimit+1) |
| 494 | line, err := reader.ReadSlice('\n') |
| 495 | if err != nil || len(line) > enrollmentWireLimit { |
| 496 | return |
| 497 | } |
| 498 | var request windowsHostEnrollmentRequest |
| 499 | decoder := json.NewDecoder(bytes.NewReader(line)) |
| 500 | decoder.DisallowUnknownFields() |
| 501 | if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF { |
| 502 | return |
| 503 | } |
| 504 | decoded, err := base64.StdEncoding.DecodeString(request.Challenge) |
| 505 | if err != nil || request.Version != 1 || request.VMID != value.options.VMID || subtle.ConstantTimeCompare(decoded, challenge) != 1 { |
| 506 | return |
| 507 | } |
| 508 | value.mu.Lock() |
| 509 | requestErr := request.validate(value.options.VMID, owner, value.guestSID) |
| 510 | value.mu.Unlock() |
| 511 | if requestErr != nil { |
| 512 | return |
| 513 | } |
| 514 | key := make([]byte, 32) |
| 515 | defer clear(key) |
| 516 | if request.Action == "deliver-gui" || request.Action == "deliver-packet" { |
| 517 | if !admin { |
| 518 | return |
| 519 | } |
| 520 | if _, err = io.ReadFull(reader, key); err != nil { |
| 521 | return |
| 522 | } |
| 523 | } |
| 524 | if reader.Buffered() != 0 { |
| 525 | return |
| 526 | } |
| 527 | _ = conn.SetDeadline(time.Now().Add(45 * time.Second)) |
| 528 | operation, finish := context.WithCancel(ctx) |
| 529 | defer finish() |
| 530 | disconnected := make(chan struct{}) |
| 531 | go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); finish() }() |
| 532 | defer func() { conn.Close(); <-disconnected }() |
| 533 | value.mu.Lock() |
| 534 | defer value.mu.Unlock() |
| 535 | if err = value.assertScope(); err != nil { |
| 536 | write(windowsHostEnrollmentReply{Error: err.Error()}) |
| 537 | return |
| 538 | } |
| 539 | if owner { |
| 540 | switch request.Action { |
| 541 | case "ready": |
| 542 | case "allow-admin": |
| 543 | err = value.authorizeAdmin(request) |
| 544 | case "stop": |
| 545 | cancel() |
| 546 | default: |
| 547 | err = errors.New("enrollment_action_invalid") |
| 548 | } |
| 549 | } else if !value.admin.alive() { |
| 550 | err = errors.New("enrollment_admin_exited") |
| 551 | } else { |
| 552 | switch request.Action { |
| 553 | case "deliver-gui", "deliver-packet": |
| 554 | err = value.storeKey(operation, request.Action, request.GUIUserSID, key) |
| 555 | case "finalize": |
| 556 | if request.GUIUserSID != value.guestSID { |
| 557 | err = errors.New("enrollment_guest_changed") |
| 558 | } else { |
| 559 | err = value.finalize(operation) |
| 560 | } |
| 561 | default: |
| 562 | err = errors.New("enrollment_action_invalid") |
| 563 | } |
| 564 | } |
| 565 | if err != nil { |
| 566 | write(windowsHostEnrollmentReply{Error: "enrollment_not_completed"}) |
| 567 | return |
| 568 | } |
| 569 | write(windowsHostEnrollmentReply{OK: true}) |
| 570 | } |
| 571 | |
| 572 | func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollmentOptions) error { |
| 573 | value, err := newWindowsHostEnrollment(options) |
| 574 | if err != nil { |
| 575 | return err |
| 576 | } |
| 577 | defer windows.CloseHandle(value.owner.handle) |
| 578 | defer func() { |
| 579 | if value.admin.handle != 0 { |
| 580 | windows.CloseHandle(value.admin.handle) |
| 581 | } |
| 582 | }() |
| 583 | ctx, cancel := context.WithCancel(parent) |
| 584 | defer cancel() |
| 585 | |
| 586 | |
| 587 | listener, err := winio.ListenPipe(`\\.\pipe\`+options.Pipe, &winio.PipeConfig{SecurityDescriptor: "O:" + options.HostSID + "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019f;;;" + options.HostSID + ")", InputBufferSize: enrollmentWireLimit, OutputBufferSize: enrollmentWireLimit}) |
| 588 | if err != nil { |
| 589 | return enrollmentPipeError("listen", err) |
| 590 | } |
| 591 | defer listener.Close() |
| 592 | var active sync.WaitGroup |
| 593 | var connections sync.Map |
| 594 | go func() { |
| 595 | ticker := time.NewTicker(200 * time.Millisecond) |
| 596 | defer ticker.Stop() |
| 597 | for { |
| 598 | select { |
| 599 | case <-ctx.Done(): |
| 600 | listener.Close() |
| 601 | connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) |
| 602 | return |
| 603 | case <-ticker.C: |
| 604 | if !value.owner.alive() { |
| 605 | cancel() |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | }() |
| 610 | defer func() { |
| 611 | cancel() |
| 612 | listener.Close() |
| 613 | connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) |
| 614 | active.Wait() |
| 615 | }() |
| 616 | slots := make(chan struct{}, 4) |
| 617 | for { |
| 618 | conn, err := listener.Accept() |
| 619 | if err != nil { |
| 620 | if ctx.Err() != nil { |
| 621 | return nil |
| 622 | } |
| 623 | return enrollmentPipeError("accept", err) |
| 624 | } |
| 625 | select { |
| 626 | case slots <- struct{}{}: |
| 627 | default: |
| 628 | conn.Close() |
| 629 | continue |
| 630 | } |
| 631 | connections.Store(conn, struct{}{}) |
| 632 | active.Add(1) |
| 633 | go func() { |
| 634 | defer active.Done() |
| 635 | defer func() { <-slots; connections.Delete(conn) }() |
| 636 | value.connection(ctx, conn, cancel) |
| 637 | }() |
| 638 | } |
| 639 | } |