| 1 | From 7234d0452e01c04a82f3b4c865e0175b45c29180 Mon Sep 17 00:00:00 2001 |
| 2 | From: Sylvain Zimmer <[email protected]> |
| 3 | Date: Wed, 23 Sep 2026 22:52:23 +0200 |
| 4 | Subject: [PATCH 1/2] reversesshfs: serve only the mounted directory, add |
| 5 | ReadonlyNames |
| 6 | |
| 7 | The builtin driver used sftp.NewServer, which serves the whole host file |
| 8 | system to the guest. It now uses sftp.NewRequestServer with handlers |
| 9 | rooted at LocalPath: reads go through os.Root, and writes open each |
| 10 | parent directory without following any symlink (O_NOFOLLOW on Linux and |
| 11 | macOS, OBJ_DONT_REPARSE on Windows). A path outside the root is denied. |
| 12 | |
| 13 | Setting the mode fails on a symlink, on macOS as on Linux. On Linux |
| 14 | kernels without fchmodat2 (< 6.6), it goes through /proc/self/fd of an |
| 15 | O_PATH fd, as glibc does, so it needs no read permission. |
| 16 | |
| 17 | ReadonlyNames makes a path read-only when any of its components matches |
| 18 | one of these names, compared case-insensitively and ignoring the code |
| 19 | points that HFS+ ignores, as git does. For example, [".git"] keeps the |
| 20 | working tree writable while hooks and config stay read-only. Setting |
| 21 | ReadonlyNames selects the builtin driver in auto mode, and fails with |
| 22 | the OpenSSH driver. |
| 23 | |
| 24 | On Windows, a name that passes this check may still refer to a read-only |
| 25 | entry through its 8.3 short name (CVE-2019-1353), so every handle that a |
| 26 | write goes through is also checked by its normalized name, in which the |
| 27 | file system has expanded short names. Writes to names with a colon |
| 28 | (NTFS streams, CVE-2019-1352) or a backslash are denied. Creating |
| 29 | symlinks is not supported on Windows: it needs a privilege or the |
| 30 | developer mode, and CreateSymbolicLink takes a path. |
| 31 | |
| 32 | Setting the times of a read-only name to its current mtime is a no-op |
| 33 | that succeeds, because this is how the Lima guest agent triggers |
| 34 | IN_ATTRIB for host changes (mountInotify). |
| 35 | |
| 36 | Addresses #6. |
| 37 | |
| 38 | Assisted-by: Claude Opus 5.5 (1M context) <[email protected]> |
| 39 | Signed-off-by: Sylvain Zimmer <[email protected]> |
| 40 | |
| 41 | go.mod | 2 +- |
| 42 | pkg/reversesshfs/reversesshfs.go | 30 +- |
| 43 | pkg/reversesshfs/rooted.go | 252 ++++++++++++ |
| 44 | pkg/reversesshfs/rooted_darwin.go | 34 ++ |
| 45 | pkg/reversesshfs/rooted_darwin_test.go | 16 + |
| 46 | pkg/reversesshfs/rooted_e2e_test.go | 173 ++++++++ |
| 47 | pkg/reversesshfs/rooted_linux.go | 53 +++ |
| 48 | pkg/reversesshfs/rooted_linux_test.go | 59 +++ |
| 49 | pkg/reversesshfs/rooted_others.go | 18 + |
| 50 | pkg/reversesshfs/rooted_test.go | 371 +++++++++++++++++ |
| 51 | pkg/reversesshfs/rooted_unix.go | 264 ++++++++++++ |
| 52 | pkg/reversesshfs/rooted_windows.go | 513 ++++++++++++++++++++++++ |
| 53 | pkg/reversesshfs/rooted_windows_test.go | 170 ++++++++ |
| 54 | 13 files changed, 1943 insertions(+), 12 deletions(-) |
| 55 | create mode 100644 pkg/reversesshfs/rooted.go |
| 56 | create mode 100644 pkg/reversesshfs/rooted_darwin.go |
| 57 | create mode 100644 pkg/reversesshfs/rooted_darwin_test.go |
| 58 | create mode 100644 pkg/reversesshfs/rooted_e2e_test.go |
| 59 | create mode 100644 pkg/reversesshfs/rooted_linux.go |
| 60 | create mode 100644 pkg/reversesshfs/rooted_linux_test.go |
| 61 | create mode 100644 pkg/reversesshfs/rooted_others.go |
| 62 | create mode 100644 pkg/reversesshfs/rooted_test.go |
| 63 | create mode 100644 pkg/reversesshfs/rooted_unix.go |
| 64 | create mode 100644 pkg/reversesshfs/rooted_windows.go |
| 65 | create mode 100644 pkg/reversesshfs/rooted_windows_test.go |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | @@ -6,6 +6,7 @@ require ( |
| 72 | github.com/pkg/sftp v1.13.11 |
| 73 | github.com/sirupsen/logrus v1.9.4 |
| 74 | github.com/urfave/cli/v2 v2.27.7 |
| 75 | + golang.org/x/sys v0.47.0 |
| 76 | ) |
| 77 | |
| 78 | require ( |
| 79 | @@ -14,5 +15,4 @@ require ( |
| 80 | github.com/russross/blackfriday/v2 v2.1.0 // indirect |
| 81 | github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect |
| 82 | golang.org/x/crypto v0.54.0 // indirect |
| 83 | - golang.org/x/sys v0.47.0 // indirect |
| 84 | ) |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | @@ -16,7 +16,6 @@ import ( |
| 90 | |
| 91 | "github.com/lima-vm/sshocker/pkg/ssh" |
| 92 | "github.com/lima-vm/sshocker/pkg/util" |
| 93 | - "github.com/pkg/sftp" |
| 94 | "github.com/sirupsen/logrus" |
| 95 | ) |
| 96 | |
| 97 | @@ -40,6 +39,10 @@ type ReverseSSHFS struct { |
| 98 | sshCmd *exec.Cmd |
| 99 | opensshSftpServerCmd *exec.Cmd |
| 100 | SSHFSAdditionalArgs []string |
| 101 | + |
| 102 | + // ReadonlyNames makes a path read-only when any of its components is one of these names |
| 103 | + // (compared case-insensitively). Requires DriverBuiltin on Linux, macOS, or Windows. |
| 104 | + ReadonlyNames []string |
| 105 | } |
| 106 | |
| 107 | func (rsf *ReverseSSHFS) Prepare() error { |
| 108 | @@ -158,6 +161,10 @@ func (rsf *ReverseSSHFS) Start() error { |
| 109 | case DriverBuiltin, DriverOpensshSftpServer: |
| 110 | // NOP |
| 111 | case "", DriverAuto: |
| 112 | + if len(rsf.ReadonlyNames) > 0 { |
| 113 | + driver = DriverBuiltin |
| 114 | + break |
| 115 | + } |
| 116 | var err error |
| 117 | driver, opensshSftpServerBinary, err = DetectDriver(opensshSftpServerBinary) |
| 118 | if err != nil { |
| 119 | @@ -167,7 +174,13 @@ func (rsf *ReverseSSHFS) Start() error { |
| 120 | default: |
| 121 | return fmt.Errorf("unknown driver %q", driver) |
| 122 | } |
| 123 | - var builtinSftpServer *sftp.Server |
| 124 | + if len(rsf.ReadonlyNames) > 0 && driver != DriverBuiltin { |
| 125 | + return fmt.Errorf("ReadonlyNames requires driver %q, got %q", DriverBuiltin, driver) |
| 126 | + } |
| 127 | + var ( |
| 128 | + builtinSftpServer interface{ Serve() error } |
| 129 | + rooted *rootedHandlers |
| 130 | + ) |
| 131 | switch driver { |
| 132 | case DriverBuiltin: |
| 133 | stdinPipe, err := rsf.sshCmd.StdinPipe() |
| 134 | @@ -182,15 +195,7 @@ func (rsf *ReverseSSHFS) Start() error { |
| 135 | ReadCloser: stdoutPipe, |
| 136 | WriteCloser: stdinPipe, |
| 137 | } |
| 138 | - var sftpOpts []sftp.ServerOption |
| 139 | - if rsf.Readonly { |
| 140 | - sftpOpts = append(sftpOpts, sftp.ReadOnly()) |
| 141 | - } |
| 142 | - // NOTE: sftp.NewServer doesn't support specifying the root. |
| 143 | - // https://github.com/pkg/sftp/pull/238 |
| 144 | - // |
| 145 | - // TODO: use sftp.NewRequestServer with custom handlers to mitigate potential vulnerabilities. |
| 146 | - builtinSftpServer, err = sftp.NewServer(stdio, sftpOpts...) |
| 147 | + builtinSftpServer, rooted, err = newRootedServer(stdio, rsf.LocalPath, rsf.Readonly, rsf.ReadonlyNames) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | @@ -234,6 +239,9 @@ func (rsf *ReverseSSHFS) Start() error { |
| 152 | switch driver { |
| 153 | case DriverBuiltin: |
| 154 | go func() { |
| 155 | + if rooted != nil { |
| 156 | + defer rooted.Close() |
| 157 | + } |
| 158 | if srvErr := builtinSftpServer.Serve(); srvErr != nil { |
| 159 | if errors.Is(srvErr, io.EOF) { |
| 160 | logrus.WithError(srvErr).Debugf("sftp server for %v exited with EOF (negligible)", rsf.LocalPath) |
| 161 | |
| 162 | new file mode 100644 |
| 163 | |
| 164 | |
| 165 | |
| 166 | @@ -0,0 +1,252 @@ |
| 167 | +//go:build linux || darwin || windows |
| 168 | + |
| 169 | +package reversesshfs |
| 170 | + |
| 171 | +import ( |
| 172 | + "errors" |
| 173 | + "io" |
| 174 | + "os" |
| 175 | + "path" |
| 176 | + "strings" |
| 177 | + |
| 178 | + "github.com/pkg/sftp" |
| 179 | +) |
| 180 | + |
| 181 | +// rootedHandlers serves only the files under rootPath. |
| 182 | +// |
| 183 | +// Reads go through os.Root, which follows symlinks but never outside the root. |
| 184 | +// Writes open the parent directory without following any symlink, |
| 185 | +// and are denied when any path component matches readonlyNames. |
| 186 | +// Following no symlink on writes is what prevents the client from |
| 187 | +// swapping a directory for a symlink into a read-only one. |
| 188 | +// The OS-specific part is in rootedSys. |
| 189 | +type rootedHandlers struct { |
| 190 | + rootPath string // slash-separated, cleaned |
| 191 | + root *os.Root |
| 192 | + readonly bool |
| 193 | + readonlyNames []string |
| 194 | + rootedSys |
| 195 | +} |
| 196 | + |
| 197 | +func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, readonlyNames []string) (*sftp.RequestServer, *rootedHandlers, error) { |
| 198 | + root, err := os.OpenRoot(localPath) |
| 199 | + if err != nil { |
| 200 | + return nil, nil, err |
| 201 | + } |
| 202 | + sys, err := openRootedSys(localPath) |
| 203 | + if err != nil { |
| 204 | + root.Close() |
| 205 | + return nil, nil, err |
| 206 | + } |
| 207 | + h := &rootedHandlers{ |
| 208 | + rootPath: slashPath(localPath), |
| 209 | + root: root, |
| 210 | + readonly: readonly, |
| 211 | + readonlyNames: readonlyNames, |
| 212 | + rootedSys: sys, |
| 213 | + } |
| 214 | + handlers := sftp.Handlers{FileGet: h, FilePut: h, FileCmd: h, FileList: h} |
| 215 | + srv := sftp.NewRequestServer(rwc, handlers, sftp.WithStartDirectory(startDirectory(h.rootPath))) |
| 216 | + return srv, h, nil |
| 217 | +} |
| 218 | + |
| 219 | +func (h *rootedHandlers) Close() error { |
| 220 | + return errors.Join(h.root.Close(), h.rootedSys.close()) |
| 221 | +} |
| 222 | + |
| 223 | +// rel maps a request path to a path relative to the root. |
| 224 | +// The result has no "." or ".." component, except "." for the root itself. |
| 225 | +func (h *rootedHandlers) rel(p string) (string, error) { |
| 226 | + if !path.IsAbs(p) { |
| 227 | + p = path.Join(h.rootPath, p) |
| 228 | + } |
| 229 | + p = path.Clean(p) |
| 230 | + if p == h.rootPath { |
| 231 | + return ".", nil |
| 232 | + } |
| 233 | + prefix := h.rootPath |
| 234 | + if prefix != "/" { |
| 235 | + prefix += "/" |
| 236 | + } |
| 237 | + if r, ok := strings.CutPrefix(p, prefix); ok { |
| 238 | + return r, nil |
| 239 | + } |
| 240 | + return "", errDenied |
| 241 | +} |
| 242 | + |
| 243 | +func (h *rootedHandlers) writableRel(p string) (string, error) { |
| 244 | + if h.readonly { |
| 245 | + return "", errDenied |
| 246 | + } |
| 247 | + r, err := h.rel(p) |
| 248 | + if err != nil { |
| 249 | + return "", err |
| 250 | + } |
| 251 | + if h.isReadonlyName(r) || !writableName(r) { |
| 252 | + return "", errDenied |
| 253 | + } |
| 254 | + return r, nil |
| 255 | +} |
| 256 | + |
| 257 | +func (h *rootedHandlers) isReadonlyName(rel string) bool { |
| 258 | + for _, c := range strings.Split(rel, "/") { |
| 259 | + for _, name := range h.readonlyNames { |
| 260 | + if sameName(c, name) { |
| 261 | + return true |
| 262 | + } |
| 263 | + } |
| 264 | + } |
| 265 | + return false |
| 266 | +} |
| 267 | + |
| 268 | +// sameName reports whether a file name may refer to the same entry as name |
| 269 | +// on a case-insensitive (APFS, HFS+, NTFS) file system. |
| 270 | +// The ignored code points are the ones listed in next_hfs_char() of git's utf8.c. |
| 271 | +func sameName(s, name string) bool { |
| 272 | + s = strings.Map(func(r rune) rune { |
| 273 | + switch { |
| 274 | + case r >= 0x200c && r <= 0x200f, r >= 0x202a && r <= 0x202e, r >= 0x206a && r <= 0x206f, r == 0xfeff: |
| 275 | + return -1 |
| 276 | + } |
| 277 | + return r |
| 278 | + }, s) |
| 279 | + return strings.EqualFold(s, name) |
| 280 | +} |
| 281 | + |
| 282 | +// Fileread implements sftp.FileReader. |
| 283 | +func (h *rootedHandlers) Fileread(r *sftp.Request) (io.ReaderAt, error) { |
| 284 | + rel, err := h.rel(r.Filepath) |
| 285 | + if err != nil { |
| 286 | + return nil, err |
| 287 | + } |
| 288 | + return h.root.Open(rel) |
| 289 | +} |
| 290 | + |
| 291 | +// Filewrite implements sftp.FileWriter. |
| 292 | +func (h *rootedHandlers) Filewrite(r *sftp.Request) (io.WriterAt, error) { |
| 293 | + return h.openFile(r) |
| 294 | +} |
| 295 | + |
| 296 | +// OpenFile implements sftp.OpenFileWriter. |
| 297 | +func (h *rootedHandlers) OpenFile(r *sftp.Request) (sftp.WriterAtReaderAt, error) { |
| 298 | + return h.openFile(r) |
| 299 | +} |
| 300 | + |
| 301 | +// Filecmd implements sftp.FileCmder. |
| 302 | +func (h *rootedHandlers) Filecmd(r *sftp.Request) error { |
| 303 | + switch r.Method { |
| 304 | + case "Setstat": |
| 305 | + if h.isNoopTimes(r) { |
| 306 | + return nil |
| 307 | + } |
| 308 | + return h.setstat(r) |
| 309 | + case "Rename": |
| 310 | + return h.rename(r, true) |
| 311 | + case "Link": |
| 312 | + return h.link(r) |
| 313 | + case "Remove", "Rmdir": |
| 314 | + return h.remove(r) |
| 315 | + case "Mkdir": |
| 316 | + return h.mkdir(r) |
| 317 | + case "Symlink": |
| 318 | + return h.symlink(r) |
| 319 | + } |
| 320 | + return sftp.ErrSSHFxOpUnsupported |
| 321 | +} |
| 322 | + |
| 323 | +// PosixRename implements sftp.PosixRenameFileCmder. |
| 324 | +func (h *rootedHandlers) PosixRename(r *sftp.Request) error { |
| 325 | + return h.rename(r, false) |
| 326 | +} |
| 327 | + |
| 328 | +// isNoopTimes reports whether r only sets the access and modification times of a |
| 329 | +// read-only name to its current modification time. Such a request is answered |
| 330 | +// without touching the file, so that the guest kernel still emits IN_ATTRIB: |
| 331 | +// this is how the guest agent relays host inotify events (mountInotify). |
| 332 | +func (h *rootedHandlers) isNoopTimes(r *sftp.Request) bool { |
| 333 | + flags := r.AttrFlags() |
| 334 | + if h.readonly || flags.Size || flags.UidGid || flags.Permissions || !flags.Acmodtime { |
| 335 | + return false |
| 336 | + } |
| 337 | + rel, err := h.rel(r.Filepath) |
| 338 | + if err != nil || !h.isReadonlyName(rel) { |
| 339 | + return false |
| 340 | + } |
| 341 | + fi, err := h.root.Lstat(rel) |
| 342 | + if err != nil { |
| 343 | + return false |
| 344 | + } |
| 345 | + // SFTP v3 times are in seconds. |
| 346 | + mtime := uint32(fi.ModTime().Unix()) |
| 347 | + attrs := r.Attributes() |
| 348 | + return attrs.Atime == mtime && attrs.Mtime == mtime |
| 349 | +} |
| 350 | + |
| 351 | +// Filelist implements sftp.FileLister. |
| 352 | +func (h *rootedHandlers) Filelist(r *sftp.Request) (sftp.ListerAt, error) { |
| 353 | + rel, err := h.rel(r.Filepath) |
| 354 | + if err != nil { |
| 355 | + return nil, err |
| 356 | + } |
| 357 | + switch r.Method { |
| 358 | + case "List": |
| 359 | + f, err := h.root.Open(rel) |
| 360 | + if err != nil { |
| 361 | + return nil, err |
| 362 | + } |
| 363 | + defer f.Close() |
| 364 | + fis, err := f.Readdir(-1) |
| 365 | + if err != nil { |
| 366 | + return nil, err |
| 367 | + } |
| 368 | + return listerAt(fis), nil |
| 369 | + case "Stat": |
| 370 | + fi, err := h.root.Stat(rel) |
| 371 | + if err != nil { |
| 372 | + return nil, err |
| 373 | + } |
| 374 | + return listerAt{fi}, nil |
| 375 | + } |
| 376 | + return nil, sftp.ErrSSHFxOpUnsupported |
| 377 | +} |
| 378 | + |
| 379 | +// Lstat implements sftp.LstatFileLister. |
| 380 | +func (h *rootedHandlers) Lstat(r *sftp.Request) (sftp.ListerAt, error) { |
| 381 | + rel, err := h.rel(r.Filepath) |
| 382 | + if err != nil { |
| 383 | + return nil, err |
| 384 | + } |
| 385 | + fi, err := h.root.Lstat(rel) |
| 386 | + if err != nil { |
| 387 | + return nil, err |
| 388 | + } |
| 389 | + return listerAt{fi}, nil |
| 390 | +} |
| 391 | + |
| 392 | +// Readlink implements sftp.ReadlinkFileLister. |
| 393 | +func (h *rootedHandlers) Readlink(p string) (string, error) { |
| 394 | + rel, err := h.rel(p) |
| 395 | + if err != nil { |
| 396 | + return "", err |
| 397 | + } |
| 398 | + return h.root.Readlink(rel) |
| 399 | +} |
| 400 | + |
| 401 | +// RealPath implements sftp.RealPathFileLister. |
| 402 | +// It does not resolve symlinks, and does not access the file system. |
| 403 | +func (h *rootedHandlers) RealPath(p string) (string, error) { |
| 404 | + return realPath(h.rootPath, p), nil |
| 405 | +} |
| 406 | + |
| 407 | +type listerAt []os.FileInfo |
| 408 | + |
| 409 | +func (l listerAt) ListAt(ls []os.FileInfo, offset int64) (int, error) { |
| 410 | + if offset >= int64(len(l)) { |
| 411 | + return 0, io.EOF |
| 412 | + } |
| 413 | + n := copy(ls, l[offset:]) |
| 414 | + if n < len(ls) { |
| 415 | + return n, io.EOF |
| 416 | + } |
| 417 | + return n, nil |
| 418 | +} |
| 419 | |
| 420 | new file mode 100644 |
| 421 | |
| 422 | |
| 423 | |
| 424 | @@ -0,0 +1,34 @@ |
| 425 | +package reversesshfs |
| 426 | + |
| 427 | +import ( |
| 428 | + "github.com/pkg/sftp" |
| 429 | + "golang.org/x/sys/unix" |
| 430 | +) |
| 431 | + |
| 432 | +func statVFS(st *unix.Statfs_t) *sftp.StatVFS { |
| 433 | + return &sftp.StatVFS{ |
| 434 | + Bsize: uint64(st.Bsize), |
| 435 | + Frsize: uint64(st.Bsize), |
| 436 | + Blocks: st.Blocks, |
| 437 | + Bfree: st.Bfree, |
| 438 | + Bavail: st.Bavail, |
| 439 | + Files: st.Files, |
| 440 | + Ffree: st.Ffree, |
| 441 | + Favail: st.Ffree, |
| 442 | + Flag: uint64(st.Flags), |
| 443 | + Namemax: 1024, |
| 444 | + } |
| 445 | +} |
| 446 | + |
| 447 | +// fchmodatNoFollow never follows a symlink at base, and fails on one, as on Linux. |
| 448 | +// If base is replaced by a symlink after the check, fchmodat changes the mode of the symlink itself. |
| 449 | +func fchmodatNoFollow(dirfd int, base string, mode uint32) error { |
| 450 | + var st unix.Stat_t |
| 451 | + if err := unix.Fstatat(dirfd, base, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { |
| 452 | + return err |
| 453 | + } |
| 454 | + if st.Mode&unix.S_IFMT == unix.S_IFLNK { |
| 455 | + return unix.ELOOP |
| 456 | + } |
| 457 | + return unix.Fchmodat(dirfd, base, mode, unix.AT_SYMLINK_NOFOLLOW) |
| 458 | +} |
| 459 | |
| 460 | new file mode 100644 |
| 461 | |
| 462 | |
| 463 | |
| 464 | @@ -0,0 +1,16 @@ |
| 465 | +package reversesshfs |
| 466 | + |
| 467 | +import ( |
| 468 | + "os" |
| 469 | + "syscall" |
| 470 | + "testing" |
| 471 | +) |
| 472 | + |
| 473 | +func ctime(t *testing.T, p string) syscall.Timespec { |
| 474 | + t.Helper() |
| 475 | + fi, err := os.Lstat(p) |
| 476 | + if err != nil { |
| 477 | + t.Fatal(err) |
| 478 | + } |
| 479 | + return fi.Sys().(*syscall.Stat_t).Ctimespec |
| 480 | +} |
| 481 | |
| 482 | new file mode 100644 |
| 483 | |
| 484 | |
| 485 | |
| 486 | @@ -0,0 +1,173 @@ |
| 487 | +//go:build linux |
| 488 | + |
| 489 | +package reversesshfs |
| 490 | + |
| 491 | +import ( |
| 492 | + "os" |
| 493 | + "os/exec" |
| 494 | + "path/filepath" |
| 495 | + "testing" |
| 496 | + "time" |
| 497 | + |
| 498 | + "github.com/lima-vm/sshocker/pkg/util" |
| 499 | + "golang.org/x/sys/unix" |
| 500 | +) |
| 501 | + |
| 502 | +// TestRootedSSHFS mounts the rooted server with a real sshfs in slave mode. |
| 503 | +// It runs only when $SSHFS names an sshfs binary and FUSE is usable. |
| 504 | +func TestRootedSSHFS(t *testing.T) { |
| 505 | + sshfs := os.Getenv("SSHFS") |
| 506 | + if sshfs == "" { |
| 507 | + t.Skip("SSHFS is not set") |
| 508 | + } |
| 509 | + tmp := t.TempDir() |
| 510 | + root := filepath.Join(tmp, "root") |
| 511 | + mnt := filepath.Join(tmp, "mnt") |
| 512 | + for _, d := range []string{filepath.Join(root, "src"), mnt} { |
| 513 | + if err := os.MkdirAll(d, 0o755); err != nil { |
| 514 | + t.Fatal(err) |
| 515 | + } |
| 516 | + } |
| 517 | + git := func(dir string, args ...string) string { |
| 518 | + t.Helper() |
| 519 | + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) |
| 520 | + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=a", "GIT_AUTHOR_EMAIL=a@a", "GIT_COMMITTER_NAME=a", "GIT_COMMITTER_EMAIL=a@a") |
| 521 | + out, err := cmd.CombinedOutput() |
| 522 | + if err != nil { |
| 523 | + t.Fatalf("git %v: %v: %s", args, err, out) |
| 524 | + } |
| 525 | + return string(out) |
| 526 | + } |
| 527 | + if err := os.WriteFile(filepath.Join(root, "src", "main.go"), []byte("package main\n"), 0o644); err != nil { |
| 528 | + t.Fatal(err) |
| 529 | + } |
| 530 | + git(root, "init", "-q") |
| 531 | + git(root, "add", ".") |
| 532 | + git(root, "commit", "-q", "-m", "init") |
| 533 | + |
| 534 | + cmd := exec.Command(sshfs, ":"+root, mnt, "-f", "-o", "slave") |
| 535 | + stdin, err := cmd.StdinPipe() |
| 536 | + if err != nil { |
| 537 | + t.Fatal(err) |
| 538 | + } |
| 539 | + stdout, err := cmd.StdoutPipe() |
| 540 | + if err != nil { |
| 541 | + t.Fatal(err) |
| 542 | + } |
| 543 | + cmd.Stderr = os.Stderr |
| 544 | + srv, h, err := newRootedServer(&util.RWC{ReadCloser: stdout, WriteCloser: stdin}, root, false, []string{".git"}) |
| 545 | + if err != nil { |
| 546 | + t.Fatal(err) |
| 547 | + } |
| 548 | + if err := cmd.Start(); err != nil { |
| 549 | + t.Fatal(err) |
| 550 | + } |
| 551 | + go func() { |
| 552 | + _ = srv.Serve() |
| 553 | + _ = h.Close() |
| 554 | + }() |
| 555 | + t.Cleanup(func() { |
| 556 | + _ = exec.Command("fusermount3", "-u", mnt).Run() |
| 557 | + _ = cmd.Wait() |
| 558 | + }) |
| 559 | + for i := 0; ; i++ { |
| 560 | + if _, err := os.Stat(filepath.Join(mnt, "src", "main.go")); err == nil { |
| 561 | + break |
| 562 | + } |
| 563 | + if i == 50 { |
| 564 | + t.Fatal("sshfs did not mount") |
| 565 | + } |
| 566 | + time.Sleep(100 * time.Millisecond) |
| 567 | + } |
| 568 | + |
| 569 | + sh := func(script string) error { |
| 570 | + c := exec.Command("sh", "-euc", script) |
| 571 | + c.Dir = mnt |
| 572 | + out, err := c.CombinedOutput() |
| 573 | + t.Logf("%s: %v: %s", script, err, out) |
| 574 | + return err |
| 575 | + } |
| 576 | + allowed := []string{ |
| 577 | + "echo x > src/new.go && cat src/new.go", |
| 578 | + "mkdir -p a/b/c && touch a/b/c/f && rm -rf a", |
| 579 | + "sed -i s/main/foo/ src/main.go", |
| 580 | + "cp -a src src2 && rm -r src2", |
| 581 | + "chmod 600 src/new.go && truncate -s 0 src/new.go", |
| 582 | + "ln -s main.go src/link && readlink src/link && cat src/link && rm src/link", |
| 583 | + "mv src/new.go src/renamed.go && rm src/renamed.go", |
| 584 | + "df .", |
| 585 | + "cat .git/HEAD && ls .git/hooks", |
| 586 | + "git status --short", |
| 587 | + "git log --oneline", |
| 588 | + } |
| 589 | + for _, s := range allowed { |
| 590 | + if err := sh(s); err != nil { |
| 591 | + t.Errorf("%s: %v", s, err) |
| 592 | + } |
| 593 | + } |
| 594 | + denied := []string{ |
| 595 | + "echo evil > .git/hooks/pre-commit", |
| 596 | + "echo evil >> .git/config", |
| 597 | + "mv .git x", |
| 598 | + "rm .git/HEAD", |
| 599 | + "chmod 777 .git/config", |
| 600 | + // Not @0: sshfs replaces a zero time with the current time. |
| 601 | + "touch -d @1 .git/config", |
| 602 | + "mkdir src/.git", |
| 603 | + "ln -s .git g && echo evil > g/hooks/post-checkout", |
| 604 | + "git add src", |
| 605 | + "git commit -q --allow-empty -m evil", |
| 606 | + } |
| 607 | + for _, s := range denied { |
| 608 | + if err := sh(s); err == nil { |
| 609 | + t.Errorf("%s: expected an error", s) |
| 610 | + } |
| 611 | + } |
| 612 | + if fi, err := os.Stat(filepath.Join(root, ".git", "config")); err != nil || fi.ModTime().Unix() == 1 { |
| 613 | + t.Errorf(".git/config times were changed: %v, %v", fi.ModTime(), err) |
| 614 | + } |
| 615 | + if _, err := os.Stat(filepath.Join(root, ".git", "hooks", "pre-commit")); err == nil { |
| 616 | + t.Error("hook was written") |
| 617 | + } |
| 618 | + if n := git(root, "rev-list", "--count", "HEAD"); n != "1\n" { |
| 619 | + t.Errorf("commit count changed: %q", n) |
| 620 | + } |
| 621 | + |
| 622 | + // Relay a host change the way Lima's guest agent does for mountInotify. |
| 623 | + for _, f := range []string{".git/HEAD", "src/main.go"} { |
| 624 | + if err := os.WriteFile(filepath.Join(root, f), []byte("ref: refs/heads/other\n"), 0o644); err != nil { |
| 625 | + t.Fatal(err) |
| 626 | + } |
| 627 | + fi, err := os.Stat(filepath.Join(root, f)) |
| 628 | + if err != nil { |
| 629 | + t.Fatal(err) |
| 630 | + } |
| 631 | + if !gotAttribEvent(t, filepath.Join(mnt, f), fi.ModTime()) { |
| 632 | + t.Errorf("%s: no IN_ATTRIB event in the mount", f) |
| 633 | + } |
| 634 | + } |
| 635 | +} |
| 636 | + |
| 637 | +func gotAttribEvent(t *testing.T, p string, mtime time.Time) bool { |
| 638 | + t.Helper() |
| 639 | + fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) |
| 640 | + if err != nil { |
| 641 | + t.Fatal(err) |
| 642 | + } |
| 643 | + defer unix.Close(fd) |
| 644 | + if _, err := unix.InotifyAddWatch(fd, p, unix.IN_ATTRIB); err != nil { |
| 645 | + t.Fatal(err) |
| 646 | + } |
| 647 | + if err := os.Chtimes(p, mtime, mtime); err != nil { |
| 648 | + t.Logf("chtimes %s: %v", p, err) |
| 649 | + return false |
| 650 | + } |
| 651 | + buf := make([]byte, 4096) |
| 652 | + for range 20 { |
| 653 | + if n, err := unix.Read(fd, buf); err == nil && n > 0 { |
| 654 | + return true |
| 655 | + } |
| 656 | + time.Sleep(50 * time.Millisecond) |
| 657 | + } |
| 658 | + return false |
| 659 | +} |
| 660 | |
| 661 | new file mode 100644 |
| 662 | |
| 663 | |
| 664 | |
| 665 | @@ -0,0 +1,53 @@ |
| 666 | +package reversesshfs |
| 667 | + |
| 668 | +import ( |
| 669 | + "errors" |
| 670 | + "strconv" |
| 671 | + |
| 672 | + "github.com/pkg/sftp" |
| 673 | + "golang.org/x/sys/unix" |
| 674 | +) |
| 675 | + |
| 676 | +func statVFS(st *unix.Statfs_t) *sftp.StatVFS { |
| 677 | + return &sftp.StatVFS{ |
| 678 | + Bsize: uint64(st.Bsize), |
| 679 | + Frsize: uint64(st.Frsize), |
| 680 | + Blocks: st.Blocks, |
| 681 | + Bfree: st.Bfree, |
| 682 | + Bavail: st.Bavail, |
| 683 | + Files: st.Files, |
| 684 | + Ffree: st.Ffree, |
| 685 | + Favail: st.Ffree, |
| 686 | + Flag: uint64(st.Flags), |
| 687 | + Namemax: uint64(st.Namelen), |
| 688 | + } |
| 689 | +} |
| 690 | + |
| 691 | +// fchmodatNoFollow never follows a symlink at base, and fails on one. |
| 692 | +// Only fchmodat2 (kernel 6.6+) supports AT_SYMLINK_NOFOLLOW, and it fails with EOPNOTSUPP on a symlink. |
| 693 | +func fchmodatNoFollow(dirfd int, base string, mode uint32) error { |
| 694 | + err := unix.Fchmodat(dirfd, base, mode, unix.AT_SYMLINK_NOFOLLOW) |
| 695 | + if !errors.Is(err, unix.EOPNOTSUPP) && !errors.Is(err, unix.ENOSYS) { |
| 696 | + return err |
| 697 | + } |
| 698 | + return fchmodatOPath(dirfd, base, mode) |
| 699 | +} |
| 700 | + |
| 701 | +// fchmodatOPath is the fallback of fchmodatNoFollow, as in glibc: |
| 702 | +// fchmod does not work on an O_PATH fd, but chmod on its /proc/self/fd entry does, |
| 703 | +// and unlike opening base for reading, needs no read permission. |
| 704 | +func fchmodatOPath(dirfd int, base string, mode uint32) error { |
| 705 | + fd, err := unix.Openat(dirfd, base, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 706 | + if err != nil { |
| 707 | + return err |
| 708 | + } |
| 709 | + defer unix.Close(fd) |
| 710 | + var st unix.Stat_t |
| 711 | + if err := unix.Fstat(fd, &st); err != nil { |
| 712 | + return err |
| 713 | + } |
| 714 | + if st.Mode&unix.S_IFMT == unix.S_IFLNK { |
| 715 | + return unix.ELOOP |
| 716 | + } |
| 717 | + return unix.Chmod("/proc/self/fd/"+strconv.Itoa(fd), mode) |
| 718 | +} |
| 719 | |
| 720 | new file mode 100644 |
| 721 | |
| 722 | |
| 723 | |
| 724 | @@ -0,0 +1,59 @@ |
| 725 | +package reversesshfs |
| 726 | + |
| 727 | +import ( |
| 728 | + "errors" |
| 729 | + "os" |
| 730 | + "path/filepath" |
| 731 | + "syscall" |
| 732 | + "testing" |
| 733 | + |
| 734 | + "golang.org/x/sys/unix" |
| 735 | +) |
| 736 | + |
| 737 | +func ctime(t *testing.T, p string) syscall.Timespec { |
| 738 | + t.Helper() |
| 739 | + fi, err := os.Lstat(p) |
| 740 | + if err != nil { |
| 741 | + t.Fatal(err) |
| 742 | + } |
| 743 | + return fi.Sys().(*syscall.Stat_t).Ctim |
| 744 | +} |
| 745 | + |
| 746 | +// TestFchmodatOPath runs the fallback for kernels without fchmodat2 (< 6.6) directly, |
| 747 | +// as newer kernels only take it for symlinks. |
| 748 | +func TestFchmodatOPath(t *testing.T) { |
| 749 | + if os.Geteuid() == 0 { |
| 750 | + t.Skip("root bypasses permission checks") |
| 751 | + } |
| 752 | + dir := t.TempDir() |
| 753 | + if err := os.WriteFile(filepath.Join(dir, "file"), []byte("orig"), 0); err != nil { |
| 754 | + t.Fatal(err) |
| 755 | + } |
| 756 | + if err := os.Mkdir(filepath.Join(dir, "dir"), 0); err != nil { |
| 757 | + t.Fatal(err) |
| 758 | + } |
| 759 | + t.Cleanup(func() { _ = os.Chmod(filepath.Join(dir, "dir"), 0o755) }) |
| 760 | + if err := os.Symlink("file", filepath.Join(dir, "link")); err != nil { |
| 761 | + t.Fatal(err) |
| 762 | + } |
| 763 | + dirfd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 764 | + if err != nil { |
| 765 | + t.Fatal(err) |
| 766 | + } |
| 767 | + defer unix.Close(dirfd) |
| 768 | + |
| 769 | + for _, name := range []string{"file", "dir"} { |
| 770 | + if err := fchmodatOPath(dirfd, name, 0o755); err != nil { |
| 771 | + t.Fatalf("%s: %v", name, err) |
| 772 | + } |
| 773 | + if fi, err := os.Lstat(filepath.Join(dir, name)); err != nil || fi.Mode().Perm() != 0o755 { |
| 774 | + t.Fatalf("%s: %v, %v", name, fi, err) |
| 775 | + } |
| 776 | + } |
| 777 | + if err := fchmodatOPath(dirfd, "link", 0o600); !errors.Is(err, unix.ELOOP) { |
| 778 | + t.Fatalf("link: expected ELOOP, got %v", err) |
| 779 | + } |
| 780 | + if fi, err := os.Stat(filepath.Join(dir, "file")); err != nil || fi.Mode().Perm() != 0o755 { |
| 781 | + t.Fatalf("symlink target changed: %v, %v", fi, err) |
| 782 | + } |
| 783 | +} |
| 784 | |
| 785 | new file mode 100644 |
| 786 | |
| 787 | |
| 788 | |
| 789 | @@ -0,0 +1,18 @@ |
| 790 | +//go:build !linux && !darwin && !windows |
| 791 | + |
| 792 | +package reversesshfs |
| 793 | + |
| 794 | +import ( |
| 795 | + "errors" |
| 796 | + "io" |
| 797 | + |
| 798 | + "github.com/pkg/sftp" |
| 799 | +) |
| 800 | + |
| 801 | +type rootedHandlers struct{} |
| 802 | + |
| 803 | +func newRootedServer(io.ReadWriteCloser, string, bool, []string) (*sftp.RequestServer, *rootedHandlers, error) { |
| 804 | + return nil, nil, errors.New("the rooted builtin sftp server is supported only on Linux, macOS, and Windows") |
| 805 | +} |
| 806 | + |
| 807 | +func (*rootedHandlers) Close() error { return nil } |
| 808 | |
| 809 | new file mode 100644 |
| 810 | |
| 811 | |
| 812 | |
| 813 | @@ -0,0 +1,371 @@ |
| 814 | +//go:build linux || darwin || windows |
| 815 | + |
| 816 | +package reversesshfs |
| 817 | + |
| 818 | +import ( |
| 819 | + "io" |
| 820 | + "os" |
| 821 | + "path/filepath" |
| 822 | + "runtime" |
| 823 | + "sync" |
| 824 | + "testing" |
| 825 | + "time" |
| 826 | + |
| 827 | + "github.com/lima-vm/sshocker/pkg/util" |
| 828 | + "github.com/pkg/sftp" |
| 829 | +) |
| 830 | + |
| 831 | +var ( |
| 832 | + zwnj = string(rune(0x200c)) // ignored by HFS+ |
| 833 | + zwj = string(rune(0x200d)) |
| 834 | + bom = string(rune(0xfeff)) |
| 835 | +) |
| 836 | + |
| 837 | +// setupRooted serves <tmp>/root with ".git" read-only, and returns a client |
| 838 | +// that plays the role of a compromised guest sending arbitrary requests. |
| 839 | +// It also creates the symlinks "gitlink" -> ".git" and "configlink" -> ".git/config". |
| 840 | +func setupRooted(t *testing.T, readonly bool) (*sftp.Client, string) { |
| 841 | + t.Helper() |
| 842 | + tmp := t.TempDir() |
| 843 | + root := filepath.Join(tmp, "root") |
| 844 | + for _, d := range []string{filepath.Join(root, ".git", "hooks"), filepath.Join(root, "src"), filepath.Join(tmp, "outside")} { |
| 845 | + if err := os.MkdirAll(d, 0o755); err != nil { |
| 846 | + t.Fatal(err) |
| 847 | + } |
| 848 | + } |
| 849 | + for _, f := range []string{filepath.Join(root, ".git", "config"), filepath.Join(root, "src", "main.go"), filepath.Join(tmp, "outside", "secret")} { |
| 850 | + if err := os.WriteFile(f, []byte("orig"), 0o644); err != nil { |
| 851 | + t.Fatal(err) |
| 852 | + } |
| 853 | + } |
| 854 | + if err := os.Symlink(".git", filepath.Join(root, "gitlink")); err != nil { |
| 855 | + t.Fatal(err) |
| 856 | + } |
| 857 | + if err := os.Symlink(filepath.Join(".git", "config"), filepath.Join(root, "configlink")); err != nil { |
| 858 | + t.Fatal(err) |
| 859 | + } |
| 860 | + c2sR, c2sW := io.Pipe() |
| 861 | + s2cR, s2cW := io.Pipe() |
| 862 | + srv, h, err := newRootedServer(&util.RWC{ReadCloser: c2sR, WriteCloser: s2cW}, root, readonly, []string{".git"}) |
| 863 | + if err != nil { |
| 864 | + t.Fatal(err) |
| 865 | + } |
| 866 | + done := make(chan struct{}) |
| 867 | + go func() { |
| 868 | + defer close(done) |
| 869 | + _ = srv.Serve() |
| 870 | + _ = h.Close() |
| 871 | + }() |
| 872 | + client, err := sftp.NewClientPipe(s2cR, c2sW) |
| 873 | + if err != nil { |
| 874 | + t.Fatal(err) |
| 875 | + } |
| 876 | + t.Cleanup(func() { |
| 877 | + srv.Close() |
| 878 | + client.Close() |
| 879 | + <-done |
| 880 | + }) |
| 881 | + return client, root |
| 882 | +} |
| 883 | + |
| 884 | +func assertUnchanged(t *testing.T, root string) { |
| 885 | + t.Helper() |
| 886 | + fi, err := os.Lstat(filepath.Join(root, ".git")) |
| 887 | + if err != nil || !fi.IsDir() { |
| 888 | + t.Fatalf(".git is no longer a directory: %v, %v", fi, err) |
| 889 | + } |
| 890 | + b, err := os.ReadFile(filepath.Join(root, ".git", "config")) |
| 891 | + if err != nil || string(b) != "orig" { |
| 892 | + t.Fatalf(".git/config changed: %q, %v", b, err) |
| 893 | + } |
| 894 | + wantPerm := os.FileMode(0o644) |
| 895 | + if runtime.GOOS == "windows" { |
| 896 | + wantPerm = 0o666 |
| 897 | + } |
| 898 | + fi, err = os.Stat(filepath.Join(root, ".git", "config")) |
| 899 | + if err != nil || fi.Mode().Perm() != wantPerm { |
| 900 | + t.Fatalf(".git/config mode changed: %v, %v", fi, err) |
| 901 | + } |
| 902 | + b, err = os.ReadFile(filepath.Join(filepath.Dir(root), "outside", "secret")) |
| 903 | + if err != nil || string(b) != "orig" { |
| 904 | + t.Fatalf("outside/secret changed: %q, %v", b, err) |
| 905 | + } |
| 906 | + for dir, n := range map[string]int{".git": 2, ".git/hooks": 0, "../outside": 1} { |
| 907 | + entries, err := os.ReadDir(filepath.Join(root, dir)) |
| 908 | + if err != nil || len(entries) != n { |
| 909 | + t.Fatalf("%s entries changed: %v, %v", dir, entries, err) |
| 910 | + } |
| 911 | + } |
| 912 | +} |
| 913 | + |
| 914 | +func TestRootedAllowsNormalOperations(t *testing.T) { |
| 915 | + c, root := setupRooted(t, false) |
| 916 | + p := func(s string) string { return filepath.Join(root, s) } |
| 917 | + |
| 918 | + f, err := c.Create(p("src/new.go")) |
| 919 | + if err != nil { |
| 920 | + t.Fatal(err) |
| 921 | + } |
| 922 | + if _, err := f.Write([]byte("hello")); err != nil { |
| 923 | + t.Fatal(err) |
| 924 | + } |
| 925 | + if err := f.Chmod(0o600); err != nil { |
| 926 | + t.Fatal(err) |
| 927 | + } |
| 928 | + f.Close() |
| 929 | + if err := c.Truncate(p("src/new.go"), 2); err != nil { |
| 930 | + t.Fatal(err) |
| 931 | + } |
| 932 | + mtime := time.Unix(1_000_000_000, 0) |
| 933 | + if err := c.Chtimes(p("src/new.go"), mtime, mtime); err != nil { |
| 934 | + t.Fatal(err) |
| 935 | + } |
| 936 | + if err := c.Mkdir(p("dir")); err != nil { |
| 937 | + t.Fatal(err) |
| 938 | + } |
| 939 | + if err := c.PosixRename(p("src/new.go"), p("dir/renamed.go")); err != nil { |
| 940 | + t.Fatal(err) |
| 941 | + } |
| 942 | + if err := c.Rename(p("dir/renamed.go"), p("src/main.go")); err == nil { |
| 943 | + t.Fatal("Rename must not replace an existing file") |
| 944 | + } |
| 945 | + names := []string{"dir/hardlink", "dir/renamed.go"} |
| 946 | + statName, wantPerm := "dir/renamed.go", os.FileMode(0o666) // Windows keeps only the owner write bit |
| 947 | + if runtime.GOOS != "windows" { |
| 948 | + if err := c.Symlink("renamed.go", p("dir/link")); err != nil { |
| 949 | + t.Fatal(err) |
| 950 | + } |
| 951 | + if target, err := c.ReadLink(p("dir/link")); err != nil || target != "renamed.go" { |
| 952 | + t.Fatalf("ReadLink: %q, %v", target, err) |
| 953 | + } |
| 954 | + names = append(names, "dir/link") |
| 955 | + statName, wantPerm = "dir/link", 0o600 |
| 956 | + } |
| 957 | + fi, err := c.Stat(p(statName)) |
| 958 | + if err != nil { |
| 959 | + t.Fatal(err) |
| 960 | + } |
| 961 | + if fi.Size() != 2 || fi.Mode().Perm() != wantPerm || !fi.ModTime().Equal(mtime) { |
| 962 | + t.Fatalf("unexpected stat: size=%d mode=%v mtime=%v", fi.Size(), fi.Mode(), fi.ModTime()) |
| 963 | + } |
| 964 | + if err := c.Link(p("dir/renamed.go"), p("dir/hardlink")); err != nil { |
| 965 | + t.Fatal(err) |
| 966 | + } |
| 967 | + entries, err := c.ReadDir(p("dir")) |
| 968 | + if err != nil || len(entries) != len(names) { |
| 969 | + t.Fatalf("ReadDir: %v, %v", entries, err) |
| 970 | + } |
| 971 | + if _, err := c.StatVFS(root); err != nil { |
| 972 | + t.Fatal(err) |
| 973 | + } |
| 974 | + for _, s := range names { |
| 975 | + if err := c.Remove(p(s)); err != nil { |
| 976 | + t.Fatal(err) |
| 977 | + } |
| 978 | + } |
| 979 | + if err := c.RemoveDirectory(p("dir")); err != nil { |
| 980 | + t.Fatal(err) |
| 981 | + } |
| 982 | + // Reading the protected directory, also through an in-root symlink, is allowed. |
| 983 | + rf, err := c.Open(p("configlink")) |
| 984 | + if err != nil { |
| 985 | + t.Fatal(err) |
| 986 | + } |
| 987 | + b, err := io.ReadAll(rf) |
| 988 | + rf.Close() |
| 989 | + if err != nil || string(b) != "orig" { |
| 990 | + t.Fatalf("read .git/config: %q, %v", b, err) |
| 991 | + } |
| 992 | + assertUnchanged(t, root) |
| 993 | +} |
| 994 | + |
| 995 | +func TestRootedChmodWithoutReadPermission(t *testing.T) { |
| 996 | + if runtime.GOOS == "windows" { |
| 997 | + t.Skip("mode bits other than the owner write bit are not supported on Windows") |
| 998 | + } |
| 999 | + if os.Geteuid() == 0 { |
| 1000 | + t.Skip("root bypasses permission checks") |
| 1001 | + } |
| 1002 | + c, root := setupRooted(t, false) |
| 1003 | + for _, s := range []string{"src/main.go", "src"} { |
| 1004 | + p := filepath.Join(root, s) |
| 1005 | + if err := os.Chmod(p, 0); err != nil { |
| 1006 | + t.Fatal(err) |
| 1007 | + } |
| 1008 | + t.Cleanup(func() { _ = os.Chmod(p, 0o755) }) |
| 1009 | + if err := c.Chmod(p, 0o755); err != nil { |
| 1010 | + t.Fatalf("%s: %v", s, err) |
| 1011 | + } |
| 1012 | + if fi, err := os.Stat(p); err != nil || fi.Mode().Perm() != 0o755 { |
| 1013 | + t.Fatalf("%s: %v, %v", s, fi, err) |
| 1014 | + } |
| 1015 | + } |
| 1016 | +} |
| 1017 | + |
| 1018 | +func TestRootedDeniesProtectedWrites(t *testing.T) { |
| 1019 | + type env struct { |
| 1020 | + c *sftp.Client |
| 1021 | + root string |
| 1022 | + } |
| 1023 | + p := func(e env, s string) string { return filepath.Join(e.root, s) } |
| 1024 | + open := func(e env, s string, flags int) error { |
| 1025 | + f, err := e.c.OpenFile(p(e, s), flags) |
| 1026 | + if err == nil { |
| 1027 | + f.Close() |
| 1028 | + } |
| 1029 | + return err |
| 1030 | + } |
| 1031 | + create := func(e env, s string) error { return open(e, s, os.O_RDWR|os.O_CREATE|os.O_TRUNC) } |
| 1032 | + withOutsideLink := func(f func(e env) error) func(e env) error { |
| 1033 | + return func(e env) error { |
| 1034 | + if err := os.Symlink(filepath.Join(e.root, "..", "outside"), p(e, "out")); err != nil { |
| 1035 | + panic(err) |
| 1036 | + } |
| 1037 | + return f(e) |
| 1038 | + } |
| 1039 | + } |
| 1040 | + attempts := []struct { |
| 1041 | + name string |
| 1042 | + f func(e env) error |
| 1043 | + }{ |
| 1044 | + {"create hook", func(e env) error { return create(e, ".git/hooks/pre-commit") }}, |
| 1045 | + {"open config for write", func(e env) error { return open(e, ".git/config", os.O_WRONLY) }}, |
| 1046 | + // On a case-insensitive file system, these would name the existing .git. |
| 1047 | + {"upper case", func(e env) error { return e.c.Mkdir(p(e, "src/.GIT")) }}, |
| 1048 | + {"hfs ignorable", func(e env) error { return e.c.Mkdir(p(e, "src/.g"+zwnj+"it")) }}, |
| 1049 | + {"nested repo", func(e env) error { return e.c.Mkdir(p(e, "src/.git")) }}, |
| 1050 | + {"nested gitfile", func(e env) error { return create(e, "src/.git") }}, |
| 1051 | + {"via dir symlink", func(e env) error { return create(e, "gitlink/hooks/pre-commit") }}, |
| 1052 | + {"via file symlink", func(e env) error { return open(e, "configlink", os.O_WRONLY|os.O_TRUNC) }}, |
| 1053 | + {"hardlink from config", func(e env) error { return e.c.Link(p(e, ".git/config"), p(e, "src/config")) }}, |
| 1054 | + {"hardlink into hooks", func(e env) error { return e.c.Link(p(e, "src/main.go"), p(e, ".git/hooks/x")) }}, |
| 1055 | + {"symlink in hooks", func(e env) error { return e.c.Symlink("/bin/sh", p(e, ".git/hooks/x")) }}, |
| 1056 | + {"rename .git away", func(e env) error { return e.c.PosixRename(p(e, ".git"), p(e, "old")) }}, |
| 1057 | + {"rename into .git", func(e env) error { return e.c.PosixRename(p(e, "src/main.go"), p(e, ".git/hooks/x")) }}, |
| 1058 | + {"rename to nested gitfile", func(e env) error { return e.c.PosixRename(p(e, "src/main.go"), p(e, "src/.git")) }}, |
| 1059 | + {"remove config", func(e env) error { return e.c.Remove(p(e, ".git/config")) }}, |
| 1060 | + {"rmdir hooks", func(e env) error { return e.c.RemoveDirectory(p(e, ".git/hooks")) }}, |
| 1061 | + {"chmod config", func(e env) error { return e.c.Chmod(p(e, ".git/config"), 0o777) }}, |
| 1062 | + {"chmod via symlink", func(e env) error { return e.c.Chmod(p(e, "configlink"), 0o777) }}, |
| 1063 | + {"truncate config", func(e env) error { return e.c.Truncate(p(e, ".git/config"), 0) }}, |
| 1064 | + {"truncate via symlink", func(e env) error { return e.c.Truncate(p(e, "configlink"), 0) }}, |
| 1065 | + {"chtimes config", func(e env) error { return e.c.Chtimes(p(e, ".git/config"), time.Unix(0, 0), time.Unix(0, 0)) }}, |
| 1066 | + {"write outside", func(e env) error { return create(e, "../outside/secret") }}, |
| 1067 | + {"read outside", func(e env) error { return open(e, "../outside/secret", os.O_RDONLY) }}, |
| 1068 | + {"write through outside symlink", withOutsideLink(func(e env) error { return create(e, "out/secret") })}, |
| 1069 | + {"read through outside symlink", withOutsideLink(func(e env) error { return open(e, "out/secret", os.O_RDONLY) })}, |
| 1070 | + } |
| 1071 | + for _, a := range attempts { |
| 1072 | + t.Run(a.name, func(t *testing.T) { |
| 1073 | + c, root := setupRooted(t, false) |
| 1074 | + if err := a.f(env{c, root}); err == nil { |
| 1075 | + t.Error("expected an error") |
| 1076 | + } |
| 1077 | + assertUnchanged(t, root) |
| 1078 | + }) |
| 1079 | + } |
| 1080 | +} |
| 1081 | + |
| 1082 | +// TestRootedNoopTimes checks the utimes request used by Lima's mountInotify. |
| 1083 | +func TestRootedNoopTimes(t *testing.T) { |
| 1084 | + c, root := setupRooted(t, false) |
| 1085 | + config := filepath.Join(root, ".git", "config") |
| 1086 | + mtime := time.Unix(1_000_000_000, 0) |
| 1087 | + if err := os.Chtimes(config, mtime, mtime); err != nil { |
| 1088 | + t.Fatal(err) |
| 1089 | + } |
| 1090 | + before := ctime(t, config) |
| 1091 | + time.Sleep(10 * time.Millisecond) |
| 1092 | + if err := c.Chtimes(config, mtime, mtime); err != nil { |
| 1093 | + t.Fatalf("utimes to the current mtime: %v", err) |
| 1094 | + } |
| 1095 | + after, err := os.Lstat(config) |
| 1096 | + if err != nil { |
| 1097 | + t.Fatal(err) |
| 1098 | + } |
| 1099 | + if afterCtime := ctime(t, config); before != afterCtime || !after.ModTime().Equal(mtime) { |
| 1100 | + t.Fatalf("file was modified: ctime %v -> %v, mtime %v", before, afterCtime, after.ModTime()) |
| 1101 | + } |
| 1102 | + for _, times := range [][2]time.Time{ |
| 1103 | + {mtime, mtime.Add(time.Second)}, |
| 1104 | + {mtime.Add(time.Second), mtime}, |
| 1105 | + {mtime.Add(time.Second), mtime.Add(time.Second)}, |
| 1106 | + } { |
| 1107 | + if err := c.Chtimes(config, times[0], times[1]); err == nil { |
| 1108 | + t.Errorf("utimes to %v: expected an error", times) |
| 1109 | + } |
| 1110 | + } |
| 1111 | + if err := c.Chtimes(filepath.Join(root, ".git", "missing"), mtime, mtime); err == nil { |
| 1112 | + t.Error("utimes on a missing file: expected an error") |
| 1113 | + } |
| 1114 | + assertUnchanged(t, root) |
| 1115 | +} |
| 1116 | + |
| 1117 | +func TestRootedReadonly(t *testing.T) { |
| 1118 | + c, root := setupRooted(t, true) |
| 1119 | + if _, err := c.Create(filepath.Join(root, "src", "new.go")); err == nil { |
| 1120 | + t.Error("expected an error") |
| 1121 | + } |
| 1122 | + if err := c.Mkdir(filepath.Join(root, "dir")); err == nil { |
| 1123 | + t.Error("expected an error") |
| 1124 | + } |
| 1125 | + if _, err := c.Stat(filepath.Join(root, "src", "main.go")); err != nil { |
| 1126 | + t.Error(err) |
| 1127 | + } |
| 1128 | +} |
| 1129 | + |
| 1130 | +// TestRootedSymlinkSwapRace swaps a directory for a symlink to .git |
| 1131 | +// while the client keeps writing into it. |
| 1132 | +func TestRootedSymlinkSwapRace(t *testing.T) { |
| 1133 | + c, root := setupRooted(t, false) |
| 1134 | + d := filepath.Join(root, "d") |
| 1135 | + stop := make(chan struct{}) |
| 1136 | + var wg sync.WaitGroup |
| 1137 | + wg.Add(1) |
| 1138 | + go func() { |
| 1139 | + defer wg.Done() |
| 1140 | + for { |
| 1141 | + select { |
| 1142 | + case <-stop: |
| 1143 | + return |
| 1144 | + default: |
| 1145 | + } |
| 1146 | + _ = os.RemoveAll(d) |
| 1147 | + _ = os.Mkdir(d, 0o755) |
| 1148 | + _ = os.RemoveAll(d) |
| 1149 | + _ = os.Symlink(".git", d) |
| 1150 | + } |
| 1151 | + }() |
| 1152 | + var created int |
| 1153 | + deadline := time.Now().Add(2 * time.Second) |
| 1154 | + for time.Now().Before(deadline) { |
| 1155 | + if f, err := c.Create(filepath.Join(d, "pwn")); err == nil { |
| 1156 | + f.Close() |
| 1157 | + created++ |
| 1158 | + } |
| 1159 | + _ = c.Mkdir(filepath.Join(d, "pwndir")) |
| 1160 | + _ = c.Symlink("x", filepath.Join(d, "pwnlink")) |
| 1161 | + _ = c.Chmod(filepath.Join(d, "config"), 0o777) |
| 1162 | + _ = c.Truncate(filepath.Join(d, "config"), 0) |
| 1163 | + _ = c.Remove(filepath.Join(d, "config")) |
| 1164 | + } |
| 1165 | + close(stop) |
| 1166 | + wg.Wait() |
| 1167 | + if created == 0 { |
| 1168 | + t.Fatal("no write reached d while it was a directory, the race was not exercised") |
| 1169 | + } |
| 1170 | + assertUnchanged(t, root) |
| 1171 | +} |
| 1172 | + |
| 1173 | +func TestSameName(t *testing.T) { |
| 1174 | + for _, s := range []string{".git", ".GIT", ".Git", ".g" + zwnj + "it", bom + ".git", ".git" + zwj} { |
| 1175 | + if !sameName(s, ".git") { |
| 1176 | + t.Errorf("%q should match .git", s) |
| 1177 | + } |
| 1178 | + } |
| 1179 | + for _, s := range []string{".gitignore", "git", ".git.", "x.git", ".gi"} { |
| 1180 | + if sameName(s, ".git") { |
| 1181 | + t.Errorf("%q should not match .git", s) |
| 1182 | + } |
| 1183 | + } |
| 1184 | +} |
| 1185 | |
| 1186 | new file mode 100644 |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | @@ -0,0 +1,264 @@ |
| 1191 | +//go:build linux || darwin |
| 1192 | + |
| 1193 | +package reversesshfs |
| 1194 | + |
| 1195 | +import ( |
| 1196 | + "os" |
| 1197 | + "path" |
| 1198 | + "path/filepath" |
| 1199 | + "strings" |
| 1200 | + |
| 1201 | + "github.com/pkg/sftp" |
| 1202 | + "golang.org/x/sys/unix" |
| 1203 | +) |
| 1204 | + |
| 1205 | +var errDenied error = unix.EACCES |
| 1206 | + |
| 1207 | +type rootedSys struct { |
| 1208 | + rootFD int |
| 1209 | +} |
| 1210 | + |
| 1211 | +func openRootedSys(localPath string) (rootedSys, error) { |
| 1212 | + rootFD, err := unix.Open(localPath, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 1213 | + if err != nil { |
| 1214 | + return rootedSys{}, &os.PathError{Op: "open", Path: localPath, Err: err} |
| 1215 | + } |
| 1216 | + return rootedSys{rootFD: rootFD}, nil |
| 1217 | +} |
| 1218 | + |
| 1219 | +func (s rootedSys) close() error { |
| 1220 | + return unix.Close(s.rootFD) |
| 1221 | +} |
| 1222 | + |
| 1223 | +// slashPath returns the request path of the host path p. |
| 1224 | +func slashPath(p string) string { |
| 1225 | + return path.Clean(filepath.ToSlash(p)) |
| 1226 | +} |
| 1227 | + |
| 1228 | +func startDirectory(rootPath string) string { |
| 1229 | + return rootPath |
| 1230 | +} |
| 1231 | + |
| 1232 | +func realPath(rootPath, p string) string { |
| 1233 | + if !path.IsAbs(p) { |
| 1234 | + p = path.Join(rootPath, p) |
| 1235 | + } |
| 1236 | + return path.Clean(p) |
| 1237 | +} |
| 1238 | + |
| 1239 | +func writableName(string) bool { |
| 1240 | + return true |
| 1241 | +} |
| 1242 | + |
| 1243 | +// openParent returns a directory fd for the parent of rel, and the base name. |
| 1244 | +// The caller must close the fd. |
| 1245 | +func (h *rootedHandlers) openParent(rel string) (int, string, error) { |
| 1246 | + fd, err := unix.Dup(h.rootFD) |
| 1247 | + if err != nil { |
| 1248 | + return -1, "", err |
| 1249 | + } |
| 1250 | + if rel == "." { |
| 1251 | + return fd, ".", nil |
| 1252 | + } |
| 1253 | + dir, base := path.Split(rel) |
| 1254 | + if dir != "" { |
| 1255 | + for _, c := range strings.Split(strings.TrimSuffix(dir, "/"), "/") { |
| 1256 | + if c == "" || c == "." || c == ".." { |
| 1257 | + unix.Close(fd) |
| 1258 | + return -1, "", unix.EACCES |
| 1259 | + } |
| 1260 | + next, err := unix.Openat(fd, c, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0) |
| 1261 | + unix.Close(fd) |
| 1262 | + if err != nil { |
| 1263 | + return -1, "", err |
| 1264 | + } |
| 1265 | + fd = next |
| 1266 | + } |
| 1267 | + } |
| 1268 | + return fd, base, nil |
| 1269 | +} |
| 1270 | + |
| 1271 | +func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) { |
| 1272 | + rel, err := h.writableRel(r.Filepath) |
| 1273 | + if err != nil { |
| 1274 | + return nil, err |
| 1275 | + } |
| 1276 | + pf := r.Pflags() |
| 1277 | + flags := unix.O_NOFOLLOW | unix.O_CLOEXEC |
| 1278 | + switch { |
| 1279 | + case pf.Read && (pf.Write || pf.Append): |
| 1280 | + flags |= unix.O_RDWR |
| 1281 | + case pf.Write || pf.Append: |
| 1282 | + flags |= unix.O_WRONLY |
| 1283 | + default: |
| 1284 | + flags |= unix.O_RDONLY |
| 1285 | + } |
| 1286 | + // O_APPEND is not set, as it conflicts with WriteAt; the client sends offsets. |
| 1287 | + if pf.Creat { |
| 1288 | + flags |= unix.O_CREAT |
| 1289 | + } |
| 1290 | + if pf.Trunc { |
| 1291 | + flags |= unix.O_TRUNC |
| 1292 | + } |
| 1293 | + if pf.Excl { |
| 1294 | + flags |= unix.O_EXCL |
| 1295 | + } |
| 1296 | + var mode uint32 = 0o644 |
| 1297 | + if r.AttrFlags().Permissions { |
| 1298 | + mode = r.Attributes().Mode & 0o7777 |
| 1299 | + } |
| 1300 | + dirfd, base, err := h.openParent(rel) |
| 1301 | + if err != nil { |
| 1302 | + return nil, err |
| 1303 | + } |
| 1304 | + defer unix.Close(dirfd) |
| 1305 | + fd, err := unix.Openat(dirfd, base, flags, mode) |
| 1306 | + if err != nil { |
| 1307 | + return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err} |
| 1308 | + } |
| 1309 | + return os.NewFile(uintptr(fd), r.Filepath), nil |
| 1310 | +} |
| 1311 | + |
| 1312 | +// inParent calls f with the parent directory fd and the base name of the writable path p. |
| 1313 | +func (h *rootedHandlers) inParent(op, p string, f func(dirfd int, base string) error) error { |
| 1314 | + rel, err := h.writableRel(p) |
| 1315 | + if err != nil { |
| 1316 | + return err |
| 1317 | + } |
| 1318 | + dirfd, base, err := h.openParent(rel) |
| 1319 | + if err != nil { |
| 1320 | + return err |
| 1321 | + } |
| 1322 | + defer unix.Close(dirfd) |
| 1323 | + if err := f(dirfd, base); err != nil { |
| 1324 | + return &os.PathError{Op: op, Path: p, Err: err} |
| 1325 | + } |
| 1326 | + return nil |
| 1327 | +} |
| 1328 | + |
| 1329 | +func (h *rootedHandlers) remove(r *sftp.Request) error { |
| 1330 | + var flags int |
| 1331 | + if r.Method == "Rmdir" { |
| 1332 | + flags = unix.AT_REMOVEDIR |
| 1333 | + } |
| 1334 | + return h.inParent(strings.ToLower(r.Method), r.Filepath, func(dirfd int, base string) error { |
| 1335 | + return unix.Unlinkat(dirfd, base, flags) |
| 1336 | + }) |
| 1337 | +} |
| 1338 | + |
| 1339 | +func (h *rootedHandlers) mkdir(r *sftp.Request) error { |
| 1340 | + var mode uint32 = 0o755 |
| 1341 | + if r.AttrFlags().Permissions { |
| 1342 | + mode = r.Attributes().Mode & 0o7777 |
| 1343 | + } |
| 1344 | + return h.inParent("mkdir", r.Filepath, func(dirfd int, base string) error { |
| 1345 | + return unix.Mkdirat(dirfd, base, mode) |
| 1346 | + }) |
| 1347 | +} |
| 1348 | + |
| 1349 | +// symlink has the link target in Filepath and the link path in Target. |
| 1350 | +func (h *rootedHandlers) symlink(r *sftp.Request) error { |
| 1351 | + return h.inParent("symlink", r.Target, func(dirfd int, base string) error { |
| 1352 | + return unix.Symlinkat(r.Filepath, dirfd, base) |
| 1353 | + }) |
| 1354 | +} |
| 1355 | + |
| 1356 | +func (h *rootedHandlers) link(r *sftp.Request) error { |
| 1357 | + return h.twoPaths(r.Filepath, r.Target, func(oldfd int, oldBase string, newfd int, newBase string) error { |
| 1358 | + return unix.Linkat(oldfd, oldBase, newfd, newBase, 0) |
| 1359 | + }) |
| 1360 | +} |
| 1361 | + |
| 1362 | +func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error { |
| 1363 | + return h.twoPaths(r.Filepath, r.Target, func(oldfd int, oldBase string, newfd int, newBase string) error { |
| 1364 | + if noReplace { |
| 1365 | + var st unix.Stat_t |
| 1366 | + if err := unix.Fstatat(newfd, newBase, &st, unix.AT_SYMLINK_NOFOLLOW); err == nil { |
| 1367 | + return os.ErrExist |
| 1368 | + } |
| 1369 | + } |
| 1370 | + return unix.Renameat(oldfd, oldBase, newfd, newBase) |
| 1371 | + }) |
| 1372 | +} |
| 1373 | + |
| 1374 | +func (h *rootedHandlers) twoPaths(oldPath, newPath string, f func(oldfd int, oldBase string, newfd int, newBase string) error) error { |
| 1375 | + oldRel, err := h.writableRel(oldPath) |
| 1376 | + if err != nil { |
| 1377 | + return err |
| 1378 | + } |
| 1379 | + newRel, err := h.writableRel(newPath) |
| 1380 | + if err != nil { |
| 1381 | + return err |
| 1382 | + } |
| 1383 | + oldfd, oldBase, err := h.openParent(oldRel) |
| 1384 | + if err != nil { |
| 1385 | + return err |
| 1386 | + } |
| 1387 | + defer unix.Close(oldfd) |
| 1388 | + newfd, newBase, err := h.openParent(newRel) |
| 1389 | + if err != nil { |
| 1390 | + return err |
| 1391 | + } |
| 1392 | + defer unix.Close(newfd) |
| 1393 | + if err := f(oldfd, oldBase, newfd, newBase); err != nil { |
| 1394 | + return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: err} |
| 1395 | + } |
| 1396 | + return nil |
| 1397 | +} |
| 1398 | + |
| 1399 | +func (h *rootedHandlers) setstat(r *sftp.Request) error { |
| 1400 | + rel, err := h.writableRel(r.Filepath) |
| 1401 | + if err != nil { |
| 1402 | + return err |
| 1403 | + } |
| 1404 | + dirfd, base, err := h.openParent(rel) |
| 1405 | + if err != nil { |
| 1406 | + return err |
| 1407 | + } |
| 1408 | + defer unix.Close(dirfd) |
| 1409 | + flags := r.AttrFlags() |
| 1410 | + attrs := r.Attributes() |
| 1411 | + if flags.Size { |
| 1412 | + fd, err := unix.Openat(dirfd, base, unix.O_WRONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0) |
| 1413 | + if err != nil { |
| 1414 | + return &os.PathError{Op: "truncate", Path: r.Filepath, Err: err} |
| 1415 | + } |
| 1416 | + err = unix.Ftruncate(fd, int64(attrs.Size)) |
| 1417 | + unix.Close(fd) |
| 1418 | + if err != nil { |
| 1419 | + return &os.PathError{Op: "truncate", Path: r.Filepath, Err: err} |
| 1420 | + } |
| 1421 | + } |
| 1422 | + if flags.Permissions { |
| 1423 | + if err := fchmodatNoFollow(dirfd, base, attrs.Mode&0o7777); err != nil { |
| 1424 | + return &os.PathError{Op: "chmod", Path: r.Filepath, Err: err} |
| 1425 | + } |
| 1426 | + } |
| 1427 | + if flags.UidGid { |
| 1428 | + if err := unix.Fchownat(dirfd, base, int(attrs.UID), int(attrs.GID), unix.AT_SYMLINK_NOFOLLOW); err != nil { |
| 1429 | + return &os.PathError{Op: "chown", Path: r.Filepath, Err: err} |
| 1430 | + } |
| 1431 | + } |
| 1432 | + if flags.Acmodtime { |
| 1433 | + ts := []unix.Timespec{ |
| 1434 | + unix.NsecToTimespec(int64(attrs.Atime) * 1e9), |
| 1435 | + unix.NsecToTimespec(int64(attrs.Mtime) * 1e9), |
| 1436 | + } |
| 1437 | + if err := unix.UtimesNanoAt(dirfd, base, ts, unix.AT_SYMLINK_NOFOLLOW); err != nil { |
| 1438 | + return &os.PathError{Op: "chtimes", Path: r.Filepath, Err: err} |
| 1439 | + } |
| 1440 | + } |
| 1441 | + return nil |
| 1442 | +} |
| 1443 | + |
| 1444 | +// StatVFS implements sftp.StatVFSFileCmder. |
| 1445 | +func (h *rootedHandlers) StatVFS(r *sftp.Request) (*sftp.StatVFS, error) { |
| 1446 | + if _, err := h.rel(r.Filepath); err != nil { |
| 1447 | + return nil, err |
| 1448 | + } |
| 1449 | + var st unix.Statfs_t |
| 1450 | + if err := unix.Fstatfs(h.rootFD, &st); err != nil { |
| 1451 | + return nil, err |
| 1452 | + } |
| 1453 | + return statVFS(&st), nil |
| 1454 | +} |
| 1455 | |
| 1456 | new file mode 100644 |
| 1457 | |
| 1458 | |
| 1459 | |
| 1460 | @@ -0,0 +1,513 @@ |
| 1461 | +package reversesshfs |
| 1462 | + |
| 1463 | +import ( |
| 1464 | + "errors" |
| 1465 | + "os" |
| 1466 | + "path" |
| 1467 | + "path/filepath" |
| 1468 | + "strings" |
| 1469 | + "syscall" |
| 1470 | + "unsafe" |
| 1471 | + |
| 1472 | + "github.com/pkg/sftp" |
| 1473 | + "golang.org/x/sys/windows" |
| 1474 | +) |
| 1475 | + |
| 1476 | +var errDenied error = windows.ERROR_ACCESS_DENIED |
| 1477 | + |
| 1478 | +// The first four are not defined in x/sys/windows. |
| 1479 | +const ( |
| 1480 | + fileNameNormalized = 0x0 // FILE_NAME_NORMALIZED |
| 1481 | + volumeNameNone = 0x4 // VOLUME_NAME_NONE |
| 1482 | + fileLinkInformation = 11 |
| 1483 | + fileRenameInformationEx = 65 |
| 1484 | + fileAttributeReadonly = windows.FILE_ATTRIBUTE_READONLY |
| 1485 | + fileAttributeNormal = windows.FILE_ATTRIBUTE_NORMAL |
| 1486 | + fileDirectoryAccess = windows.FILE_LIST_DIRECTORY | windows.FILE_TRAVERSE | windows.FILE_READ_ATTRIBUTES |
| 1487 | + fileShareAll = windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE | windows.FILE_SHARE_DELETE |
| 1488 | + fileDispositionFlagsPOSIX = windows.FILE_DISPOSITION_DELETE | windows.FILE_DISPOSITION_POSIX_SEMANTICS | windows.FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE |
| 1489 | +) |
| 1490 | + |
| 1491 | +// rootedSys walks paths with NtCreateFile relative to directory handles. |
| 1492 | +// OBJ_DONT_REPARSE makes it fail on any reparse point (symlink, junction), |
| 1493 | +// like O_NOFOLLOW on each component. |
| 1494 | +// |
| 1495 | +// A name that passes the lexical check may still refer to a read-only entry, |
| 1496 | +// through its 8.3 short name (e.g. GIT~1 for .git, see CVE-2019-1353). |
| 1497 | +// So every handle that a write goes through is checked by its normalized |
| 1498 | +// name, in which the file system has replaced short names by long ones. |
| 1499 | +type rootedSys struct { |
| 1500 | + localPath string |
| 1501 | + rootHandle windows.Handle |
| 1502 | + rootName string // normalized path of the root, without the volume and a trailing separator |
| 1503 | +} |
| 1504 | + |
| 1505 | +func openRootedSys(localPath string) (rootedSys, error) { |
| 1506 | + p, err := windows.UTF16PtrFromString(localPath) |
| 1507 | + if err != nil { |
| 1508 | + return rootedSys{}, err |
| 1509 | + } |
| 1510 | + h, err := windows.CreateFile(p, fileDirectoryAccess|windows.SYNCHRONIZE, fileShareAll, nil, |
| 1511 | + windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) |
| 1512 | + if err != nil { |
| 1513 | + return rootedSys{}, &os.PathError{Op: "open", Path: localPath, Err: err} |
| 1514 | + } |
| 1515 | + name, err := normalizedName(h) |
| 1516 | + if err != nil { |
| 1517 | + windows.CloseHandle(h) |
| 1518 | + return rootedSys{}, &os.PathError{Op: "open", Path: localPath, Err: err} |
| 1519 | + } |
| 1520 | + return rootedSys{localPath: localPath, rootHandle: h, rootName: strings.TrimSuffix(name, `\`)}, nil |
| 1521 | +} |
| 1522 | + |
| 1523 | +func (s rootedSys) close() error { |
| 1524 | + return windows.CloseHandle(s.rootHandle) |
| 1525 | +} |
| 1526 | + |
| 1527 | +// slashPath returns the request path of the host path p. |
| 1528 | +// sshfs sends the host path it was given, e.g. C:/Users/foo/bar, |
| 1529 | +// which the sftp request server turns into /C:/Users/foo/bar. |
| 1530 | +func slashPath(p string) string { |
| 1531 | + return path.Clean("/" + filepath.ToSlash(filepath.Clean(p))) |
| 1532 | +} |
| 1533 | + |
| 1534 | +func startDirectory(string) string { |
| 1535 | + return "/" |
| 1536 | +} |
| 1537 | + |
| 1538 | +func realPath(rootPath, p string) string { |
| 1539 | + if filepath.VolumeName(p) != "" || strings.HasPrefix(p, "/") || strings.HasPrefix(p, `\`) { |
| 1540 | + return slashPath(p) |
| 1541 | + } |
| 1542 | + return path.Join(rootPath, filepath.ToSlash(p)) |
| 1543 | +} |
| 1544 | + |
| 1545 | +// writableName rejects backslashes, which are separators on Windows, |
| 1546 | +// and colons, which name NTFS streams (e.g. .git::$INDEX_ALLOCATION, see CVE-2019-1352). |
| 1547 | +func writableName(rel string) bool { |
| 1548 | + return !strings.ContainsAny(rel, `\:`) |
| 1549 | +} |
| 1550 | + |
| 1551 | +func normalizedName(h windows.Handle) (string, error) { |
| 1552 | + buf := make([]uint16, windows.MAX_PATH) |
| 1553 | + for { |
| 1554 | + n, err := windows.GetFinalPathNameByHandle(h, &buf[0], uint32(len(buf)), fileNameNormalized|volumeNameNone) |
| 1555 | + if err != nil { |
| 1556 | + return "", err |
| 1557 | + } |
| 1558 | + if n < uint32(len(buf)) { |
| 1559 | + return windows.UTF16ToString(buf[:n]), nil |
| 1560 | + } |
| 1561 | + buf = make([]uint16, n) |
| 1562 | + } |
| 1563 | +} |
| 1564 | + |
| 1565 | +// checkHandle denies fh when its normalized path has a read-only component, or is not under the root. |
| 1566 | +func (h *rootedHandlers) checkHandle(fh windows.Handle) error { |
| 1567 | + name, err := normalizedName(fh) |
| 1568 | + if err != nil { |
| 1569 | + return err |
| 1570 | + } |
| 1571 | + if name == h.rootName { |
| 1572 | + return nil |
| 1573 | + } |
| 1574 | + rel, ok := strings.CutPrefix(name, h.rootName+`\`) |
| 1575 | + if !ok { |
| 1576 | + return errDenied |
| 1577 | + } |
| 1578 | + for _, c := range strings.Split(rel, `\`) { |
| 1579 | + c, _, _ = strings.Cut(c, ":") |
| 1580 | + if h.isReadonlyName(c) { |
| 1581 | + return errDenied |
| 1582 | + } |
| 1583 | + } |
| 1584 | + return nil |
| 1585 | +} |
| 1586 | + |
| 1587 | +func ntCreate(dir windows.Handle, name string, access, attrs, disposition, options, objFlags uint32) (windows.Handle, error) { |
| 1588 | + objectName, err := windows.NewNTUnicodeString(name) |
| 1589 | + if err != nil { |
| 1590 | + return windows.InvalidHandle, err |
| 1591 | + } |
| 1592 | + oa := &windows.OBJECT_ATTRIBUTES{ |
| 1593 | + RootDirectory: dir, |
| 1594 | + ObjectName: objectName, |
| 1595 | + Attributes: windows.OBJ_CASE_INSENSITIVE | objFlags, |
| 1596 | + } |
| 1597 | + oa.Length = uint32(unsafe.Sizeof(*oa)) |
| 1598 | + var fh windows.Handle |
| 1599 | + err = windows.NtCreateFile(&fh, access|windows.SYNCHRONIZE, oa, &windows.IO_STATUS_BLOCK{}, nil, attrs, fileShareAll, |
| 1600 | + disposition, options|windows.FILE_SYNCHRONOUS_IO_NONALERT|windows.FILE_OPEN_FOR_BACKUP_INTENT, 0, 0) |
| 1601 | + if err != nil { |
| 1602 | + return windows.InvalidHandle, ntError(err) |
| 1603 | + } |
| 1604 | + return fh, nil |
| 1605 | +} |
| 1606 | + |
| 1607 | +func ntError(err error) error { |
| 1608 | + s, ok := err.(windows.NTStatus) |
| 1609 | + if !ok { |
| 1610 | + return err |
| 1611 | + } |
| 1612 | + if s == windows.STATUS_REPARSE_POINT_ENCOUNTERED { |
| 1613 | + return errDenied |
| 1614 | + } |
| 1615 | + return s.Errno() |
| 1616 | +} |
| 1617 | + |
| 1618 | +// openParent returns a handle of the parent directory of rel, and the base name. |
| 1619 | +// The caller must close the handle. |
| 1620 | +func (h *rootedHandlers) openParent(rel string) (windows.Handle, string, error) { |
| 1621 | + if rel == "." { |
| 1622 | + return windows.InvalidHandle, "", errDenied |
| 1623 | + } |
| 1624 | + dir, base := path.Split(rel) |
| 1625 | + dir = strings.TrimSuffix(dir, "/") |
| 1626 | + if dir == "" { |
| 1627 | + var dup windows.Handle |
| 1628 | + p := windows.CurrentProcess() |
| 1629 | + if err := windows.DuplicateHandle(p, h.rootHandle, p, &dup, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil { |
| 1630 | + return windows.InvalidHandle, "", err |
| 1631 | + } |
| 1632 | + return dup, base, nil |
| 1633 | + } |
| 1634 | + for _, c := range strings.Split(dir, "/") { |
| 1635 | + if c == "" || c == "." || c == ".." { |
| 1636 | + return windows.InvalidHandle, "", errDenied |
| 1637 | + } |
| 1638 | + } |
| 1639 | + fh, err := ntCreate(h.rootHandle, filepath.FromSlash(dir), fileDirectoryAccess, 0, windows.FILE_OPEN, |
| 1640 | + windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE) |
| 1641 | + if err != nil { |
| 1642 | + return windows.InvalidHandle, "", err |
| 1643 | + } |
| 1644 | + if err := h.checkHandle(fh); err != nil { |
| 1645 | + windows.CloseHandle(fh) |
| 1646 | + return windows.InvalidHandle, "", err |
| 1647 | + } |
| 1648 | + return fh, base, nil |
| 1649 | +} |
| 1650 | + |
| 1651 | +// openChecked opens the writable path p, which must not be a reparse point unless options has FILE_OPEN_REPARSE_POINT. |
| 1652 | +// The caller must close both handles. |
| 1653 | +func (h *rootedHandlers) openChecked(p string, access, options uint32) (parent, fh windows.Handle, err error) { |
| 1654 | + rel, err := h.writableRel(p) |
| 1655 | + if err != nil { |
| 1656 | + return windows.InvalidHandle, windows.InvalidHandle, err |
| 1657 | + } |
| 1658 | + parent, base, err := h.openParent(rel) |
| 1659 | + if err != nil { |
| 1660 | + return windows.InvalidHandle, windows.InvalidHandle, err |
| 1661 | + } |
| 1662 | + var objFlags uint32 |
| 1663 | + if options&windows.FILE_OPEN_REPARSE_POINT == 0 { |
| 1664 | + objFlags = windows.OBJ_DONT_REPARSE |
| 1665 | + } |
| 1666 | + fh, err = ntCreate(parent, base, access, 0, windows.FILE_OPEN, options, objFlags) |
| 1667 | + if err == nil { |
| 1668 | + err = h.checkHandle(fh) |
| 1669 | + if err != nil { |
| 1670 | + windows.CloseHandle(fh) |
| 1671 | + } |
| 1672 | + } |
| 1673 | + if err != nil { |
| 1674 | + windows.CloseHandle(parent) |
| 1675 | + return windows.InvalidHandle, windows.InvalidHandle, err |
| 1676 | + } |
| 1677 | + return parent, fh, nil |
| 1678 | +} |
| 1679 | + |
| 1680 | +func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) { |
| 1681 | + rel, err := h.writableRel(r.Filepath) |
| 1682 | + if err != nil { |
| 1683 | + return nil, err |
| 1684 | + } |
| 1685 | + parent, base, err := h.openParent(rel) |
| 1686 | + if err != nil { |
| 1687 | + return nil, err |
| 1688 | + } |
| 1689 | + defer windows.CloseHandle(parent) |
| 1690 | + pf := r.Pflags() |
| 1691 | + var access, options uint32 |
| 1692 | + switch { |
| 1693 | + case pf.Read && (pf.Write || pf.Append): |
| 1694 | + access = windows.FILE_GENERIC_READ | windows.FILE_GENERIC_WRITE |
| 1695 | + options = windows.FILE_NON_DIRECTORY_FILE |
| 1696 | + case pf.Write || pf.Append: |
| 1697 | + access = windows.FILE_GENERIC_WRITE |
| 1698 | + options = windows.FILE_NON_DIRECTORY_FILE |
| 1699 | + default: |
| 1700 | + access = windows.FILE_GENERIC_READ |
| 1701 | + } |
| 1702 | + // FILE_APPEND_DATA semantics are not requested, as the client sends offsets. |
| 1703 | + disposition := uint32(windows.FILE_OPEN) |
| 1704 | + switch { |
| 1705 | + case pf.Creat && pf.Excl: |
| 1706 | + disposition = windows.FILE_CREATE |
| 1707 | + case pf.Creat: |
| 1708 | + disposition = windows.FILE_OPEN_IF |
| 1709 | + } |
| 1710 | + var attrs uint32 = fileAttributeNormal |
| 1711 | + if r.AttrFlags().Permissions && r.Attributes().Mode&0o200 == 0 { |
| 1712 | + attrs = fileAttributeReadonly |
| 1713 | + } |
| 1714 | + fh, err := ntCreate(parent, base, access, attrs, disposition, options, windows.OBJ_DONT_REPARSE) |
| 1715 | + if err != nil { |
| 1716 | + return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err} |
| 1717 | + } |
| 1718 | + // Checked before truncating: base may be the short name of an existing read-only name. |
| 1719 | + if err := h.checkHandle(fh); err != nil { |
| 1720 | + windows.CloseHandle(fh) |
| 1721 | + return nil, err |
| 1722 | + } |
| 1723 | + if pf.Trunc { |
| 1724 | + if err := windows.Ftruncate(fh, 0); err != nil { |
| 1725 | + windows.CloseHandle(fh) |
| 1726 | + return nil, &os.PathError{Op: "truncate", Path: r.Filepath, Err: err} |
| 1727 | + } |
| 1728 | + } |
| 1729 | + return os.NewFile(uintptr(fh), r.Filepath), nil |
| 1730 | +} |
| 1731 | + |
| 1732 | +func (h *rootedHandlers) remove(r *sftp.Request) error { |
| 1733 | + options := uint32(windows.FILE_OPEN_REPARSE_POINT) |
| 1734 | + if r.Method == "Rmdir" { |
| 1735 | + options |= windows.FILE_DIRECTORY_FILE |
| 1736 | + } |
| 1737 | + parent, fh, err := h.openChecked(r.Filepath, windows.DELETE|windows.FILE_READ_ATTRIBUTES, options) |
| 1738 | + if err != nil { |
| 1739 | + return err |
| 1740 | + } |
| 1741 | + defer windows.CloseHandle(parent) |
| 1742 | + defer windows.CloseHandle(fh) |
| 1743 | + if r.Method == "Remove" { |
| 1744 | + // As unlink, which removes a symlink to a directory but not a directory. |
| 1745 | + var fi windows.ByHandleFileInformation |
| 1746 | + if err := windows.GetFileInformationByHandle(fh, &fi); err != nil { |
| 1747 | + return &os.PathError{Op: "remove", Path: r.Filepath, Err: err} |
| 1748 | + } |
| 1749 | + if fi.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0 && fi.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT == 0 { |
| 1750 | + return &os.PathError{Op: "remove", Path: r.Filepath, Err: syscall.EISDIR} |
| 1751 | + } |
| 1752 | + } |
| 1753 | + if err := deleteHandle(fh); err != nil { |
| 1754 | + return &os.PathError{Op: strings.ToLower(r.Method), Path: r.Filepath, Err: err} |
| 1755 | + } |
| 1756 | + return nil |
| 1757 | +} |
| 1758 | + |
| 1759 | +// deleteHandle is Deleteat of Go's internal/syscall/windows. |
| 1760 | +func deleteHandle(fh windows.Handle) error { |
| 1761 | + flags := uint32(fileDispositionFlagsPOSIX) |
| 1762 | + err := windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&flags)), |
| 1763 | + uint32(unsafe.Sizeof(flags)), windows.FileDispositionInformationEx) |
| 1764 | + switch err { |
| 1765 | + case nil: |
| 1766 | + return nil |
| 1767 | + case windows.STATUS_INVALID_INFO_CLASS, windows.STATUS_INVALID_PARAMETER, windows.STATUS_NOT_SUPPORTED: |
| 1768 | + // Older Windows, or a file system without POSIX semantics, such as FAT32. |
| 1769 | + deleteFile := uint8(1) |
| 1770 | + err = windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, &deleteFile, |
| 1771 | + uint32(unsafe.Sizeof(deleteFile)), windows.FileDispositionInformation) |
| 1772 | + } |
| 1773 | + return ntError(err) |
| 1774 | +} |
| 1775 | + |
| 1776 | +func (h *rootedHandlers) mkdir(r *sftp.Request) error { |
| 1777 | + rel, err := h.writableRel(r.Filepath) |
| 1778 | + if err != nil { |
| 1779 | + return err |
| 1780 | + } |
| 1781 | + parent, base, err := h.openParent(rel) |
| 1782 | + if err != nil { |
| 1783 | + return err |
| 1784 | + } |
| 1785 | + defer windows.CloseHandle(parent) |
| 1786 | + // A base that is the short name of an existing entry fails with STATUS_OBJECT_NAME_COLLISION. |
| 1787 | + fh, err := ntCreate(parent, base, fileDirectoryAccess, fileAttributeNormal, windows.FILE_CREATE, |
| 1788 | + windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE) |
| 1789 | + if err != nil { |
| 1790 | + return &os.PathError{Op: "mkdir", Path: r.Filepath, Err: err} |
| 1791 | + } |
| 1792 | + return windows.CloseHandle(fh) |
| 1793 | +} |
| 1794 | + |
| 1795 | +// symlink is not supported: creating a symlink needs a privilege, or the developer mode, |
| 1796 | +// and CreateSymbolicLink takes a path, so it would follow symlinks in the parent directories. |
| 1797 | +func (h *rootedHandlers) symlink(*sftp.Request) error { |
| 1798 | + return sftp.ErrSSHFxOpUnsupported |
| 1799 | +} |
| 1800 | + |
| 1801 | +func (h *rootedHandlers) link(r *sftp.Request) error { |
| 1802 | + return h.twoPaths(r.Filepath, r.Target, windows.FILE_WRITE_ATTRIBUTES|windows.FILE_READ_ATTRIBUTES, |
| 1803 | + windows.FILE_NON_DIRECTORY_FILE, true, func(src, newParent windows.Handle, newBase string) error { |
| 1804 | + return setName(src, fileLinkInformation, 0, newParent, newBase) |
| 1805 | + }) |
| 1806 | +} |
| 1807 | + |
| 1808 | +func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error { |
| 1809 | + return h.twoPaths(r.Filepath, r.Target, windows.DELETE|windows.FILE_READ_ATTRIBUTES, 0, noReplace, |
| 1810 | + func(src, newParent windows.Handle, newBase string) error { |
| 1811 | + var flags uint32 = windows.FILE_RENAME_POSIX_SEMANTICS | windows.FILE_RENAME_IGNORE_READONLY_ATTRIBUTE |
| 1812 | + if !noReplace { |
| 1813 | + flags |= windows.FILE_RENAME_REPLACE_IF_EXISTS |
| 1814 | + } |
| 1815 | + err := setName(src, fileRenameInformationEx, flags, newParent, newBase) |
| 1816 | + switch err { |
| 1817 | + case windows.STATUS_INVALID_INFO_CLASS, windows.STATUS_INVALID_PARAMETER, windows.STATUS_NOT_SUPPORTED: |
| 1818 | + // Older Windows, or a file system without POSIX semantics. |
| 1819 | + // The first byte of the flags is ReplaceIfExists. |
| 1820 | + err = setName(src, windows.FileRenameInformation, flags&windows.FILE_RENAME_REPLACE_IF_EXISTS, newParent, newBase) |
| 1821 | + } |
| 1822 | + return err |
| 1823 | + }) |
| 1824 | +} |
| 1825 | + |
| 1826 | +// twoPaths opens oldPath without following a symlink, and calls f with the parent directory handle and |
| 1827 | +// the base name of newPath. |
| 1828 | +func (h *rootedHandlers) twoPaths(oldPath, newPath string, access, options uint32, noReplace bool, |
| 1829 | + f func(src, newParent windows.Handle, newBase string) error, |
| 1830 | +) error { |
| 1831 | + newRel, err := h.writableRel(newPath) |
| 1832 | + if err != nil { |
| 1833 | + return err |
| 1834 | + } |
| 1835 | + oldParent, src, err := h.openChecked(oldPath, access, options|windows.FILE_OPEN_REPARSE_POINT) |
| 1836 | + if err != nil { |
| 1837 | + return err |
| 1838 | + } |
| 1839 | + defer windows.CloseHandle(oldParent) |
| 1840 | + defer windows.CloseHandle(src) |
| 1841 | + newParent, newBase, err := h.openParent(newRel) |
| 1842 | + if err != nil { |
| 1843 | + return err |
| 1844 | + } |
| 1845 | + defer windows.CloseHandle(newParent) |
| 1846 | + // newBase may be the short name of an existing read-only name, which would be replaced. |
| 1847 | + dst, err := ntCreate(newParent, newBase, windows.FILE_READ_ATTRIBUTES, 0, windows.FILE_OPEN, windows.FILE_OPEN_REPARSE_POINT, 0) |
| 1848 | + switch { |
| 1849 | + case err == nil: |
| 1850 | + err = h.checkHandle(dst) |
| 1851 | + windows.CloseHandle(dst) |
| 1852 | + if err != nil { |
| 1853 | + return err |
| 1854 | + } |
| 1855 | + if noReplace { |
| 1856 | + return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: os.ErrExist} |
| 1857 | + } |
| 1858 | + case !errors.Is(err, os.ErrNotExist): |
| 1859 | + return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: err} |
| 1860 | + } |
| 1861 | + if err := f(src, newParent, newBase); err != nil { |
| 1862 | + return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: ntError(err)} |
| 1863 | + } |
| 1864 | + return nil |
| 1865 | +} |
| 1866 | + |
| 1867 | +// fileNameInformation is FILE_RENAME_INFORMATION and FILE_LINK_INFORMATION. |
| 1868 | +// Flags is a BOOLEAN ReplaceIfExists for the non-Ex classes. |
| 1869 | +type fileNameInformation struct { |
| 1870 | + Flags uint32 |
| 1871 | + RootDirectory windows.Handle |
| 1872 | + FileNameLength uint32 |
| 1873 | + FileName [1]uint16 |
| 1874 | +} |
| 1875 | + |
| 1876 | +// setName renames src, or creates a hard link of it, to name in the directory dir. |
| 1877 | +func setName(src windows.Handle, class, flags uint32, dir windows.Handle, name string) error { |
| 1878 | + name16, err := windows.UTF16FromString(name) |
| 1879 | + if err != nil { |
| 1880 | + return err |
| 1881 | + } |
| 1882 | + name16 = name16[:len(name16)-1] |
| 1883 | + size := unsafe.Offsetof(fileNameInformation{}.FileName) + uintptr(len(name16))*2 |
| 1884 | + buf := make([]uint64, (size+7)/8) |
| 1885 | + info := (*fileNameInformation)(unsafe.Pointer(&buf[0])) |
| 1886 | + info.Flags = flags |
| 1887 | + info.RootDirectory = dir |
| 1888 | + info.FileNameLength = uint32(len(name16) * 2) |
| 1889 | + copy(unsafe.Slice(&info.FileName[0], len(name16)), name16) |
| 1890 | + return windows.NtSetInformationFile(src, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&buf[0])), uint32(size), class) |
| 1891 | +} |
| 1892 | + |
| 1893 | +// fileBasicInformation is FILE_BASIC_INFORMATION. Zero values are left unchanged. |
| 1894 | +type fileBasicInformation struct { |
| 1895 | + CreationTime, LastAccessTime, LastWriteTime, ChangeTime int64 |
| 1896 | + FileAttributes uint32 |
| 1897 | + _ uint32 // the C struct is 40 bytes on 386 too |
| 1898 | +} |
| 1899 | + |
| 1900 | +func (h *rootedHandlers) setstat(r *sftp.Request) error { |
| 1901 | + flags := r.AttrFlags() |
| 1902 | + attrs := r.Attributes() |
| 1903 | + if flags.UidGid { |
| 1904 | + return &os.PathError{Op: "chown", Path: r.Filepath, Err: syscall.EWINDOWS} |
| 1905 | + } |
| 1906 | + access := uint32(windows.FILE_READ_ATTRIBUTES | windows.FILE_WRITE_ATTRIBUTES) |
| 1907 | + if flags.Size { |
| 1908 | + access |= windows.FILE_WRITE_DATA |
| 1909 | + } |
| 1910 | + parent, fh, err := h.openChecked(r.Filepath, access, 0) |
| 1911 | + if err != nil { |
| 1912 | + return err |
| 1913 | + } |
| 1914 | + defer windows.CloseHandle(parent) |
| 1915 | + defer windows.CloseHandle(fh) |
| 1916 | + if flags.Size { |
| 1917 | + if err := windows.Ftruncate(fh, int64(attrs.Size)); err != nil { |
| 1918 | + return &os.PathError{Op: "truncate", Path: r.Filepath, Err: err} |
| 1919 | + } |
| 1920 | + } |
| 1921 | + if flags.Permissions { |
| 1922 | + // As os.Chmod: only the owner write bit is used, for the read-only attribute. |
| 1923 | + var fi windows.ByHandleFileInformation |
| 1924 | + if err := windows.GetFileInformationByHandle(fh, &fi); err != nil { |
| 1925 | + return &os.PathError{Op: "chmod", Path: r.Filepath, Err: err} |
| 1926 | + } |
| 1927 | + a := fi.FileAttributes &^ fileAttributeReadonly |
| 1928 | + if attrs.Mode&0o200 == 0 { |
| 1929 | + a |= fileAttributeReadonly |
| 1930 | + } |
| 1931 | + if a == 0 { |
| 1932 | + a = fileAttributeNormal |
| 1933 | + } |
| 1934 | + info := fileBasicInformation{FileAttributes: a} |
| 1935 | + err := windows.NtSetInformationFile(fh, &windows.IO_STATUS_BLOCK{}, (*byte)(unsafe.Pointer(&info)), |
| 1936 | + uint32(unsafe.Sizeof(info)), windows.FileBasicInformation) |
| 1937 | + if err != nil { |
| 1938 | + return &os.PathError{Op: "chmod", Path: r.Filepath, Err: ntError(err)} |
| 1939 | + } |
| 1940 | + } |
| 1941 | + if flags.Acmodtime { |
| 1942 | + atime := windows.NsecToFiletime(int64(attrs.Atime) * 1e9) |
| 1943 | + mtime := windows.NsecToFiletime(int64(attrs.Mtime) * 1e9) |
| 1944 | + if err := windows.SetFileTime(fh, nil, &atime, &mtime); err != nil { |
| 1945 | + return &os.PathError{Op: "chtimes", Path: r.Filepath, Err: err} |
| 1946 | + } |
| 1947 | + } |
| 1948 | + return nil |
| 1949 | +} |
| 1950 | + |
| 1951 | +// StatVFS implements sftp.StatVFSFileCmder. |
| 1952 | +func (h *rootedHandlers) StatVFS(r *sftp.Request) (*sftp.StatVFS, error) { |
| 1953 | + if _, err := h.rel(r.Filepath); err != nil { |
| 1954 | + return nil, err |
| 1955 | + } |
| 1956 | + p, err := windows.UTF16PtrFromString(h.localPath) |
| 1957 | + if err != nil { |
| 1958 | + return nil, err |
| 1959 | + } |
| 1960 | + var avail, total, free uint64 |
| 1961 | + if err := windows.GetDiskFreeSpaceEx(p, &avail, &total, &free); err != nil { |
| 1962 | + return nil, &os.PathError{Op: "statvfs", Path: h.localPath, Err: err} |
| 1963 | + } |
| 1964 | + const bsize = 4096 |
| 1965 | + return &sftp.StatVFS{ |
| 1966 | + Bsize: bsize, |
| 1967 | + Frsize: bsize, |
| 1968 | + Blocks: total / bsize, |
| 1969 | + Bfree: free / bsize, |
| 1970 | + Bavail: avail / bsize, |
| 1971 | + Namemax: 255, |
| 1972 | + }, nil |
| 1973 | +} |
| 1974 | |
| 1975 | new file mode 100644 |
| 1976 | |
| 1977 | |
| 1978 | |
| 1979 | @@ -0,0 +1,170 @@ |
| 1980 | +package reversesshfs |
| 1981 | + |
| 1982 | +import ( |
| 1983 | + "os" |
| 1984 | + "os/exec" |
| 1985 | + "path/filepath" |
| 1986 | + "strings" |
| 1987 | + "testing" |
| 1988 | + "unsafe" |
| 1989 | + |
| 1990 | + "github.com/pkg/sftp" |
| 1991 | + "golang.org/x/sys/windows" |
| 1992 | +) |
| 1993 | + |
| 1994 | +func ctime(t *testing.T, p string) int64 { |
| 1995 | + t.Helper() |
| 1996 | + f, err := os.Open(p) |
| 1997 | + if err != nil { |
| 1998 | + t.Fatal(err) |
| 1999 | + } |
| 2000 | + defer f.Close() |
| 2001 | + var info fileBasicInformation |
| 2002 | + if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), windows.FileBasicInfo, |
| 2003 | + (*byte)(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))); err != nil { |
| 2004 | + t.Fatal(err) |
| 2005 | + } |
| 2006 | + return info.ChangeTime |
| 2007 | +} |
| 2008 | + |
| 2009 | +func TestSlashPath(t *testing.T) { |
| 2010 | + for in, want := range map[string]string{ |
| 2011 | + `C:\Users\foo`: "/C:/Users/foo", |
| 2012 | + `C:/Users/foo`: "/C:/Users/foo", |
| 2013 | + `/C:/Users/foo/`: "/C:/Users/foo", |
| 2014 | + `C:\`: "/C:", |
| 2015 | + `\\server\share\foo`: "/server/share/foo", |
| 2016 | + } { |
| 2017 | + if got := slashPath(in); got != want { |
| 2018 | + t.Errorf("slashPath(%q) = %q, want %q", in, got, want) |
| 2019 | + } |
| 2020 | + } |
| 2021 | + for in, want := range map[string]string{ |
| 2022 | + "C:/Users/foo/bar": "/C:/Users/foo/bar", |
| 2023 | + "/C:/Users/foo/bar": "/C:/Users/foo/bar", |
| 2024 | + "bar": "/C:/Users/foo/bar", |
| 2025 | + ".": "/C:/Users/foo", |
| 2026 | + } { |
| 2027 | + if got := realPath("/C:/Users/foo", in); got != want { |
| 2028 | + t.Errorf("realPath(%q) = %q, want %q", in, got, want) |
| 2029 | + } |
| 2030 | + } |
| 2031 | +} |
| 2032 | + |
| 2033 | +func shortBase(t *testing.T, p string) string { |
| 2034 | + t.Helper() |
| 2035 | + p16, err := windows.UTF16PtrFromString(p) |
| 2036 | + if err != nil { |
| 2037 | + t.Fatal(err) |
| 2038 | + } |
| 2039 | + buf := make([]uint16, windows.MAX_PATH) |
| 2040 | + n, err := windows.GetShortPathName(p16, &buf[0], uint32(len(buf))) |
| 2041 | + if err != nil { |
| 2042 | + t.Fatal(err) |
| 2043 | + } |
| 2044 | + return filepath.Base(windows.UTF16ToString(buf[:n])) |
| 2045 | +} |
| 2046 | + |
| 2047 | +// TestRootedDeniesShortNames writes through the 8.3 short name of .git (CVE-2019-1353), |
| 2048 | +// which passes the lexical check. |
| 2049 | +func TestRootedDeniesShortNames(t *testing.T) { |
| 2050 | + type env struct { |
| 2051 | + c *sftp.Client |
| 2052 | + root, git string // git is the short name of .git |
| 2053 | + gitfile string // the short name of src/.git |
| 2054 | + } |
| 2055 | + p := func(e env, s string) string { return filepath.Join(e.root, s) } |
| 2056 | + open := func(e env, s string, flags int) error { |
| 2057 | + f, err := e.c.OpenFile(p(e, s), flags) |
| 2058 | + if err == nil { |
| 2059 | + f.Close() |
| 2060 | + } |
| 2061 | + return err |
| 2062 | + } |
| 2063 | + attempts := []struct { |
| 2064 | + name string |
| 2065 | + f func(e env) error |
| 2066 | + }{ |
| 2067 | + {"create hook", func(e env) error { return open(e, e.git+"/hooks/pre-commit", os.O_RDWR|os.O_CREATE|os.O_TRUNC) }}, |
| 2068 | + {"open config for write", func(e env) error { return open(e, e.git+"/config", os.O_WRONLY) }}, |
| 2069 | + {"truncate on open", func(e env) error { return open(e, e.git+"/config", os.O_WRONLY|os.O_TRUNC) }}, |
| 2070 | + {"remove config", func(e env) error { return e.c.Remove(p(e, e.git+"/config")) }}, |
| 2071 | + {"rmdir hooks", func(e env) error { return e.c.RemoveDirectory(p(e, e.git+"/hooks")) }}, |
| 2072 | + {"rename .git away", func(e env) error { return e.c.PosixRename(p(e, e.git), p(e, "old")) }}, |
| 2073 | + {"rename into .git", func(e env) error { return e.c.PosixRename(p(e, "src/main.go"), p(e, e.git+"/hooks/x")) }}, |
| 2074 | + {"hardlink into hooks", func(e env) error { return e.c.Link(p(e, "src/main.go"), p(e, e.git+"/hooks/x")) }}, |
| 2075 | + {"chmod config", func(e env) error { return e.c.Chmod(p(e, e.git+"/config"), 0o444) }}, |
| 2076 | + {"truncate config", func(e env) error { return e.c.Truncate(p(e, e.git+"/config"), 0) }}, |
| 2077 | + {"write gitfile", func(e env) error { return open(e, "src/"+e.gitfile, os.O_WRONLY|os.O_TRUNC) }}, |
| 2078 | + {"replace gitfile", func(e env) error { return e.c.PosixRename(p(e, "src/main.go"), p(e, "src/"+e.gitfile)) }}, |
| 2079 | + {"remove gitfile", func(e env) error { return e.c.Remove(p(e, "src/"+e.gitfile)) }}, |
| 2080 | + } |
| 2081 | + for _, a := range attempts { |
| 2082 | + t.Run(a.name, func(t *testing.T) { |
| 2083 | + c, root := setupRooted(t, false) |
| 2084 | + gitfileLong := filepath.Join(root, "src", ".git") |
| 2085 | + if err := os.WriteFile(gitfileLong, []byte("gitdir: x"), 0o644); err != nil { |
| 2086 | + t.Fatal(err) |
| 2087 | + } |
| 2088 | + e := env{c: c, root: root, git: shortBase(t, filepath.Join(root, ".git")), gitfile: shortBase(t, gitfileLong)} |
| 2089 | + if strings.EqualFold(e.git, ".git") || strings.EqualFold(e.gitfile, ".git") { |
| 2090 | + t.Skip("8.3 names are not created on this volume") |
| 2091 | + } |
| 2092 | + if err := a.f(e); err == nil { |
| 2093 | + t.Error("expected an error") |
| 2094 | + } |
| 2095 | + assertUnchanged(t, root) |
| 2096 | + if b, err := os.ReadFile(gitfileLong); err != nil || string(b) != "gitdir: x" { |
| 2097 | + t.Fatalf("src/.git changed: %q, %v", b, err) |
| 2098 | + } |
| 2099 | + }) |
| 2100 | + } |
| 2101 | +} |
| 2102 | + |
| 2103 | +func TestRootedDeniesWindowsNames(t *testing.T) { |
| 2104 | + junction := func(t *testing.T, root string) { |
| 2105 | + t.Helper() |
| 2106 | + // Unlike a symlink, a junction needs no privilege. |
| 2107 | + out, err := exec.Command("cmd", "/c", "mklink", "/J", filepath.Join(root, "jn"), filepath.Join(root, ".git")).CombinedOutput() |
| 2108 | + if err != nil { |
| 2109 | + t.Fatalf("mklink: %v: %s", err, out) |
| 2110 | + } |
| 2111 | + } |
| 2112 | + attempts := []struct { |
| 2113 | + name string |
| 2114 | + setup func(t *testing.T, root string) |
| 2115 | + path string |
| 2116 | + }{ |
| 2117 | + {"stream of .git", nil, ".git::$INDEX_ALLOCATION/hooks/pre-commit"}, |
| 2118 | + {"stream of a file", nil, "src/main.go:x"}, |
| 2119 | + {"backslashes", nil, `src\..\.git\hooks\pre-commit`}, |
| 2120 | + {"via junction", junction, "jn/hooks/pre-commit"}, |
| 2121 | + {"via junction to a file", junction, "jn/config"}, |
| 2122 | + } |
| 2123 | + for _, a := range attempts { |
| 2124 | + t.Run(a.name, func(t *testing.T) { |
| 2125 | + c, root := setupRooted(t, false) |
| 2126 | + if a.setup != nil { |
| 2127 | + a.setup(t, root) |
| 2128 | + } |
| 2129 | + if f, err := c.OpenFile(root+`\`+a.path, os.O_RDWR|os.O_CREATE|os.O_TRUNC); err == nil { |
| 2130 | + f.Close() |
| 2131 | + t.Error("expected an error") |
| 2132 | + } |
| 2133 | + assertUnchanged(t, root) |
| 2134 | + if fis, err := os.ReadDir(filepath.Join(root, "src")); err != nil || len(fis) != 1 { |
| 2135 | + t.Fatalf("src entries changed: %v, %v", fis, err) |
| 2136 | + } |
| 2137 | + }) |
| 2138 | + } |
| 2139 | +} |
| 2140 | + |
| 2141 | +func TestRootedSymlinkUnsupported(t *testing.T) { |
| 2142 | + c, root := setupRooted(t, false) |
| 2143 | + if err := c.Symlink("main.go", filepath.Join(root, "src", "link")); err == nil { |
| 2144 | + t.Fatal("expected an error") |
| 2145 | + } |
| 2146 | + if _, err := os.Lstat(filepath.Join(root, "src", "link")); err == nil { |
| 2147 | + t.Fatal("the symlink was created") |
| 2148 | + } |
| 2149 | +} |
| 2150 | -- |
| 2151 | 2.47.3 |
| 2152 | |