Skip to content

Commit 0809631

Browse files
committed
Add support for Linux Network Devices
Implement support for passing Linux Network Devices to the container network namespace. The network device is passed during the creation of the container, before the process is started. It implements the logic defined in the OCI runtime specification. Change-Id: I190d5c444f03e65bbbfe5b4bc90809c0ad0a2017 Signed-off-by: Antonio Ojea <[email protected]>
1 parent 503168a commit 0809631

File tree

12 files changed

+680
-1
lines changed

12 files changed

+680
-1
lines changed

Diff for: features.go

+3
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ var featuresCommand = cli.Command{
6363
Enabled: &t,
6464
},
6565
},
66+
NetDevices: &features.NetDevices{
67+
Enabled: &t,
68+
},
6669
},
6770
PotentiallyUnsafeConfigAnnotations: []string{
6871
"bundle",

Diff for: go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ require (
2121
github.com/sirupsen/logrus v1.9.3
2222
github.com/urfave/cli v1.22.16
2323
github.com/vishvananda/netlink v1.3.0
24+
github.com/vishvananda/netns v0.0.4
2425
golang.org/x/net v0.37.0
2526
golang.org/x/sys v0.31.0
2627
google.golang.org/protobuf v1.36.5
@@ -37,5 +38,4 @@ require (
3738
github.com/cilium/ebpf v0.17.3 // indirect
3839
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
3940
github.com/russross/blackfriday/v2 v2.1.0 // indirect
40-
github.com/vishvananda/netns v0.0.4 // indirect
4141
)

Diff for: libcontainer/configs/config.go

+3
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,9 @@ type Config struct {
119119
// 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!
120120
Devices []*devices.Device `json:"devices"`
121121

122+
// NetDevices are key-value pairs, keyed by network device name, moved to the container's network namespace.
123+
NetDevices map[string]*LinuxNetDevice `json:"netDevices"`
124+
122125
MountLabel string `json:"mount_label,omitempty"`
123126

124127
// Hostname optionally sets the container's hostname if provided.

Diff for: libcontainer/configs/netdevices.go

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package configs
2+
3+
// LinuxNetDevice represents a single network device to be added to the container's network namespace.
4+
type LinuxNetDevice struct {
5+
// Name of the device in the container namespace.
6+
Name string `json:"name,omitempty"`
7+
}

Diff for: libcontainer/configs/validate/validator.go

+38
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ func Validate(config *configs.Config) error {
2424
cgroupsCheck,
2525
rootfs,
2626
network,
27+
netdevices,
2728
uts,
2829
security,
2930
namespaces,
@@ -70,6 +71,43 @@ func rootfs(config *configs.Config) error {
7071
return nil
7172
}
7273

74+
// https://elixir.bootlin.com/linux/v6.12/source/net/core/dev.c#L1066
75+
func devValidName(name string) bool {
76+
if len(name) == 0 || len(name) > unix.IFNAMSIZ {
77+
return false
78+
}
79+
if (name == ".") || (name == "..") {
80+
return false
81+
}
82+
if strings.ContainsAny(name, "/: ") {
83+
return false
84+
}
85+
return true
86+
}
87+
88+
func netdevices(config *configs.Config) error {
89+
if len(config.NetDevices) == 0 {
90+
return nil
91+
}
92+
if !config.Namespaces.Contains(configs.NEWNET) {
93+
return errors.New("unable to move network devices without a NET namespace")
94+
}
95+
96+
if config.RootlessEUID || config.RootlessCgroups {
97+
return errors.New("network devices are not supported for rootless containers")
98+
}
99+
100+
for name, netdev := range config.NetDevices {
101+
if !devValidName(name) {
102+
return fmt.Errorf("invalid network device name %q", name)
103+
}
104+
if netdev.Name != "" && !devValidName(netdev.Name) {
105+
return fmt.Errorf("invalid network device name %q", netdev.Name)
106+
}
107+
}
108+
return nil
109+
}
110+
73111
func network(config *configs.Config) error {
74112
if !config.Namespaces.Contains(configs.NEWNET) {
75113
if len(config.Networks) > 0 || len(config.Routes) > 0 {

Diff for: libcontainer/configs/validate/validator_test.go

+168
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package validate
33
import (
44
"os"
55
"path/filepath"
6+
"strings"
67
"testing"
78

89
"github.com/opencontainers/runc/libcontainer/configs"
@@ -877,3 +878,170 @@ func TestValidateIOPriority(t *testing.T) {
877878
}
878879
}
879880
}
881+
882+
func TestValidateNetDevices(t *testing.T) {
883+
testCases := []struct {
884+
name string
885+
isErr bool
886+
config *configs.Config
887+
}{
888+
{
889+
name: "network device",
890+
config: &configs.Config{
891+
Namespaces: configs.Namespaces(
892+
[]configs.Namespace{
893+
{
894+
Type: configs.NEWNET,
895+
Path: "/var/run/netns/blue",
896+
},
897+
},
898+
),
899+
NetDevices: map[string]*configs.LinuxNetDevice{
900+
"eth0": {},
901+
},
902+
},
903+
},
904+
{
905+
name: "network device rename",
906+
config: &configs.Config{
907+
Namespaces: configs.Namespaces(
908+
[]configs.Namespace{
909+
{
910+
Type: configs.NEWNET,
911+
Path: "/var/run/netns/blue",
912+
},
913+
},
914+
),
915+
NetDevices: map[string]*configs.LinuxNetDevice{
916+
"eth0": {
917+
Name: "c0",
918+
},
919+
},
920+
},
921+
},
922+
{
923+
name: "network device network namespace created by runc",
924+
config: &configs.Config{
925+
Namespaces: configs.Namespaces(
926+
[]configs.Namespace{
927+
{
928+
Type: configs.NEWNET,
929+
Path: "",
930+
},
931+
},
932+
),
933+
NetDevices: map[string]*configs.LinuxNetDevice{
934+
"eth0": {},
935+
},
936+
},
937+
},
938+
{
939+
name: "network device network namespace empty",
940+
isErr: true,
941+
config: &configs.Config{
942+
Namespaces: configs.Namespaces(
943+
[]configs.Namespace{},
944+
),
945+
NetDevices: map[string]*configs.LinuxNetDevice{
946+
"eth0": {},
947+
},
948+
},
949+
},
950+
{
951+
name: "network device rootless EUID",
952+
isErr: true,
953+
config: &configs.Config{
954+
Namespaces: configs.Namespaces(
955+
[]configs.Namespace{
956+
{
957+
Type: configs.NEWNET,
958+
Path: "/var/run/netns/blue",
959+
},
960+
},
961+
),
962+
RootlessEUID: true,
963+
NetDevices: map[string]*configs.LinuxNetDevice{
964+
"eth0": {},
965+
},
966+
},
967+
},
968+
{
969+
name: "network device rootless",
970+
isErr: true,
971+
config: &configs.Config{
972+
Namespaces: configs.Namespaces(
973+
[]configs.Namespace{
974+
{
975+
Type: configs.NEWNET,
976+
Path: "/var/run/netns/blue",
977+
},
978+
},
979+
),
980+
RootlessCgroups: true,
981+
NetDevices: map[string]*configs.LinuxNetDevice{
982+
"eth0": {},
983+
},
984+
},
985+
},
986+
{
987+
name: "network device bad name",
988+
isErr: true,
989+
config: &configs.Config{
990+
Namespaces: configs.Namespaces(
991+
[]configs.Namespace{
992+
{
993+
Type: configs.NEWNET,
994+
Path: "/var/run/netns/blue",
995+
},
996+
},
997+
),
998+
NetDevices: map[string]*configs.LinuxNetDevice{
999+
"eth0": {
1000+
Name: "eth0/",
1001+
},
1002+
},
1003+
},
1004+
},
1005+
}
1006+
1007+
for _, tc := range testCases {
1008+
tc := tc
1009+
t.Run(tc.name, func(t *testing.T) {
1010+
config := tc.config
1011+
config.Rootfs = "/var"
1012+
1013+
err := Validate(config)
1014+
if tc.isErr && err == nil {
1015+
t.Error("expected error, got nil")
1016+
}
1017+
1018+
if !tc.isErr && err != nil {
1019+
t.Error(err)
1020+
}
1021+
})
1022+
}
1023+
}
1024+
1025+
func TestDevValidName(t *testing.T) {
1026+
testCases := []struct {
1027+
name string
1028+
valid bool
1029+
}{
1030+
{name: "", valid: false},
1031+
{name: "a", valid: true},
1032+
{name: strings.Repeat("a", unix.IFNAMSIZ), valid: true},
1033+
{name: strings.Repeat("a", unix.IFNAMSIZ+1), valid: false},
1034+
{name: ".", valid: false},
1035+
{name: "..", valid: false},
1036+
{name: "dev/null", valid: false},
1037+
{name: "valid:name", valid: false},
1038+
{name: "valid name", valid: false},
1039+
}
1040+
for _, tc := range testCases {
1041+
t.Run(tc.name, func(t *testing.T) {
1042+
if devValidName(tc.name) != tc.valid {
1043+
t.Fatalf("name %q, expected valid: %v", tc.name, tc.valid)
1044+
}
1045+
})
1046+
}
1047+
}

Diff for: libcontainer/network_linux.go

+100
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ import (
99

1010
"github.com/opencontainers/runc/libcontainer/configs"
1111
"github.com/opencontainers/runc/types"
12+
"github.com/sirupsen/logrus"
1213
"github.com/vishvananda/netlink"
14+
"github.com/vishvananda/netlink/nl"
15+
"github.com/vishvananda/netns"
16+
17+
"golang.org/x/sys/unix"
1318
)
1419

1520
var strategies = map[string]networkStrategy{
@@ -98,3 +103,98 @@ func (l *loopback) attach(n *configs.Network) (err error) {
98103
func (l *loopback) detach(n *configs.Network) (err error) {
99104
return nil
100105
}
106+
107+
// devChangeNetNamespace allows to change the device name from a network namespace and optionally replace the existing name.
108+
// This function ensures that the move and rename operations occur simultaneously.
109+
// It preserves existing interface attributes, including IP addresses.
110+
func devChangeNetNamespace(name string, nsPath string, device configs.LinuxNetDevice) error {
111+
logrus.Debugf("attaching network device %s with attrs %+v to network namespace %s", name, device, nsPath)
112+
link, err := netlink.LinkByName(name)
113+
if err != nil {
114+
return fmt.Errorf("link not found for interface %s on runtime namespace: %w", name, err)
115+
}
116+
117+
// set the interface down to change the attributes safely
118+
err = netlink.LinkSetDown(link)
119+
if err != nil {
120+
return fmt.Errorf("fail to set link down: %w", err)
121+
}
122+
123+
// get the existing IP addresses
124+
addresses, err := netlink.AddrList(link, netlink.FAMILY_ALL)
125+
if err != nil {
126+
return fmt.Errorf("fail to get ip addresses: %w", err)
127+
}
128+
129+
// do interface rename and namespace change in the same operation to avoid
130+
// possible conflicts with the interface name.
131+
flags := unix.NLM_F_REQUEST | unix.NLM_F_ACK
132+
req := nl.NewNetlinkRequest(unix.RTM_NEWLINK, flags)
133+
134+
// Get a netlink socket in current namespace
135+
s, err := nl.GetNetlinkSocketAt(netns.None(), netns.None(), unix.NETLINK_ROUTE)
136+
if err != nil {
137+
return fmt.Errorf("could not get network namespace handle: %w", err)
138+
}
139+
defer s.Close()
140+
141+
req.Sockets = map[int]*nl.SocketHandle{
142+
unix.NETLINK_ROUTE: {Socket: s},
143+
}
144+
145+
// set the interface index
146+
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
147+
msg.Index = int32(link.Attrs().Index)
148+
req.AddData(msg)
149+
150+
// set the interface name, rename if requested
151+
newName := name
152+
if device.Name != "" {
153+
newName = device.Name
154+
}
155+
nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(newName))
156+
req.AddData(nameData)
157+
158+
// set the new network namespace
159+
ns, err := netns.GetFromPath(nsPath)
160+
if err != nil {
161+
return fmt.Errorf("could not get network namespace from path %s for network device %s : %w", nsPath, name, err)
162+
}
163+
164+
val := nl.Uint32Attr(uint32(ns))
165+
attr := nl.NewRtAttr(unix.IFLA_NET_NS_FD, val)
166+
req.AddData(attr)
167+
168+
_, err = req.Execute(unix.NETLINK_ROUTE, 0)
169+
if err != nil {
170+
return fmt.Errorf("fail to move network device %s to network namespace %s: %w", name, nsPath, err)
171+
}
172+
173+
// to avoid golang problem with goroutines we create the socket in the
174+
// namespace and use it directly
175+
nhNs, err := netlink.NewHandleAt(ns)
176+
if err != nil {
177+
return err
178+
}
179+
180+
nsLink, err := nhNs.LinkByName(newName)
181+
if err != nil {
182+
return fmt.Errorf("link not found for interface %s on namespace %s : %w", newName, nsPath, err)
183+
}
184+
185+
for _, address := range addresses {
186+
// remove the interface attribute of the original address
187+
// to avoid issues when the interface is renamed.
188+
err = nhNs.AddrAdd(nsLink, &netlink.Addr{IPNet: address.IPNet})
189+
if err != nil {
190+
return fmt.Errorf("fail to set up address %s on namespace %s: %w", address.String(), nsPath, err)
191+
}
192+
}
193+
194+
err = nhNs.LinkSetUp(nsLink)
195+
if err != nil {
196+
return fmt.Errorf("fail to set up interface %s on namespace %s: %w", nsLink.Attrs().Name, nsPath, err)
197+
}
198+
199+
return nil
200+
}

0 commit comments

Comments
 (0)