| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "os/user" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "syscall" |
| 11 | "unsafe" |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | fileAttributeReparsePoint = 0x0400 |
| 16 | |
| 17 | sddlRevision1 = 1 |
| 18 | |
| 19 | seFileObject = 1 |
| 20 | ownerSecurityInfo = 0x00000001 |
| 21 | daclSecurityInfo = 0x00000004 |
| 22 | seDACLPresent uint16 = 0x0004 |
| 23 | |
| 24 | aclSizeInformationClass = 2 |
| 25 | accessAllowedACEType = 0 |
| 26 | accessDeniedACEType = 1 |
| 27 | |
| 28 | tokenOwnerInfoClass = 4 |
| 29 | ) |
| 30 | |
| 31 | var ( |
| 32 | modAdvapi32 = syscall.NewLazyDLL("advapi32.dll") |
| 33 | procConvertStringSecurityDescriptorToSDW = modAdvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") |
| 34 | procGetNamedSecurityInfoW = modAdvapi32.NewProc("GetNamedSecurityInfoW") |
| 35 | procGetSecurityInfo = modAdvapi32.NewProc("GetSecurityInfo") |
| 36 | procGetSecurityDescriptorControl = modAdvapi32.NewProc("GetSecurityDescriptorControl") |
| 37 | procGetAclInformation = modAdvapi32.NewProc("GetAclInformation") |
| 38 | procGetAce = modAdvapi32.NewProc("GetAce") |
| 39 | ) |
| 40 | |
| 41 | type windowsTokenOwner struct { |
| 42 | Owner *syscall.SID |
| 43 | } |
| 44 | |
| 45 | type windowsACLSizeInformation struct { |
| 46 | AceCount uint32 |
| 47 | AceBytesInUse uint32 |
| 48 | AceBytesFree uint32 |
| 49 | } |
| 50 | |
| 51 | type windowsACEHeader struct { |
| 52 | AceType byte |
| 53 | AceFlags byte |
| 54 | AceSize uint16 |
| 55 | } |
| 56 | |
| 57 | type windowsAccessAllowedACE struct { |
| 58 | Header windowsACEHeader |
| 59 | Mask uint32 |
| 60 | SidStart uint32 |
| 61 | } |
| 62 | |
| 63 | func sanitizeUserScope(raw string) string { |
| 64 | var b strings.Builder |
| 65 | for _, r := range raw { |
| 66 | if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' || r == '_' || r == '-' { |
| 67 | b.WriteRune(r) |
| 68 | } |
| 69 | } |
| 70 | return b.String() |
| 71 | } |
| 72 | |
| 73 | func currentWindowsTokenSIDs() (string, string, error) { |
| 74 | token, err := syscall.OpenCurrentProcessToken() |
| 75 | if err != nil { |
| 76 | return "", "", fmt.Errorf("engine: open process token: %w", err) |
| 77 | } |
| 78 | defer func() { _ = token.Close() }() |
| 79 | |
| 80 | tu, err := token.GetTokenUser() |
| 81 | if err != nil || tu == nil || tu.User.Sid == nil { |
| 82 | return "", "", fmt.Errorf("engine: read token user SID: %w", err) |
| 83 | } |
| 84 | userSID, err := tu.User.Sid.String() |
| 85 | if err != nil { |
| 86 | return "", "", fmt.Errorf("engine: format token user SID: %w", err) |
| 87 | } |
| 88 | |
| 89 | ownerSID := userSID |
| 90 | var needed uint32 |
| 91 | _ = syscall.GetTokenInformation(token, tokenOwnerInfoClass, nil, 0, &needed) |
| 92 | if needed > 0 { |
| 93 | buf := make([]byte, needed) |
| 94 | if err := syscall.GetTokenInformation(token, tokenOwnerInfoClass, &buf[0], needed, &needed); err == nil { |
| 95 | to := (*windowsTokenOwner)(unsafe.Pointer(&buf[0])) |
| 96 | if to.Owner != nil { |
| 97 | if s, sErr := to.Owner.String(); sErr == nil && s != "" { |
| 98 | ownerSID = s |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | return userSID, ownerSID, nil |
| 104 | } |
| 105 | |
| 106 | func cacheParentDir(baseDir string) string { |
| 107 | scope := "" |
| 108 | if userSID, _, err := currentWindowsTokenSIDs(); err == nil { |
| 109 | scope = sanitizeUserScope(userSID) |
| 110 | } |
| 111 | if scope == "" { |
| 112 | if u, err := user.Current(); err == nil && u != nil { |
| 113 | scope = sanitizeUserScope(u.Uid) |
| 114 | if scope == "" { |
| 115 | scope = sanitizeUserScope(u.Username) |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | if scope == "" { |
| 120 | scope = sanitizeUserScope(os.Getenv("USERNAME")) |
| 121 | } |
| 122 | if scope == "" { |
| 123 | return filepath.Join(filepath.Clean(baseDir), cacheSubdir) |
| 124 | } |
| 125 | return filepath.Join(filepath.Clean(baseDir), fmt.Sprintf("%s-%s", cacheSubdir, scope)) |
| 126 | } |
| 127 | |
| 128 | func isReparsePoint(info os.FileInfo) bool { |
| 129 | if info.Mode()&os.ModeSymlink != 0 { |
| 130 | return true |
| 131 | } |
| 132 | if attr, ok := info.Sys().(*syscall.Win32FileAttributeData); ok { |
| 133 | return attr.FileAttributes&fileAttributeReparsePoint != 0 |
| 134 | } |
| 135 | return false |
| 136 | } |
| 137 | |
| 138 | func mkdirPrivate(path string) error { |
| 139 | userSID, ownerSID, err := currentWindowsTokenSIDs() |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | sddl := buildPrivateWindowsSDDL(userSID, ownerSID) |
| 144 | sddlPtr, err := syscall.UTF16PtrFromString(sddl) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | var sd uintptr |
| 149 | r1, _, callErr := procConvertStringSecurityDescriptorToSDW.Call( |
| 150 | uintptr(unsafe.Pointer(sddlPtr)), |
| 151 | uintptr(sddlRevision1), |
| 152 | uintptr(unsafe.Pointer(&sd)), |
| 153 | 0, |
| 154 | ) |
| 155 | if r1 == 0 { |
| 156 | return fmt.Errorf("engine: build private Windows security descriptor: %w", callErr) |
| 157 | } |
| 158 | defer func() { _, _ = syscall.LocalFree(syscall.Handle(sd)) }() |
| 159 | |
| 160 | pathPtr, err := syscall.UTF16PtrFromString(path) |
| 161 | if err != nil { |
| 162 | return err |
| 163 | } |
| 164 | sa := syscall.SecurityAttributes{ |
| 165 | Length: uint32(unsafe.Sizeof(syscall.SecurityAttributes{})), |
| 166 | SecurityDescriptor: sd, |
| 167 | } |
| 168 | if err := syscall.CreateDirectory(pathPtr, &sa); err != nil { |
| 169 | return &os.PathError{Op: "mkdir", Path: path, Err: err} |
| 170 | } |
| 171 | return nil |
| 172 | } |
| 173 | |
| 174 | func ensurePrivateParentDir(parent string) error { |
| 175 | if err := os.MkdirAll(filepath.Dir(parent), 0o700); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | if err := mkdirPrivate(parent); err != nil && !errors.Is(err, os.ErrExist) && !errors.Is(err, syscall.ERROR_ALREADY_EXISTS) { |
| 179 | return err |
| 180 | } |
| 181 | return verifyPrivateDir(parent) |
| 182 | } |
| 183 | |
| 184 | func verifyWindowsObjectSecurity(path string) error { |
| 185 | pathPtr, err := syscall.UTF16PtrFromString(path) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | var ( |
| 190 | ownerSIDPtr *syscall.SID |
| 191 | dacl uintptr |
| 192 | sd uintptr |
| 193 | ) |
| 194 | status, _, _ := procGetNamedSecurityInfoW.Call( |
| 195 | uintptr(unsafe.Pointer(pathPtr)), |
| 196 | uintptr(seFileObject), |
| 197 | uintptr(ownerSecurityInfo|daclSecurityInfo), |
| 198 | uintptr(unsafe.Pointer(&ownerSIDPtr)), |
| 199 | 0, |
| 200 | uintptr(unsafe.Pointer(&dacl)), |
| 201 | 0, |
| 202 | uintptr(unsafe.Pointer(&sd)), |
| 203 | ) |
| 204 | if status != 0 { |
| 205 | return fmt.Errorf("engine: read Windows security info for %s: %w", path, syscall.Errno(status)) |
| 206 | } |
| 207 | defer func() { _, _ = syscall.LocalFree(syscall.Handle(sd)) }() |
| 208 | return verifyWindowsSecurityDescriptor(path, ownerSIDPtr, dacl, sd) |
| 209 | } |
| 210 | |
| 211 | func verifyWindowsHandleSecurity(handle syscall.Handle, path string) error { |
| 212 | var ( |
| 213 | ownerSIDPtr *syscall.SID |
| 214 | dacl uintptr |
| 215 | sd uintptr |
| 216 | ) |
| 217 | status, _, _ := procGetSecurityInfo.Call( |
| 218 | uintptr(handle), |
| 219 | uintptr(seFileObject), |
| 220 | uintptr(ownerSecurityInfo|daclSecurityInfo), |
| 221 | uintptr(unsafe.Pointer(&ownerSIDPtr)), |
| 222 | 0, |
| 223 | uintptr(unsafe.Pointer(&dacl)), |
| 224 | 0, |
| 225 | uintptr(unsafe.Pointer(&sd)), |
| 226 | ) |
| 227 | if status != 0 { |
| 228 | return fmt.Errorf("engine: read Windows handle security info for %s: %w", path, syscall.Errno(status)) |
| 229 | } |
| 230 | defer func() { _, _ = syscall.LocalFree(syscall.Handle(sd)) }() |
| 231 | return verifyWindowsSecurityDescriptor(path, ownerSIDPtr, dacl, sd) |
| 232 | } |
| 233 | |
| 234 | func verifyWindowsSecurityDescriptor(path string, ownerSIDPtr *syscall.SID, dacl, sd uintptr) error { |
| 235 | userSID, tokenOwnerSID, err := currentWindowsTokenSIDs() |
| 236 | if err != nil { |
| 237 | return err |
| 238 | } |
| 239 | if ownerSIDPtr == nil { |
| 240 | return fmt.Errorf("engine: cache path %s has no owner SID", path) |
| 241 | } |
| 242 | objOwner, err := ownerSIDPtr.String() |
| 243 | if err != nil { |
| 244 | return fmt.Errorf("engine: decode owner SID for %s: %w", path, err) |
| 245 | } |
| 246 | if !strings.EqualFold(objOwner, userSID) && !strings.EqualFold(objOwner, tokenOwnerSID) { |
| 247 | return fmt.Errorf("engine: cache path %s is owned by unexpected principal %s", path, objOwner) |
| 248 | } |
| 249 | |
| 250 | var ( |
| 251 | control uint16 |
| 252 | rev uint32 |
| 253 | ) |
| 254 | r1, _, callErr := procGetSecurityDescriptorControl.Call( |
| 255 | sd, |
| 256 | uintptr(unsafe.Pointer(&control)), |
| 257 | uintptr(unsafe.Pointer(&rev)), |
| 258 | ) |
| 259 | if r1 == 0 { |
| 260 | return fmt.Errorf("engine: inspect security descriptor control for %s: %w", path, callErr) |
| 261 | } |
| 262 | if control&seDACLPresent == 0 || dacl == 0 { |
| 263 | return fmt.Errorf("engine: cache path %s has a null or missing DACL", path) |
| 264 | } |
| 265 | |
| 266 | var aclSize windowsACLSizeInformation |
| 267 | r1, _, callErr = procGetAclInformation.Call( |
| 268 | dacl, |
| 269 | uintptr(unsafe.Pointer(&aclSize)), |
| 270 | uintptr(unsafe.Sizeof(aclSize)), |
| 271 | uintptr(aclSizeInformationClass), |
| 272 | ) |
| 273 | if r1 == 0 { |
| 274 | return fmt.Errorf("engine: read DACL size for %s: %w", path, callErr) |
| 275 | } |
| 276 | |
| 277 | minACESize := uint16(unsafe.Sizeof(windowsAccessAllowedACE{})) |
| 278 | for i := uint32(0); i < aclSize.AceCount; i++ { |
| 279 | var hdr *windowsACEHeader |
| 280 | r1, _, callErr = procGetAce.Call(dacl, uintptr(i), uintptr(unsafe.Pointer(&hdr))) |
| 281 | if r1 == 0 || hdr == nil { |
| 282 | return fmt.Errorf("engine: read DACL entry %d for %s: %w", i, path, callErr) |
| 283 | } |
| 284 | if hdr.AceType == accessDeniedACEType { |
| 285 | continue |
| 286 | } |
| 287 | if hdr.AceType != accessAllowedACEType { |
| 288 | return fmt.Errorf("engine: cache path %s has unsupported ACE type %d", path, hdr.AceType) |
| 289 | } |
| 290 | if hdr.AceSize < minACESize { |
| 291 | return fmt.Errorf("engine: cache path %s has malformed ACE size %d", path, hdr.AceSize) |
| 292 | } |
| 293 | ace := (*windowsAccessAllowedACE)(unsafe.Pointer(hdr)) |
| 294 | trustee := (*syscall.SID)(unsafe.Pointer(&ace.SidStart)) |
| 295 | trusteeSID, err := trustee.String() |
| 296 | if err != nil { |
| 297 | return fmt.Errorf("engine: decode ACE trustee SID for %s: %w", path, err) |
| 298 | } |
| 299 | if !isTrustedWindowsTrusteeSID(trusteeSID, userSID, tokenOwnerSID) && hasUntrustedWindowsWriteAccess(ace.Mask) { |
| 300 | return fmt.Errorf("engine: cache path %s grants write access to untrusted principal %s (mask 0x%08x)", path, trusteeSID, ace.Mask) |
| 301 | } |
| 302 | } |
| 303 | return nil |
| 304 | } |
| 305 | |
| 306 | func verifyPrivateDir(path string) error { |
| 307 | info, err := os.Lstat(path) |
| 308 | if err != nil { |
| 309 | return err |
| 310 | } |
| 311 | if isReparsePoint(info) { |
| 312 | return fmt.Errorf("engine: refusing symlink or junction cache directory %s", path) |
| 313 | } |
| 314 | if !info.IsDir() { |
| 315 | return fmt.Errorf("engine: cache path %s is not a directory", path) |
| 316 | } |
| 317 | return verifyWindowsObjectSecurity(path) |
| 318 | } |
| 319 | |
| 320 | func verifyOwnedRegularFile(info os.FileInfo, path string) error { |
| 321 | if isReparsePoint(info) || !info.Mode().IsRegular() { |
| 322 | return fmt.Errorf("engine: refusing non-regular cache file %s", path) |
| 323 | } |
| 324 | return verifyWindowsObjectSecurity(path) |
| 325 | } |
| 326 | |
| 327 | func openNoFollowFile(path string, flag int, perm os.FileMode) (*os.File, error) { |
| 328 | if info, err := os.Lstat(path); err == nil { |
| 329 | if err := verifyOwnedRegularFile(info, path); err != nil { |
| 330 | return nil, err |
| 331 | } |
| 332 | } else if !errors.Is(err, os.ErrNotExist) { |
| 333 | return nil, err |
| 334 | } |
| 335 | file, err := os.OpenFile(path, flag, perm) |
| 336 | if err != nil { |
| 337 | return nil, err |
| 338 | } |
| 339 | info, err := file.Stat() |
| 340 | if err != nil { |
| 341 | _ = file.Close() |
| 342 | return nil, err |
| 343 | } |
| 344 | if !info.Mode().IsRegular() { |
| 345 | _ = file.Close() |
| 346 | return nil, fmt.Errorf("engine: refusing non-regular cache file %s", path) |
| 347 | } |
| 348 | if err := verifyWindowsHandleSecurity(syscall.Handle(file.Fd()), path); err != nil { |
| 349 | _ = file.Close() |
| 350 | return nil, err |
| 351 | } |
| 352 | return file, nil |
| 353 | } |
| 354 | |
| 355 | func openRootRegularNoFollow(root *os.Root, cacheDir, nativeRel string) (*os.File, error) { |
| 356 | fullPath := filepath.Join(cacheDir, nativeRel) |
| 357 | linfo, err := root.Lstat(nativeRel) |
| 358 | if err != nil { |
| 359 | return nil, err |
| 360 | } |
| 361 | if isReparsePoint(linfo) || !linfo.Mode().IsRegular() { |
| 362 | return nil, fmt.Errorf("engine: refusing non-regular cache file %s", fullPath) |
| 363 | } |
| 364 | file, err := root.Open(nativeRel) |
| 365 | if err != nil { |
| 366 | return nil, err |
| 367 | } |
| 368 | info, err := file.Stat() |
| 369 | if err != nil { |
| 370 | _ = file.Close() |
| 371 | return nil, err |
| 372 | } |
| 373 | if !info.Mode().IsRegular() { |
| 374 | _ = file.Close() |
| 375 | return nil, fmt.Errorf("engine: refusing non-regular cache file %s", fullPath) |
| 376 | } |
| 377 | if err := verifyWindowsHandleSecurity(syscall.Handle(file.Fd()), fullPath); err != nil { |
| 378 | _ = file.Close() |
| 379 | return nil, err |
| 380 | } |
| 381 | return file, nil |
| 382 | } |
| 383 |