| 1 | // Copyright 2022 CNI authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package main |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "errors" |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "os/exec" |
| 23 | "runtime" |
| 24 | "strconv" |
| 25 | "syscall" |
| 26 | |
| 27 | "github.com/opencontainers/selinux/go-selinux" |
| 28 | "github.com/vishvananda/netlink" |
| 29 | "golang.org/x/sys/unix" |
| 30 | |
| 31 | "github.com/containernetworking/cni/pkg/skel" |
| 32 | "github.com/containernetworking/cni/pkg/types" |
| 33 | current "github.com/containernetworking/cni/pkg/types/100" |
| 34 | "github.com/containernetworking/cni/pkg/version" |
| 35 | "github.com/containernetworking/plugins/pkg/ip" |
| 36 | "github.com/containernetworking/plugins/pkg/ipam" |
| 37 | "github.com/containernetworking/plugins/pkg/netlinksafe" |
| 38 | "github.com/containernetworking/plugins/pkg/ns" |
| 39 | bv "github.com/containernetworking/plugins/pkg/utils/buildversion" |
| 40 | "github.com/containernetworking/plugins/pkg/utils/sysctl" |
| 41 | ) |
| 42 | |
| 43 | type NetConf struct { |
| 44 | types.NetConf |
| 45 | MultiQueue bool `json:"multiQueue"` |
| 46 | MTU int `json:"mtu"` |
| 47 | Mac string `json:"mac,omitempty"` |
| 48 | Owner *uint32 `json:"owner,omitempty"` |
| 49 | Group *uint32 `json:"group,omitempty"` |
| 50 | SelinuxContext string `json:"selinuxContext,omitempty"` |
| 51 | Bridge string `json:"bridge,omitempty"` |
| 52 | Args *struct{} `json:"args,omitempty"` |
| 53 | RuntimeConfig struct { |
| 54 | Mac string `json:"mac,omitempty"` |
| 55 | } `json:"runtimeConfig,omitempty"` |
| 56 | } |
| 57 | |
| 58 | // MacEnvArgs represents CNI_ARG |
| 59 | type MacEnvArgs struct { |
| 60 | types.CommonArgs |
| 61 | MAC types.UnmarshallableString `json:"mac,omitempty"` |
| 62 | } |
| 63 | |
| 64 | func init() { |
| 65 | // this ensures that main runs only on main thread (thread group leader). |
| 66 | // since namespace ops (unshare, setns) are done for a single thread, we |
| 67 | // must ensure that the goroutine does not jump from OS thread to thread |
| 68 | runtime.LockOSThread() |
| 69 | } |
| 70 | |
| 71 | func loadConf(args *skel.CmdArgs) (*NetConf, string, error) { |
| 72 | n := &NetConf{} |
| 73 | if err := json.Unmarshal(args.StdinData, n); err != nil { |
| 74 | return nil, "", fmt.Errorf("failed to load netconf: %v", err) |
| 75 | } |
| 76 | if args.Args != "" { |
| 77 | e := MacEnvArgs{} |
| 78 | err := types.LoadArgs(args.Args, &e) |
| 79 | if err != nil { |
| 80 | return nil, "", err |
| 81 | } |
| 82 | |
| 83 | if e.MAC != "" { |
| 84 | n.Mac = string(e.MAC) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | if n.RuntimeConfig.Mac != "" { |
| 89 | n.Mac = n.RuntimeConfig.Mac |
| 90 | } |
| 91 | |
| 92 | return n, n.CNIVersion, nil |
| 93 | } |
| 94 | |
| 95 | // We want to share the parent process std{in|out|err} - fds 0 through 2. |
| 96 | // Since the FDs are inherited on fork / exec, we close on exec all others. |
| 97 | func closeFileDescriptorsOnExec() { |
| 98 | minFDToCloseOnExec := 3 |
| 99 | maxFDToCloseOnExec := 256 |
| 100 | for fd := minFDToCloseOnExec; fd < maxFDToCloseOnExec; fd++ { |
| 101 | syscall.CloseOnExec(fd) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // Due to issues with the vishvananda/netlink library (fix pending) it is not possible to create an ownerless/groupless |
| 106 | // tap device. Until the issue is fixed, the workaround for creating a tap device with no owner/group is to use the iptool |
| 107 | func createTapWithIptool(tmpName string, mtu int, multiqueue bool, mac string, owner *uint32, group *uint32) error { |
| 108 | closeFileDescriptorsOnExec() |
| 109 | |
| 110 | tapDeviceArgs := []string{"tuntap", "add", "mode", "tap", "name", tmpName} |
| 111 | if multiqueue { |
| 112 | tapDeviceArgs = append(tapDeviceArgs, "multi_queue") |
| 113 | } |
| 114 | |
| 115 | if owner != nil { |
| 116 | tapDeviceArgs = append(tapDeviceArgs, "user", fmt.Sprintf("%d", *owner)) |
| 117 | } |
| 118 | if group != nil { |
| 119 | tapDeviceArgs = append(tapDeviceArgs, "group", fmt.Sprintf("%d", *group)) |
| 120 | } |
| 121 | output, err := exec.Command("ip", tapDeviceArgs...).CombinedOutput() |
| 122 | if err != nil { |
| 123 | return fmt.Errorf("failed to run command %s: %v", output, err) |
| 124 | } |
| 125 | |
| 126 | tapDeviceArgs = []string{"link", "set", tmpName} |
| 127 | if mtu != 0 { |
| 128 | tapDeviceArgs = append(tapDeviceArgs, "mtu", strconv.Itoa(mtu)) |
| 129 | } |
| 130 | if mac != "" { |
| 131 | tapDeviceArgs = append(tapDeviceArgs, "address", mac) |
| 132 | } |
| 133 | output, err = exec.Command("ip", tapDeviceArgs...).CombinedOutput() |
| 134 | if err != nil { |
| 135 | return fmt.Errorf("failed to run command %s: %v", output, err) |
| 136 | } |
| 137 | return nil |
| 138 | } |
| 139 | |
| 140 | func createLinkWithNetlink(tmpName string, mtu int, nsFd int, multiqueue bool, mac string, owner *uint32, group *uint32) error { |
| 141 | linkAttrs := netlink.NewLinkAttrs() |
| 142 | linkAttrs.Name = tmpName |
| 143 | linkAttrs.Namespace = netlink.NsFd(nsFd) |
| 144 | if mtu != 0 { |
| 145 | linkAttrs.MTU = mtu |
| 146 | } |
| 147 | mv := &netlink.Tuntap{ |
| 148 | LinkAttrs: linkAttrs, |
| 149 | Mode: netlink.TUNTAP_MODE_TAP, |
| 150 | } |
| 151 | |
| 152 | if owner != nil { |
| 153 | mv.Owner = *owner |
| 154 | } |
| 155 | if group != nil { |
| 156 | mv.Group = *group |
| 157 | } |
| 158 | |
| 159 | if mac != "" { |
| 160 | addr, err := net.ParseMAC(mac) |
| 161 | if err != nil { |
| 162 | return fmt.Errorf("invalid args %v for MAC addr: %v", mac, err) |
| 163 | } |
| 164 | linkAttrs.HardwareAddr = addr |
| 165 | } |
| 166 | mv.Flags = netlink.TUNTAP_VNET_HDR | unix.IFF_TAP |
| 167 | if multiqueue { |
| 168 | mv.Flags = netlink.TUNTAP_MULTI_QUEUE_DEFAULTS | mv.Flags |
| 169 | } |
| 170 | if err := netlink.LinkAdd(mv); err != nil { |
| 171 | return fmt.Errorf("failed to create tap: %v", err) |
| 172 | } |
| 173 | return nil |
| 174 | } |
| 175 | |
| 176 | func createLink(tmpName string, conf *NetConf, netns ns.NetNS) error { |
| 177 | switch { |
| 178 | case conf.SelinuxContext != "": |
| 179 | if err := selinux.SetExecLabel(conf.SelinuxContext); err != nil { |
| 180 | return fmt.Errorf("failed set socket label: %v", err) |
| 181 | } |
| 182 | return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) |
| 183 | case conf.Owner == nil || conf.Group == nil: |
| 184 | return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) |
| 185 | default: |
| 186 | return createLinkWithNetlink(tmpName, conf.MTU, int(netns.Fd()), conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func createTap(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) { |
| 191 | tap := ¤t.Interface{} |
| 192 | // due to kernel bug we have to create with tmpName or it might |
| 193 | // collide with the name on the host and error out |
| 194 | tmpName, err := ip.RandomVethName() |
| 195 | if err != nil { |
| 196 | return nil, err |
| 197 | } |
| 198 | |
| 199 | err = netns.Do(func(_ ns.NetNS) error { |
| 200 | err := createLink(tmpName, conf, netns) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | |
| 205 | if err = ip.RenameLink(tmpName, ifName); err != nil { |
| 206 | link, err := netlinksafe.LinkByName(tmpName) |
| 207 | if err != nil { |
| 208 | netlink.LinkDel(link) |
| 209 | return fmt.Errorf("failed to rename tap to %q: %v", ifName, err) |
| 210 | } |
| 211 | } |
| 212 | tap.Name = ifName |
| 213 | |
| 214 | // Re-fetch link to get all properties/attributes |
| 215 | link, err := netlinksafe.LinkByName(ifName) |
| 216 | if err != nil { |
| 217 | return fmt.Errorf("failed to refetch tap %q: %v", ifName, err) |
| 218 | } |
| 219 | |
| 220 | if conf.Bridge != "" { |
| 221 | bridge, err := netlinksafe.LinkByName(conf.Bridge) |
| 222 | if err != nil { |
| 223 | return fmt.Errorf("failed to get bridge %s: %v", conf.Bridge, err) |
| 224 | } |
| 225 | |
| 226 | tapDev := link |
| 227 | if err := netlink.LinkSetMaster(tapDev, bridge); err != nil { |
| 228 | return fmt.Errorf("failed to set tap %s as a port of bridge %s: %v", tap.Name, conf.Bridge, err) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | err = netlink.LinkSetUp(link) |
| 233 | if err != nil { |
| 234 | return fmt.Errorf("failed to set tap interface up: %v", err) |
| 235 | } |
| 236 | |
| 237 | tap.Mac = link.Attrs().HardwareAddr.String() |
| 238 | tap.Sandbox = netns.Path() |
| 239 | |
| 240 | return nil |
| 241 | }) |
| 242 | if err != nil { |
| 243 | return nil, err |
| 244 | } |
| 245 | |
| 246 | return tap, nil |
| 247 | } |
| 248 | |
| 249 | func cmdAdd(args *skel.CmdArgs) error { |
| 250 | n, cniVersion, err := loadConf(args) |
| 251 | if err != nil { |
| 252 | return err |
| 253 | } |
| 254 | |
| 255 | isLayer3 := n.IPAM.Type != "" |
| 256 | |
| 257 | netns, err := ns.GetNS(args.Netns) |
| 258 | if err != nil { |
| 259 | return fmt.Errorf("failed to open netns %q: %v", netns, err) |
| 260 | } |
| 261 | defer netns.Close() |
| 262 | |
| 263 | tapInterface, err := createTap(n, args.IfName, netns) |
| 264 | if err != nil { |
| 265 | return err |
| 266 | } |
| 267 | |
| 268 | // Delete link if err to avoid link leak in this ns |
| 269 | defer func() { |
| 270 | if err != nil { |
| 271 | netns.Do(func(_ ns.NetNS) error { |
| 272 | return ip.DelLinkByName(args.IfName) |
| 273 | }) |
| 274 | } |
| 275 | }() |
| 276 | |
| 277 | // Assume L2 interface only |
| 278 | result := ¤t.Result{ |
| 279 | CNIVersion: current.ImplementedSpecVersion, |
| 280 | Interfaces: []*current.Interface{tapInterface}, |
| 281 | } |
| 282 | |
| 283 | if isLayer3 { |
| 284 | // run the IPAM plugin and get back the config to apply |
| 285 | r, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData) |
| 286 | if err != nil { |
| 287 | return err |
| 288 | } |
| 289 | |
| 290 | // Invoke ipam del if err to avoid ip leak |
| 291 | defer func() { |
| 292 | if err != nil { |
| 293 | ipam.ExecDel(n.IPAM.Type, args.StdinData) |
| 294 | } |
| 295 | }() |
| 296 | |
| 297 | // Convert whatever the IPAM result was into the current Result type |
| 298 | ipamResult, err := current.NewResultFromResult(r) |
| 299 | if err != nil { |
| 300 | return err |
| 301 | } |
| 302 | |
| 303 | if len(ipamResult.IPs) == 0 { |
| 304 | return errors.New("IPAM plugin returned missing IP config") |
| 305 | } |
| 306 | |
| 307 | result.IPs = ipamResult.IPs |
| 308 | result.Routes = ipamResult.Routes |
| 309 | |
| 310 | for _, ipc := range result.IPs { |
| 311 | // All addresses apply to the container tap interface |
| 312 | ipc.Interface = current.Int(0) |
| 313 | } |
| 314 | |
| 315 | err = netns.Do(func(_ ns.NetNS) error { |
| 316 | _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv4/conf/%s/arp_notify", args.IfName), "1") |
| 317 | |
| 318 | return ipam.ConfigureIface(args.IfName, result) |
| 319 | }) |
| 320 | if err != nil { |
| 321 | return err |
| 322 | } |
| 323 | } else { |
| 324 | // For L2 just change interface status to up |
| 325 | err = netns.Do(func(_ ns.NetNS) error { |
| 326 | tapInterfaceLink, err := netlinksafe.LinkByName(args.IfName) |
| 327 | if err != nil { |
| 328 | return fmt.Errorf("failed to find interface name %q: %v", tapInterface.Name, err) |
| 329 | } |
| 330 | if err := netlink.LinkSetUp(tapInterfaceLink); err != nil { |
| 331 | return fmt.Errorf("failed to set %q UP: %v", args.IfName, err) |
| 332 | } |
| 333 | |
| 334 | return nil |
| 335 | }) |
| 336 | if err != nil { |
| 337 | return err |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | result.DNS = n.DNS |
| 342 | return types.PrintResult(result, cniVersion) |
| 343 | } |
| 344 | |
| 345 | func cmdDel(args *skel.CmdArgs) error { |
| 346 | n, _, err := loadConf(args) |
| 347 | if err != nil { |
| 348 | return err |
| 349 | } |
| 350 | |
| 351 | isLayer3 := n.IPAM.Type != "" |
| 352 | |
| 353 | if isLayer3 { |
| 354 | err = ipam.ExecDel(n.IPAM.Type, args.StdinData) |
| 355 | if err != nil { |
| 356 | return err |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | if args.Netns == "" { |
| 361 | return nil |
| 362 | } |
| 363 | |
| 364 | // There is a netns so try to clean up. Delete can be called multiple times |
| 365 | // so don't return an error if the device is already removed. |
| 366 | err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { |
| 367 | if err := ip.DelLinkByName(args.IfName); err != nil { |
| 368 | if err != ip.ErrLinkNotFound { |
| 369 | return err |
| 370 | } |
| 371 | } |
| 372 | return nil |
| 373 | }) |
| 374 | if err != nil { |
| 375 | // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times |
| 376 | // so don't return an error if the device is already removed. |
| 377 | // https://github.com/kubernetes/kubernetes/issues/43014#issuecomment-287164444 |
| 378 | _, ok := err.(ns.NSPathNotExistErr) |
| 379 | if ok { |
| 380 | return nil |
| 381 | } |
| 382 | return err |
| 383 | } |
| 384 | |
| 385 | return err |
| 386 | } |
| 387 | |
| 388 | func main() { |
| 389 | skel.PluginMainFuncs(skel.CNIFuncs{ |
| 390 | Add: cmdAdd, |
| 391 | Check: cmdCheck, |
| 392 | Del: cmdDel, |
| 393 | Status: cmdStatus, |
| 394 | /* FIXME GC */ |
| 395 | }, version.All, bv.BuildString("tap")) |
| 396 | } |
| 397 | |
| 398 | func cmdCheck(args *skel.CmdArgs) error { |
| 399 | n, _, err := loadConf(args) |
| 400 | if err != nil { |
| 401 | return err |
| 402 | } |
| 403 | isLayer3 := n.IPAM.Type != "" |
| 404 | |
| 405 | netns, err := ns.GetNS(args.Netns) |
| 406 | if err != nil { |
| 407 | return fmt.Errorf("failed to open netns %q: %v", args.Netns, err) |
| 408 | } |
| 409 | defer netns.Close() |
| 410 | |
| 411 | if isLayer3 { |
| 412 | // run the IPAM plugin and get back the config to apply |
| 413 | err = ipam.ExecCheck(n.IPAM.Type, args.StdinData) |
| 414 | if err != nil { |
| 415 | return err |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // Parse previous result. |
| 420 | if n.NetConf.RawPrevResult == nil { |
| 421 | return fmt.Errorf("Required prevResult missing") |
| 422 | } |
| 423 | |
| 424 | if err := version.ParsePrevResult(&n.NetConf); err != nil { |
| 425 | return err |
| 426 | } |
| 427 | |
| 428 | result, err := current.NewResultFromResult(n.PrevResult) |
| 429 | if err != nil { |
| 430 | return err |
| 431 | } |
| 432 | |
| 433 | var contMap current.Interface |
| 434 | // Find interfaces for names whe know, tap device name inside container |
| 435 | for _, intf := range result.Interfaces { |
| 436 | if args.IfName == intf.Name { |
| 437 | if args.Netns == intf.Sandbox { |
| 438 | contMap = *intf |
| 439 | continue |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // The namespace must be the same as what was configured |
| 445 | if args.Netns != contMap.Sandbox { |
| 446 | return fmt.Errorf("Sandbox in prevResult %s doesn't match configured netns: %s", |
| 447 | contMap.Sandbox, args.Netns) |
| 448 | } |
| 449 | |
| 450 | // Check prevResults for ips, routes and dns against values found in the container |
| 451 | return netns.Do(func(_ ns.NetNS) error { |
| 452 | err = ip.ValidateExpectedInterfaceIPs(args.IfName, result.IPs) |
| 453 | if err != nil { |
| 454 | return err |
| 455 | } |
| 456 | |
| 457 | err = ip.ValidateExpectedRoute(result.Routes) |
| 458 | if err != nil { |
| 459 | return err |
| 460 | } |
| 461 | return nil |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | func cmdStatus(args *skel.CmdArgs) error { |
| 466 | conf := NetConf{} |
| 467 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 468 | return fmt.Errorf("failed to load netconf: %w", err) |
| 469 | } |
| 470 | |
| 471 | if conf.IPAM.Type != "" { |
| 472 | if err := ipam.ExecStatus(conf.IPAM.Type, args.StdinData); err != nil { |
| 473 | return err |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | return nil |
| 478 | } |