internal/sys: add VerifyInode helper

This will be used for a few security patches in later patches in this
patchset. The need to verify what kind of inode we are operating on in a
race-free way turns out to be quite a common pattern...

Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
This commit is contained in:
Aleksa Sarai
2025-07-22 16:23:28 +10:00
parent 0007833a45
commit f88a6a6bc5
2 changed files with 35 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
// Package sys is an internal package that contains helper methods for dealing
// with Linux that are more complicated than basic wrappers. Basic wrappers
// usually belong in internal/linux. If you feel something belongs in
// libcontainer/utils or libcontainer/system, it probably belongs here instead.
package sys
+30
View File
@@ -0,0 +1,30 @@
package sys
import (
"fmt"
"os"
"runtime"
"golang.org/x/sys/unix"
)
// VerifyInodeFunc is the callback passed to [VerifyInode] to check if the
// inode is the expected type (and on the correct filesystem type, in the case
// of filesystem-specific inodes).
type VerifyInodeFunc func(stat *unix.Stat_t, statfs *unix.Statfs_t) error
// VerifyInode verifies that the underlying inode for the given file matches an
// expected inode type (possibly on a particular kind of filesystem). This is
// mainly a wrapper around [VerifyInodeFunc].
func VerifyInode(file *os.File, checkFunc VerifyInodeFunc) error {
var stat unix.Stat_t
if err := unix.Fstat(int(file.Fd()), &stat); err != nil {
return fmt.Errorf("fstat %q: %w", file.Name(), err)
}
var statfs unix.Statfs_t
if err := unix.Fstatfs(int(file.Fd()), &statfs); err != nil {
return fmt.Errorf("fstatfs %q: %w", file.Name(), err)
}
runtime.KeepAlive(file)
return checkFunc(&stat, &statfs)
}