How to check the device number of a device in /proc/1/ns/{ns}
?
I've read the code for a Go library (see below), which states that it's possible to determine, if a container is in the host namespace or not: the device number of an unnamespaced /proc/1/ns/{ns}
is 4 and anything else is higher.
Now, in a fresh Debian container without user namespace or cgroup, I run the following command:
root@54d74f795843:/# ls -la /proc/1/ns
total 0
dr-x--x--x 2 root root 0 Feb 29 17:18 .
dr-xr-xr-x 9 root root 0 Feb 29 17:18 ..
lrwxrwxrwx 1 root root 0 Feb 29 17:18 cgroup -> 'cgroup:[4026531835]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 ipc -> 'ipc:[4026532290]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 mnt -> 'mnt:[4026532288]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 net -> 'net:[4026532293]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 pid -> 'pid:[4026532291]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 user -> 'user:[4026531837]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 uts -> 'uts:[4026532289]'
What does the 4026531837 in 'user:[4026531837]'
mean here? I cannot be the device number, because the container is using the same user namespace as the host (I've verified that).
How can I list the device numbers of the files /proc/1/ns/{ns}
? The ls -la
command shows those files are symbolic links, so how can they have a device number?
amicontained/vendor/github.com/jessfraz/bpfd/proc/proc.go/
// HasNamespace determines if a container is using a particular namespace or the
// host namespace.
// The device number of an unnamespaced /proc/1/ns/{ns} is 4 and anything else is
// higher.
// Only works from inside a container.
func HasNamespace(ns string) (bool, error) {
file := fmt.Sprintf("/proc/1/ns/%s", ns)
// Use Lstat to not follow the symlink.
var info syscall.Stat_t
if err := syscall.Lstat(file, &info); err != nil {
return false, &os.PathError{Op: "lstat", Path: file, Err: err}
}
// Get the device number. If it is higher than 4 it is in a namespace.
if info.Dev > 4 {
return true, nil
}
return false, nil
}
stat(2)
manpage (don't confusest_dev
withst_rdev
). That's how you can tell if two paths refer to the same file: stat them and compare theirdev:ino
tuple. BTW the trick from the Q doesn't work. The device number of the ns files is still 4 inside the container.