Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Linux Network Devices #4538

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions features.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ var featuresCommand = cli.Command{
Enabled: &t,
},
},
NetDevices: &features.NetDevices{
Enabled: &t,
},
},
PotentiallyUnsafeConfigAnnotations: []string{
"bundle",
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require (
github.com/sirupsen/logrus v1.9.3
github.com/urfave/cli v1.22.16
github.com/vishvananda/netlink v1.3.0
github.com/vishvananda/netns v0.0.4
golang.org/x/net v0.37.0
golang.org/x/sys v0.31.0
google.golang.org/protobuf v1.36.5
Expand All @@ -37,5 +38,4 @@ require (
github.com/cilium/ebpf v0.17.3 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/vishvananda/netns v0.0.4 // indirect
)
3 changes: 3 additions & 0 deletions libcontainer/configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ type Config struct {
// The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
Devices []*devices.Device `json:"devices"`

// NetDevices are key-value pairs, keyed by network device name, moved to the container's network namespace.
NetDevices map[string]*LinuxNetDevice `json:"netDevices"`

MountLabel string `json:"mount_label,omitempty"`

// Hostname optionally sets the container's hostname if provided.
Expand Down
7 changes: 7 additions & 0 deletions libcontainer/configs/netdevices.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package configs

// LinuxNetDevice represents a single network device to be added to the container's network namespace.
type LinuxNetDevice struct {
// Name of the device in the container namespace.
Name string `json:"name,omitempty"`
}
38 changes: 38 additions & 0 deletions libcontainer/configs/validate/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func Validate(config *configs.Config) error {
cgroupsCheck,
rootfs,
network,
netdevices,
uts,
security,
namespaces,
Expand Down Expand Up @@ -70,6 +71,43 @@ func rootfs(config *configs.Config) error {
return nil
}

// https://elixir.bootlin.com/linux/v6.12/source/net/core/dev.c#L1066
func devValidName(name string) bool {
if len(name) == 0 || len(name) > unix.IFNAMSIZ {
return false
}
if (name == ".") || (name == "..") {
return false
}
if strings.ContainsAny(name, "/: ") {
return false
}
return true
}

func netdevices(config *configs.Config) error {
if len(config.NetDevices) == 0 {
return nil
}
if !config.Namespaces.Contains(configs.NEWNET) {
return errors.New("unable to move network devices without a NET namespace")
}

if config.RootlessEUID || config.RootlessCgroups {
return errors.New("network devices are not supported for rootless containers")
}

for name, netdev := range config.NetDevices {
if !devValidName(name) {
return fmt.Errorf("invalid network device name %q", name)
}
if netdev.Name != "" && !devValidName(netdev.Name) {
return fmt.Errorf("invalid network device name %q", netdev.Name)
}
}
return nil
}

func network(config *configs.Config) error {
if !config.Namespaces.Contains(configs.NEWNET) {
if len(config.Networks) > 0 || len(config.Routes) > 0 {
Expand Down
168 changes: 168 additions & 0 deletions libcontainer/configs/validate/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package validate
import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/opencontainers/runc/libcontainer/configs"
Expand Down Expand Up @@ -877,3 +878,170 @@ func TestValidateIOPriority(t *testing.T) {
}
}
}

func TestValidateNetDevices(t *testing.T) {
testCases := []struct {
name string
isErr bool
config *configs.Config
}{
{
name: "network device",
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "/var/run/netns/blue",
},
},
),
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {},
},
},
},
{
name: "network device rename",
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "/var/run/netns/blue",
},
},
),
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {
Name: "c0",
},
},
},
},
{
name: "network device network namespace created by runc",
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "",
},
},
),
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {},
},
},
},
{
name: "network device network namespace empty",
isErr: true,
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{},
),
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {},
},
},
},
{
name: "network device rootless EUID",
isErr: true,
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "/var/run/netns/blue",
},
},
),
RootlessEUID: true,
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {},
},
},
},
{
name: "network device rootless",
isErr: true,
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "/var/run/netns/blue",
},
},
),
RootlessCgroups: true,
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {},
},
},
},
{
name: "network device bad name",
isErr: true,
config: &configs.Config{
Namespaces: configs.Namespaces(
[]configs.Namespace{
{
Type: configs.NEWNET,
Path: "/var/run/netns/blue",
},
},
),
NetDevices: map[string]*configs.LinuxNetDevice{
"eth0": {
Name: "eth0/",
},
},
},
},
}

for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
config := tc.config
config.Rootfs = "/var"

err := Validate(config)
if tc.isErr && err == nil {
t.Error("expected error, got nil")
}

if !tc.isErr && err != nil {
t.Error(err)
}
})
}
}

func TestDevValidName(t *testing.T) {
testCases := []struct {
name string
valid bool
}{
{name: "", valid: false},
{name: "a", valid: true},
{name: strings.Repeat("a", unix.IFNAMSIZ), valid: true},
{name: strings.Repeat("a", unix.IFNAMSIZ+1), valid: false},
{name: ".", valid: false},
{name: "..", valid: false},
{name: "dev/null", valid: false},
{name: "valid:name", valid: false},
{name: "valid name", valid: false},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if devValidName(tc.name) != tc.valid {
t.Fatalf("name %q, expected valid: %v", tc.name, tc.valid)
}
})
}
}
100 changes: 100 additions & 0 deletions libcontainer/network_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import (

"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/types"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"

"golang.org/x/sys/unix"
)

var strategies = map[string]networkStrategy{
Expand Down Expand Up @@ -98,3 +103,98 @@ func (l *loopback) attach(n *configs.Network) (err error) {
func (l *loopback) detach(n *configs.Network) (err error) {
return nil
}

// devChangeNetNamespace allows to change the device name from a network namespace and optionally replace the existing name.
// This function ensures that the move and rename operations occur simultaneously.
// It preserves existing interface attributes, including IP addresses.
func devChangeNetNamespace(name string, nsPath string, device configs.LinuxNetDevice) error {
logrus.Debugf("attaching network device %s with attrs %+v to network namespace %s", name, device, nsPath)
link, err := netlink.LinkByName(name)
if err != nil {
return fmt.Errorf("link not found for interface %s on runtime namespace: %w", name, err)
}

// set the interface down to change the attributes safely
err = netlink.LinkSetDown(link)
if err != nil {
return fmt.Errorf("fail to set link down: %w", err)
}

// get the existing IP addresses
addresses, err := netlink.AddrList(link, netlink.FAMILY_ALL)
if err != nil {
return fmt.Errorf("fail to get ip addresses: %w", err)
}

// do interface rename and namespace change in the same operation to avoid
// possible conflicts with the interface name.
flags := unix.NLM_F_REQUEST | unix.NLM_F_ACK
req := nl.NewNetlinkRequest(unix.RTM_NEWLINK, flags)

// Get a netlink socket in current namespace
s, err := nl.GetNetlinkSocketAt(netns.None(), netns.None(), unix.NETLINK_ROUTE)
if err != nil {
return fmt.Errorf("could not get network namespace handle: %w", err)
}
defer s.Close()

req.Sockets = map[int]*nl.SocketHandle{
unix.NETLINK_ROUTE: {Socket: s},
}

// set the interface index
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(link.Attrs().Index)
req.AddData(msg)

// set the interface name, rename if requested
newName := name
if device.Name != "" {
newName = device.Name
}
nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(newName))
req.AddData(nameData)

// set the new network namespace
ns, err := netns.GetFromPath(nsPath)
if err != nil {
return fmt.Errorf("could not get network namespace from path %s for network device %s : %w", nsPath, name, err)
}

val := nl.Uint32Attr(uint32(ns))
attr := nl.NewRtAttr(unix.IFLA_NET_NS_FD, val)
req.AddData(attr)

_, err = req.Execute(unix.NETLINK_ROUTE, 0)
if err != nil {
return fmt.Errorf("fail to move network device %s to network namespace %s: %w", name, nsPath, err)
}

// to avoid golang problem with goroutines we create the socket in the
// namespace and use it directly
nhNs, err := netlink.NewHandleAt(ns)
if err != nil {
return err
}

nsLink, err := nhNs.LinkByName(newName)
if err != nil {
return fmt.Errorf("link not found for interface %s on namespace %s : %w", newName, nsPath, err)
}

for _, address := range addresses {
// remove the interface attribute of the original address
// to avoid issues when the interface is renamed.
err = nhNs.AddrAdd(nsLink, &netlink.Addr{IPNet: address.IPNet})
if err != nil {
return fmt.Errorf("fail to set up address %s on namespace %s: %w", address.String(), nsPath, err)
}
}

err = nhNs.LinkSetUp(nsLink)
if err != nil {
return fmt.Errorf("fail to set up interface %s on namespace %s: %w", nsLink.Attrs().Name, nsPath, err)
}

return nil
}
Loading
Loading