Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions discover/discovery_fd.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ func scanFd(_ species.NamespaceType, procfs string, fakeprocfs bool, result *Res
if nstype == species.NaNS {
continue
}
nsr = ops.NamespacePath(procFdPath)
} else if !scanFds {
// while scanning for sockets was requested, scanning fds
// wasn't, so we then don't dig deeper into fds that might
Expand Down
8 changes: 8 additions & 0 deletions discover/discovery_fd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (

"github.com/thediveo/lxkns/model"
"github.com/thediveo/lxkns/nstest"
"github.com/thediveo/lxkns/ops"
"github.com/thediveo/lxkns/species"

. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -131,6 +132,13 @@ read # wait for test to proceed()
allns := Namespaces(FromFds())
Expect(allns.Namespaces[model.NetNS]).To(
HaveKey(species.NamespaceIDfromInode(netnsino)))

By("using the socket-based reference and owner of the transient network namespace")
allns = Namespaces(FromProcs(), FromFds(), WithOwnership())
sockns := allns.Namespaces[model.NetNS][species.NamespaceIDfromInode(netnsino)]
Expect(sockns).NotTo(BeNil())
Expect(ops.NamespacePath(sockns.Ref()[0]).ID()).To(Equal(sockns.ID()))
Expect(sockns.Owner()).NotTo(BeNil())
})

It("discovers the socket-to-process mapping", func() {
Expand Down
4 changes: 4 additions & 0 deletions discover/discovery_opt.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ func WithoutTaskAffinityAndScheduling() DiscoveryOption {
}

// FromFds opts to find namespaces from the open file descriptors of processes.
//
// This includes network namespaces only kept alive by sockets; these get
// referenced by the socket's “/proc/$PID/fd/$FD” path, see
// [github.com/thediveo/lxkns/ops.NamespacePath] for the implications.
func FromFds() DiscoveryOption {
return func(o *DiscoverOpts) { o.ScanFds = true }
}
Expand Down
4 changes: 3 additions & 1 deletion discover/discovery_proc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ var _ = Describe("Discover from processes", Ordered, func() {
}

// hear, hear ... lsns finally upped its game :D ... again :D:D:D
allns := Namespaces(FromProcs(), FromBindmounts(), WithHierarchy())
// lsns also lists network namespaces only kept alive by sockets, such
// as those of WSL2's initd.
allns := Namespaces(FromProcs(), FromFds(), FromBindmounts(), WithHierarchy())
alllsns := lsns()
ignoreme := regexp.MustCompile(`^(unshare|/bin/bash|runc) (.+ )?/tmp/`)
for _, lsns := range alllsns {
Expand Down
9 changes: 9 additions & 0 deletions ops/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ uintptr respectively.
netns := NamespacePath("/proc/self/ns/net")
path := string(netns)

A [NamespacePath] can also be a procfs fd link to a socket, such as
“/proc/$PID/fd/$FD”, in which case it references the network namespace of that
socket. Using such a reference requires ptrace attach access to the process
(CAP_SYS_PTRACE for other processes) as well as CAP_NET_ADMIN in the user
namespace owning the network namespace. The PID is taken to be in the caller's
PID namespace. Such a reference is only valid as long as the process keeps
this fd open; if the fd number gets reused, the reference might silently point
to a different network namespace.

In case you want to use the [Visit] function for switching namespaces and you
need to support Linux kernels before 4.11 (which lack a required ioctl) then you
can resort to [TypedNamespacePath] instead of [NamespacePath].
Expand Down
22 changes: 10 additions & 12 deletions ops/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package ops

import (
"fmt"
"os"

"github.com/thediveo/ioctl"
"golang.org/x/sys/unix"
Expand Down Expand Up @@ -44,9 +43,8 @@ func (nsp NamespacePath) String() string {
// 🛈 A Linux kernel version 4.11 or later is required.
func (nsp NamespacePath) Type() (species.NamespaceType, error) {
// Since we only need to temporarily open the namespace "file", we keep with
// unix.Open() and and plain file descriptors instead of os.Open() and
// os.File.
fd, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
// plain file descriptors instead of os.Open() and os.File.
fd, err := openNamespacePath(string(nsp))
if err != nil {
return 0, newInvalidNamespaceError(nsp, err)
}
Expand All @@ -61,8 +59,8 @@ func (nsp NamespacePath) Type() (species.NamespaceType, error) {
// ID returns the namespace ID in form of its inode number for any given
// Linux kernel namespace reference.
func (nsp NamespacePath) ID() (species.NamespaceID, error) {
// See above for reasoning why unix.Open() instead of os.Open().
fd, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
// See above for reasoning why plain fds instead of os.Open().
fd, err := openNamespacePath(string(nsp))
if err != nil {
return species.NoneID, err
}
Expand All @@ -77,8 +75,8 @@ func (nsp NamespacePath) ID() (species.NamespaceID, error) {
//
// 🛈 A Linux kernel version 4.9 or later is required.
func (nsp NamespacePath) User() (relations.Relation, error) {
// See above for reasoning why unix.Open() instead of os.Open().
fd, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
// See above for reasoning why plain fds instead of os.Open().
fd, err := openNamespacePath(string(nsp))
if err != nil {
return nil, err
}
Expand All @@ -101,7 +99,7 @@ func (nsp NamespacePath) User() (relations.Relation, error) {
//
// 🛈 A Linux kernel version 4.9 or later is required.
func (nsp NamespacePath) Parent() (relations.Relation, error) {
fd, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
fd, err := openNamespacePath(string(nsp))
if err != nil {
return nil, err
}
Expand All @@ -118,7 +116,7 @@ func (nsp NamespacePath) Parent() (relations.Relation, error) {
//
// 🛈 A Linux kernel version 4.11 or later is required.
func (nsp NamespacePath) OwnerUID() (int, error) {
fd, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
fd, err := openNamespacePath(string(nsp))
if err != nil {
return 0, err
}
Expand All @@ -133,7 +131,7 @@ func (nsp NamespacePath) OwnerUID() (int, error) {
// namespaces under the condition that additionally the type of namespace needs
// to be known at the same time.
func (nsp NamespacePath) OpenTypedReference() (relations.Relation, opener.ReferenceCloser, error) {
f, err := os.Open(string(nsp))
f, err := openNamespaceFile(string(nsp))
if err != nil {
return nil, nil, newInvalidNamespaceError(nsp, err)
}
Expand All @@ -159,7 +157,7 @@ func (nsp NamespacePath) OpenTypedReference() (relations.Relation, opener.Refere
// [NamespacePath.NsFd] is still in use.
func (nsp NamespacePath) NsFd() (int, opener.FdCloser, error) {
var fdi int
fdi, err := unix.Open(string(nsp), unix.O_RDONLY|unix.O_CLOEXEC, 0)
fdi, err := openNamespacePath(string(nsp))
if err != nil {
return fdi, nil, newInvalidNamespaceError(nsp, err)
}
Expand Down
3 changes: 2 additions & 1 deletion ops/portable/portable.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ func (portref PortableReference) openPath(path string) (rel relations.Relation,
// Before we run further checks, we have to open the namespace first, so
// that it cannot get destroyed anymore as long as we keep the fd open that
// is referencing it.
nsf, err := os.Open(path) // #nosec G304
fd, _, err := ops.NamespacePath(path).NsFd()
if err != nil {
return nil, nil, err
}
nsf := os.NewFile(uintptr(fd), path) // takes over ownership of fd from NsFd.
// Ensure to properly close the open namespace reference in case we fail
// down below somewhere while deep in the cross-checks.
defer func() {
Expand Down
97 changes: 97 additions & 0 deletions ops/sockref.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2026 Harald Albrecht.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ops

import (
"errors"
"os"
"strconv"
"strings"

"github.com/thediveo/ioctl"
"golang.org/x/sys/unix"
)

// openNamespacePath opens the namespace referenced by path and returns an
// O_CLOEXEC file descriptor to it. If path is a procfs fd link to a socket
// (“/proc/$PID/fd/$FD”), it returns the network namespace of that socket
// instead, as sockets cannot be opened via procfs.
func openNamespacePath(path string) (int, error) {
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if !errors.Is(err, unix.ENXIO) {
return fd, err
}
if netnsfd, sockerr := socketNetnsFd(path); sockerr == nil {
return netnsfd, nil
}
return -1, err
}

// openNamespaceFile is [openNamespacePath] returning an *[os.File] and errors
// in the same form as [os.Open].
func openNamespaceFile(path string) (*os.File, error) {
fd, err := openNamespacePath(path)
if err != nil {
return nil, &os.PathError{Op: "open", Path: path, Err: err}
}
return os.NewFile(uintptr(fd), path), nil
}

// socketNetnsFd returns a file descriptor to the network namespace of the
// socket referenced by the procfs fd link path, by temporarily duplicating the
// socket's fd into our process.
func socketNetnsFd(path string) (int, error) {
pid, fdno, ok := parseProcFdPath(path)
if !ok {
return -1, unix.EINVAL
}
pidfd, err := unix.PidfdOpen(pid, 0)
if err != nil {
return -1, err
}
defer func() { _ = unix.Close(pidfd) }()
sockfd, err := unix.PidfdGetfd(pidfd, fdno, 0)
if err != nil {
return -1, err
}
defer func() { _ = unix.Close(sockfd) }()
return ioctl.RetFd(sockfd, unix.SIOCGSKNS)
}

// parseProcFdPath returns the PID and fd number from a procfs fd link path of
// the form “.../$PID/fd/$FD” or “.../$PID/task/$TID/fd/$FD”.
func parseProcFdPath(path string) (pid int, fdno int, ok bool) {
elems := strings.Split(path, "/")
n := len(elems)
if n < 4 || elems[n-2] != "fd" {
return 0, 0, false
}
fd, err := strconv.ParseUint(elems[n-1], 10, 31)
if err != nil {
return 0, 0, false
}
pidelem := elems[n-3]
if n >= 6 && elems[n-4] == "task" {
if _, err := strconv.ParseUint(pidelem, 10, 31); err != nil {
return 0, 0, false
}
pidelem = elems[n-5]
}
p, err := strconv.ParseUint(pidelem, 10, 31)
if err != nil || p == 0 {
return 0, 0, false
}
return int(p), int(fd), true
}
Loading
Loading