safeopen.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //go:build windows
  2. package safefile
  3. import (
  4. "errors"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "syscall"
  10. "unicode/utf16"
  11. "unsafe"
  12. "github.com/Microsoft/hcsshim/internal/longpath"
  13. "github.com/Microsoft/hcsshim/internal/winapi"
  14. winio "github.com/Microsoft/go-winio"
  15. )
  16. func OpenRoot(path string) (*os.File, error) {
  17. longpath, err := longpath.LongAbs(path)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return winio.OpenForBackup(longpath, syscall.GENERIC_READ, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, syscall.OPEN_EXISTING)
  22. }
  23. func cleanGoStringRelativePath(path string) (string, error) {
  24. path = filepath.Clean(path)
  25. if strings.Contains(path, ":") {
  26. // Since alternate data streams must follow the file they
  27. // are attached to, finding one here (out of order) is invalid.
  28. return "", errors.New("path contains invalid character `:`")
  29. }
  30. fspath := filepath.FromSlash(path)
  31. if len(fspath) > 0 && fspath[0] == '\\' {
  32. return "", errors.New("expected relative path")
  33. }
  34. return fspath, nil
  35. }
  36. func ntRelativePath(path string) ([]uint16, error) {
  37. fspath, err := cleanGoStringRelativePath(path)
  38. if err != nil {
  39. return nil, err
  40. }
  41. path16 := utf16.Encode(([]rune)(fspath))
  42. if len(path16) > 32767 {
  43. return nil, syscall.ENAMETOOLONG
  44. }
  45. return path16, nil
  46. }
  47. // openRelativeInternal opens a relative path from the given root, failing if
  48. // any of the intermediate path components are reparse points.
  49. func openRelativeInternal(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) {
  50. var (
  51. h uintptr
  52. iosb winapi.IOStatusBlock
  53. oa winapi.ObjectAttributes
  54. )
  55. cleanRelativePath, err := cleanGoStringRelativePath(path)
  56. if err != nil {
  57. return nil, err
  58. }
  59. if root == nil || root.Fd() == 0 {
  60. return nil, errors.New("missing root directory")
  61. }
  62. pathUnicode, err := winapi.NewUnicodeString(cleanRelativePath)
  63. if err != nil {
  64. return nil, err
  65. }
  66. oa.Length = unsafe.Sizeof(oa)
  67. oa.ObjectName = pathUnicode
  68. oa.RootDirectory = uintptr(root.Fd())
  69. oa.Attributes = winapi.OBJ_DONT_REPARSE
  70. status := winapi.NtCreateFile(
  71. &h,
  72. accessMask|syscall.SYNCHRONIZE,
  73. &oa,
  74. &iosb,
  75. nil,
  76. 0,
  77. shareFlags,
  78. createDisposition,
  79. winapi.FILE_OPEN_FOR_BACKUP_INTENT|winapi.FILE_SYNCHRONOUS_IO_NONALERT|flags,
  80. nil,
  81. 0,
  82. )
  83. if status != 0 {
  84. return nil, winapi.RtlNtStatusToDosError(status)
  85. }
  86. fullPath, err := longpath.LongAbs(filepath.Join(root.Name(), path))
  87. if err != nil {
  88. syscall.Close(syscall.Handle(h))
  89. return nil, err
  90. }
  91. return os.NewFile(h, fullPath), nil
  92. }
  93. // OpenRelative opens a relative path from the given root, failing if
  94. // any of the intermediate path components are reparse points.
  95. func OpenRelative(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) {
  96. f, err := openRelativeInternal(path, root, accessMask, shareFlags, createDisposition, flags)
  97. if err != nil {
  98. err = &os.PathError{Op: "open", Path: filepath.Join(root.Name(), path), Err: err}
  99. }
  100. return f, err
  101. }
  102. // LinkRelative creates a hard link from oldname to newname (relative to oldroot
  103. // and newroot), failing if any of the intermediate path components are reparse
  104. // points.
  105. func LinkRelative(oldname string, oldroot *os.File, newname string, newroot *os.File) error {
  106. // Open the old file.
  107. oldf, err := openRelativeInternal(
  108. oldname,
  109. oldroot,
  110. syscall.FILE_WRITE_ATTRIBUTES,
  111. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  112. winapi.FILE_OPEN,
  113. 0,
  114. )
  115. if err != nil {
  116. return &os.LinkError{Op: "link", Old: filepath.Join(oldroot.Name(), oldname), New: filepath.Join(newroot.Name(), newname), Err: err}
  117. }
  118. defer oldf.Close()
  119. // Open the parent of the new file.
  120. var parent *os.File
  121. parentPath := filepath.Dir(newname)
  122. if parentPath != "." {
  123. parent, err = openRelativeInternal(
  124. parentPath,
  125. newroot,
  126. syscall.GENERIC_READ,
  127. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  128. winapi.FILE_OPEN,
  129. winapi.FILE_DIRECTORY_FILE)
  130. if err != nil {
  131. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: err}
  132. }
  133. defer parent.Close()
  134. fi, err := winio.GetFileBasicInfo(parent)
  135. if err != nil {
  136. return err
  137. }
  138. if (fi.FileAttributes & syscall.FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
  139. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: winapi.RtlNtStatusToDosError(winapi.STATUS_REPARSE_POINT_ENCOUNTERED)}
  140. }
  141. } else {
  142. parent = newroot
  143. }
  144. // Issue an NT call to create the link. This will be safe because NT will
  145. // not open any more directories to create the link, so it cannot walk any
  146. // more reparse points.
  147. newbase := filepath.Base(newname)
  148. newbase16, err := ntRelativePath(newbase)
  149. if err != nil {
  150. return err
  151. }
  152. size := int(unsafe.Offsetof(winapi.FileLinkInformation{}.FileName)) + len(newbase16)*2
  153. linkinfoBuffer := winapi.LocalAlloc(0, size)
  154. defer winapi.LocalFree(linkinfoBuffer)
  155. linkinfo := (*winapi.FileLinkInformation)(unsafe.Pointer(linkinfoBuffer))
  156. linkinfo.RootDirectory = parent.Fd()
  157. linkinfo.FileNameLength = uint32(len(newbase16) * 2)
  158. copy(winapi.Uint16BufferToSlice(&linkinfo.FileName[0], len(newbase16)), newbase16)
  159. var iosb winapi.IOStatusBlock
  160. status := winapi.NtSetInformationFile(
  161. oldf.Fd(),
  162. &iosb,
  163. linkinfoBuffer,
  164. uint32(size),
  165. winapi.FileLinkInformationClass,
  166. )
  167. if status != 0 {
  168. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(parent.Name(), newbase), Err: winapi.RtlNtStatusToDosError(status)}
  169. }
  170. return nil
  171. }
  172. // deleteOnClose marks a file to be deleted when the handle is closed.
  173. func deleteOnClose(f *os.File) error {
  174. disposition := winapi.FileDispositionInformationEx{Flags: winapi.FILE_DISPOSITION_DELETE}
  175. var iosb winapi.IOStatusBlock
  176. status := winapi.NtSetInformationFile(
  177. f.Fd(),
  178. &iosb,
  179. uintptr(unsafe.Pointer(&disposition)),
  180. uint32(unsafe.Sizeof(disposition)),
  181. winapi.FileDispositionInformationExClass,
  182. )
  183. if status != 0 {
  184. return winapi.RtlNtStatusToDosError(status)
  185. }
  186. return nil
  187. }
  188. // clearReadOnly clears the readonly attribute on a file.
  189. func clearReadOnly(f *os.File) error {
  190. bi, err := winio.GetFileBasicInfo(f)
  191. if err != nil {
  192. return err
  193. }
  194. if bi.FileAttributes&syscall.FILE_ATTRIBUTE_READONLY == 0 {
  195. return nil
  196. }
  197. sbi := winio.FileBasicInfo{
  198. FileAttributes: bi.FileAttributes &^ syscall.FILE_ATTRIBUTE_READONLY,
  199. }
  200. if sbi.FileAttributes == 0 {
  201. sbi.FileAttributes = syscall.FILE_ATTRIBUTE_NORMAL
  202. }
  203. return winio.SetFileBasicInfo(f, &sbi)
  204. }
  205. // RemoveRelative removes a file or directory relative to a root, failing if any
  206. // intermediate path components are reparse points.
  207. func RemoveRelative(path string, root *os.File) error {
  208. f, err := openRelativeInternal(
  209. path,
  210. root,
  211. winapi.FILE_READ_ATTRIBUTES|winapi.FILE_WRITE_ATTRIBUTES|winapi.DELETE,
  212. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  213. winapi.FILE_OPEN,
  214. winapi.FILE_OPEN_REPARSE_POINT)
  215. if err == nil {
  216. defer f.Close()
  217. err = deleteOnClose(f)
  218. if err == syscall.ERROR_ACCESS_DENIED {
  219. // Maybe the file is marked readonly. Clear the bit and retry.
  220. _ = clearReadOnly(f)
  221. err = deleteOnClose(f)
  222. }
  223. }
  224. if err != nil {
  225. return &os.PathError{Op: "remove", Path: filepath.Join(root.Name(), path), Err: err}
  226. }
  227. return nil
  228. }
  229. // RemoveAllRelative removes a directory tree relative to a root, failing if any
  230. // intermediate path components are reparse points.
  231. func RemoveAllRelative(path string, root *os.File) error {
  232. fi, err := LstatRelative(path, root)
  233. if err != nil {
  234. if os.IsNotExist(err) {
  235. return nil
  236. }
  237. return err
  238. }
  239. fileAttributes := fi.Sys().(*syscall.Win32FileAttributeData).FileAttributes
  240. if fileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 || fileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 {
  241. // If this is a reparse point, it can't have children. Simple remove will do.
  242. err := RemoveRelative(path, root)
  243. if err == nil || os.IsNotExist(err) {
  244. return nil
  245. }
  246. return err
  247. }
  248. // It is necessary to use os.Open as Readdirnames does not work with
  249. // OpenRelative. This is safe because the above lstatrelative fails
  250. // if the target is outside the root, and we know this is not a
  251. // symlink from the above FILE_ATTRIBUTE_REPARSE_POINT check.
  252. fd, err := os.Open(filepath.Join(root.Name(), path))
  253. if err != nil {
  254. if os.IsNotExist(err) {
  255. // Race. It was deleted between the Lstat and Open.
  256. // Return nil per RemoveAll's docs.
  257. return nil
  258. }
  259. return err
  260. }
  261. // Remove contents & return first error.
  262. for {
  263. names, err1 := fd.Readdirnames(100)
  264. for _, name := range names {
  265. err1 := RemoveAllRelative(path+string(os.PathSeparator)+name, root)
  266. if err == nil {
  267. err = err1
  268. }
  269. }
  270. if err1 == io.EOF {
  271. break
  272. }
  273. // If Readdirnames returned an error, use it.
  274. if err == nil {
  275. err = err1
  276. }
  277. if len(names) == 0 {
  278. break
  279. }
  280. }
  281. fd.Close()
  282. // Remove directory.
  283. err1 := RemoveRelative(path, root)
  284. if err1 == nil || os.IsNotExist(err1) {
  285. return nil
  286. }
  287. if err == nil {
  288. err = err1
  289. }
  290. return err
  291. }
  292. // MkdirRelative creates a directory relative to a root, failing if any
  293. // intermediate path components are reparse points.
  294. func MkdirRelative(path string, root *os.File) error {
  295. f, err := openRelativeInternal(
  296. path,
  297. root,
  298. 0,
  299. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  300. winapi.FILE_CREATE,
  301. winapi.FILE_DIRECTORY_FILE)
  302. if err == nil {
  303. f.Close()
  304. } else {
  305. err = &os.PathError{Op: "mkdir", Path: filepath.Join(root.Name(), path), Err: err}
  306. }
  307. return err
  308. }
  309. // MkdirAllRelative creates each directory in the path relative to a root, failing if
  310. // any existing intermediate path components are reparse points.
  311. func MkdirAllRelative(path string, root *os.File) error {
  312. pathParts := strings.Split(filepath.Clean(path), (string)(filepath.Separator))
  313. for index := range pathParts {
  314. partialPath := filepath.Join(pathParts[0 : index+1]...)
  315. stat, err := LstatRelative(partialPath, root)
  316. if err != nil {
  317. if os.IsNotExist(err) {
  318. if err := MkdirRelative(partialPath, root); err != nil {
  319. return err
  320. }
  321. continue
  322. }
  323. return err
  324. }
  325. if !stat.IsDir() {
  326. fullPath := filepath.Join(root.Name(), partialPath)
  327. return &os.PathError{Op: "mkdir", Path: fullPath, Err: syscall.ENOTDIR}
  328. }
  329. }
  330. return nil
  331. }
  332. // LstatRelative performs a stat operation on a file relative to a root, failing
  333. // if any intermediate path components are reparse points.
  334. func LstatRelative(path string, root *os.File) (os.FileInfo, error) {
  335. f, err := openRelativeInternal(
  336. path,
  337. root,
  338. winapi.FILE_READ_ATTRIBUTES,
  339. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  340. winapi.FILE_OPEN,
  341. winapi.FILE_OPEN_REPARSE_POINT)
  342. if err != nil {
  343. return nil, &os.PathError{Op: "stat", Path: filepath.Join(root.Name(), path), Err: err}
  344. }
  345. defer f.Close()
  346. return f.Stat()
  347. }
  348. // EnsureNotReparsePointRelative validates that a given file (relative to a
  349. // root) and all intermediate path components are not a reparse points.
  350. func EnsureNotReparsePointRelative(path string, root *os.File) error {
  351. // Perform an open with OBJ_DONT_REPARSE but without specifying FILE_OPEN_REPARSE_POINT.
  352. f, err := OpenRelative(
  353. path,
  354. root,
  355. 0,
  356. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  357. winapi.FILE_OPEN,
  358. 0)
  359. if err != nil {
  360. return err
  361. }
  362. f.Close()
  363. return nil
  364. }