Skip to content

Commit db19bbe

Browse files
committed
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 <[email protected]>
1 parent fb01482 commit db19bbe

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

internal/sys/doc.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Package sys is an internal package that contains helper methods for dealing
2+
// with Linux that are more complicated than basic wrappers. Basic wrappers
3+
// usually belong in internal/linux. If you feel something belongs in
4+
// libcontainer/utils or libcontainer/system, it probably belongs here instead.
5+
package sys

internal/sys/verify_inode_unix.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package sys
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"runtime"
7+
8+
"golang.org/x/sys/unix"
9+
)
10+
11+
// VerifyInodeFunc is the callback passed to [VerifyInode] to check if the
12+
// inode is the expected type (and on the correct filesystem type, in the case
13+
// of filesystem-specific inodes).
14+
type VerifyInodeFunc func(stat *unix.Stat_t, statfs *unix.Statfs_t) error
15+
16+
// VerifyInode verifies that the underlying inode for the given file matches an
17+
// expected inode type (possibly on a particular kind of filesystem). This is
18+
// mainly a wrapper around [VerifyInodeFunc].
19+
func VerifyInode(file *os.File, checkFunc VerifyInodeFunc) error {
20+
var stat unix.Stat_t
21+
if err := unix.Fstat(int(file.Fd()), &stat); err != nil {
22+
return fmt.Errorf("fstat %q: %w", file.Name(), err)
23+
}
24+
var statfs unix.Statfs_t
25+
if err := unix.Fstatfs(int(file.Fd()), &statfs); err != nil {
26+
return fmt.Errorf("fstatfs %q: %w", file.Name(), err)
27+
}
28+
runtime.KeepAlive(file)
29+
return checkFunc(&stat, &statfs)
30+
}

0 commit comments

Comments
 (0)