| 1 | // Copyright 2015 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" |
| 23 | "runtime" |
| 24 | |
| 25 | "github.com/vishvananda/netlink" |
| 26 | |
| 27 | "github.com/containernetworking/cni/pkg/skel" |
| 28 | "github.com/containernetworking/cni/pkg/types" |
| 29 | current "github.com/containernetworking/cni/pkg/types/100" |
| 30 | "github.com/containernetworking/cni/pkg/version" |
| 31 | "github.com/containernetworking/plugins/pkg/ip" |
| 32 | "github.com/containernetworking/plugins/pkg/ipam" |
| 33 | "github.com/containernetworking/plugins/pkg/netlinksafe" |
| 34 | "github.com/containernetworking/plugins/pkg/ns" |
| 35 | bv "github.com/containernetworking/plugins/pkg/utils/buildversion" |
| 36 | ) |
| 37 | |
| 38 | func init() { |
| 39 | // this ensures that main runs only on main thread (thread group leader). |
| 40 | // since namespace ops (unshare, setns) are done for a single thread, we |
| 41 | // must ensure that the goroutine does not jump from OS thread to thread |
| 42 | runtime.LockOSThread() |
| 43 | } |
| 44 | |
| 45 | type NetConf struct { |
| 46 | types.NetConf |
| 47 | IPMasq bool `json:"ipMasq"` |
| 48 | IPMasqBackend *string `json:"ipMasqBackend,omitempty"` |
| 49 | MTU int `json:"mtu"` |
| 50 | } |
| 51 | |
| 52 | func setupContainerVeth(netns ns.NetNS, ifName string, mtu int, pr *current.Result) (*current.Interface, *current.Interface, error) { |
| 53 | // The IPAM result will be something like IP=192.168.3.5/24, GW=192.168.3.1. |
| 54 | // What we want is really a point-to-point link but veth does not support IFF_POINTTOPOINT. |
| 55 | // Next best thing would be to let it ARP but set interface to 192.168.3.5/32 and |
| 56 | // add a route like "192.168.3.0/24 via 192.168.3.1 dev $ifName". |
| 57 | // Unfortunately that won't work as the GW will be outside the interface's subnet. |
| 58 | |
| 59 | // Our solution is to configure the interface with 192.168.3.5/24, then delete the |
| 60 | // "192.168.3.0/24 dev $ifName" route that was automatically added. Then we add |
| 61 | // "192.168.3.1/32 dev $ifName" and "192.168.3.0/24 via 192.168.3.1 dev $ifName". |
| 62 | // In other words we force all traffic to ARP via the gateway except for GW itself. |
| 63 | |
| 64 | hostInterface := ¤t.Interface{} |
| 65 | containerInterface := ¤t.Interface{} |
| 66 | |
| 67 | err := netns.Do(func(hostNS ns.NetNS) error { |
| 68 | hostVeth, contVeth0, err := ip.SetupVeth(ifName, mtu, "", hostNS) |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | hostInterface.Name = hostVeth.Name |
| 73 | hostInterface.Mac = hostVeth.HardwareAddr.String() |
| 74 | containerInterface.Name = contVeth0.Name |
| 75 | containerInterface.Mac = contVeth0.HardwareAddr.String() |
| 76 | containerInterface.Sandbox = netns.Path() |
| 77 | |
| 78 | for _, ipc := range pr.IPs { |
| 79 | // All addresses apply to the container veth interface |
| 80 | ipc.Interface = current.Int(1) |
| 81 | } |
| 82 | |
| 83 | pr.Interfaces = []*current.Interface{hostInterface, containerInterface} |
| 84 | |
| 85 | contVeth, err := net.InterfaceByName(ifName) |
| 86 | if err != nil { |
| 87 | return fmt.Errorf("failed to look up %q: %v", ifName, err) |
| 88 | } |
| 89 | |
| 90 | if err = ipam.ConfigureIface(ifName, pr); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | for _, ipc := range pr.IPs { |
| 95 | // Delete the route that was automatically added |
| 96 | route := netlink.Route{ |
| 97 | LinkIndex: contVeth.Index, |
| 98 | Dst: &net.IPNet{ |
| 99 | IP: ipc.Address.IP.Mask(ipc.Address.Mask), |
| 100 | Mask: ipc.Address.Mask, |
| 101 | }, |
| 102 | Scope: netlink.SCOPE_NOWHERE, |
| 103 | } |
| 104 | |
| 105 | if err := netlink.RouteDel(&route); err != nil { |
| 106 | return fmt.Errorf("failed to delete route %v: %v", route, err) |
| 107 | } |
| 108 | |
| 109 | addrBits := 32 |
| 110 | if ipc.Address.IP.To4() == nil { |
| 111 | addrBits = 128 |
| 112 | } |
| 113 | |
| 114 | for _, r := range []netlink.Route{ |
| 115 | { |
| 116 | LinkIndex: contVeth.Index, |
| 117 | Dst: &net.IPNet{ |
| 118 | IP: ipc.Gateway, |
| 119 | Mask: net.CIDRMask(addrBits, addrBits), |
| 120 | }, |
| 121 | Scope: netlink.SCOPE_LINK, |
| 122 | Src: ipc.Address.IP, |
| 123 | }, |
| 124 | { |
| 125 | LinkIndex: contVeth.Index, |
| 126 | Dst: &net.IPNet{ |
| 127 | IP: ipc.Address.IP.Mask(ipc.Address.Mask), |
| 128 | Mask: ipc.Address.Mask, |
| 129 | }, |
| 130 | Scope: netlink.SCOPE_UNIVERSE, |
| 131 | Gw: ipc.Gateway, |
| 132 | Src: ipc.Address.IP, |
| 133 | }, |
| 134 | } { |
| 135 | if err := netlink.RouteAdd(&r); err != nil { |
| 136 | return fmt.Errorf("failed to add route %v: %v", r, err) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | return nil |
| 142 | }) |
| 143 | if err != nil { |
| 144 | return nil, nil, err |
| 145 | } |
| 146 | return hostInterface, containerInterface, nil |
| 147 | } |
| 148 | |
| 149 | func setupHostVeth(vethName string, result *current.Result) error { |
| 150 | // hostVeth moved namespaces and may have a new ifindex |
| 151 | veth, err := netlinksafe.LinkByName(vethName) |
| 152 | if err != nil { |
| 153 | return fmt.Errorf("failed to lookup %q: %v", vethName, err) |
| 154 | } |
| 155 | |
| 156 | for _, ipc := range result.IPs { |
| 157 | maskLen := 128 |
| 158 | if ipc.Address.IP.To4() != nil { |
| 159 | maskLen = 32 |
| 160 | } |
| 161 | |
| 162 | ipn := &net.IPNet{ |
| 163 | IP: ipc.Gateway, |
| 164 | Mask: net.CIDRMask(maskLen, maskLen), |
| 165 | } |
| 166 | addr := &netlink.Addr{IPNet: ipn, Label: ""} |
| 167 | if err = netlink.AddrAdd(veth, addr); err != nil { |
| 168 | return fmt.Errorf("failed to add IP addr (%#v) to veth: %v", ipn, err) |
| 169 | } |
| 170 | |
| 171 | ipn = &net.IPNet{ |
| 172 | IP: ipc.Address.IP, |
| 173 | Mask: net.CIDRMask(maskLen, maskLen), |
| 174 | } |
| 175 | // dst happens to be the same as IP/net of host veth |
| 176 | if err = ip.AddHostRoute(ipn, nil, veth); err != nil && !os.IsExist(err) { |
| 177 | return fmt.Errorf("failed to add route on host: %v", err) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | return nil |
| 182 | } |
| 183 | |
| 184 | func cmdAdd(args *skel.CmdArgs) error { |
| 185 | conf := NetConf{} |
| 186 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 187 | return fmt.Errorf("failed to load netconf: %v", err) |
| 188 | } |
| 189 | |
| 190 | // run the IPAM plugin and get back the config to apply |
| 191 | r, err := ipam.ExecAdd(conf.IPAM.Type, args.StdinData) |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | |
| 196 | // Invoke ipam del if err to avoid ip leak |
| 197 | defer func() { |
| 198 | if err != nil { |
| 199 | ipam.ExecDel(conf.IPAM.Type, args.StdinData) |
| 200 | } |
| 201 | }() |
| 202 | |
| 203 | // Convert whatever the IPAM result was into the current Result type |
| 204 | result, err := current.NewResultFromResult(r) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | |
| 209 | if len(result.IPs) == 0 { |
| 210 | return errors.New("IPAM plugin returned missing IP config") |
| 211 | } |
| 212 | |
| 213 | if err := ip.EnableForward(result.IPs); err != nil { |
| 214 | return fmt.Errorf("Could not enable IP forwarding: %v", err) |
| 215 | } |
| 216 | |
| 217 | netns, err := ns.GetNS(args.Netns) |
| 218 | if err != nil { |
| 219 | return fmt.Errorf("failed to open netns %q: %v", args.Netns, err) |
| 220 | } |
| 221 | defer netns.Close() |
| 222 | |
| 223 | hostInterface, _, err := setupContainerVeth(netns, args.IfName, conf.MTU, result) |
| 224 | if err != nil { |
| 225 | return err |
| 226 | } |
| 227 | |
| 228 | if err = setupHostVeth(hostInterface.Name, result); err != nil { |
| 229 | return err |
| 230 | } |
| 231 | |
| 232 | if conf.IPMasq { |
| 233 | ipns := []*net.IPNet{} |
| 234 | for _, ipc := range result.IPs { |
| 235 | ipns = append(ipns, &ipc.Address) |
| 236 | } |
| 237 | if err = ip.SetupIPMasqForNetworks(conf.IPMasqBackend, ipns, conf.Name, args.IfName, args.ContainerID); err != nil { |
| 238 | return err |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // Only override the DNS settings in the previous result if any DNS fields |
| 243 | // were provided to the ptp plugin. This allows, for example, IPAM plugins |
| 244 | // to specify the DNS settings instead of the ptp plugin. |
| 245 | if dnsConfSet(conf.DNS) { |
| 246 | result.DNS = conf.DNS |
| 247 | } |
| 248 | |
| 249 | return types.PrintResult(result, conf.CNIVersion) |
| 250 | } |
| 251 | |
| 252 | func dnsConfSet(dnsConf types.DNS) bool { |
| 253 | return dnsConf.Nameservers != nil || |
| 254 | dnsConf.Search != nil || |
| 255 | dnsConf.Options != nil || |
| 256 | dnsConf.Domain != "" |
| 257 | } |
| 258 | |
| 259 | func cmdDel(args *skel.CmdArgs) error { |
| 260 | conf := NetConf{} |
| 261 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 262 | return fmt.Errorf("failed to load netconf: %v", err) |
| 263 | } |
| 264 | |
| 265 | if err := ipam.ExecDel(conf.IPAM.Type, args.StdinData); err != nil { |
| 266 | return err |
| 267 | } |
| 268 | |
| 269 | if args.Netns == "" { |
| 270 | return nil |
| 271 | } |
| 272 | |
| 273 | // There is a netns so try to clean up. Delete can be called multiple times |
| 274 | // so don't return an error if the device is already removed. |
| 275 | // If the device isn't there then don't try to clean up IP masq either. |
| 276 | var ipnets []*net.IPNet |
| 277 | err := ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { |
| 278 | var err error |
| 279 | ipnets, err = ip.DelLinkByNameAddr(args.IfName) |
| 280 | if err != nil && err == ip.ErrLinkNotFound { |
| 281 | return nil |
| 282 | } |
| 283 | return err |
| 284 | }) |
| 285 | if err != nil { |
| 286 | // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times |
| 287 | // so don't return an error if the device is already removed. |
| 288 | // https://github.com/kubernetes/kubernetes/issues/43014#issuecomment-287164444 |
| 289 | _, ok := err.(ns.NSPathNotExistErr) |
| 290 | if ok { |
| 291 | return nil |
| 292 | } |
| 293 | return err |
| 294 | } |
| 295 | |
| 296 | if len(ipnets) != 0 && conf.IPMasq { |
| 297 | if err := ip.TeardownIPMasqForNetworks(ipnets, conf.Name, args.IfName, args.ContainerID); err != nil { |
| 298 | return err |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | return err |
| 303 | } |
| 304 | |
| 305 | func main() { |
| 306 | skel.PluginMainFuncs(skel.CNIFuncs{ |
| 307 | Add: cmdAdd, |
| 308 | Check: cmdCheck, |
| 309 | Del: cmdDel, |
| 310 | Status: cmdStatus, |
| 311 | /* FIXME GC */ |
| 312 | }, version.All, bv.BuildString("ptp")) |
| 313 | } |
| 314 | |
| 315 | func cmdCheck(args *skel.CmdArgs) error { |
| 316 | conf := NetConf{} |
| 317 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 318 | return fmt.Errorf("failed to load netconf: %v", err) |
| 319 | } |
| 320 | |
| 321 | netns, err := ns.GetNS(args.Netns) |
| 322 | if err != nil { |
| 323 | return fmt.Errorf("failed to open netns %q: %v", args.Netns, err) |
| 324 | } |
| 325 | defer netns.Close() |
| 326 | |
| 327 | // run the IPAM plugin and get back the config to apply |
| 328 | err = ipam.ExecCheck(conf.IPAM.Type, args.StdinData) |
| 329 | if err != nil { |
| 330 | return err |
| 331 | } |
| 332 | if conf.NetConf.RawPrevResult == nil { |
| 333 | return fmt.Errorf("ptp: Required prevResult missing") |
| 334 | } |
| 335 | if err := version.ParsePrevResult(&conf.NetConf); err != nil { |
| 336 | return err |
| 337 | } |
| 338 | // Convert whatever the IPAM result was into the current Result type |
| 339 | result, err := current.NewResultFromResult(conf.PrevResult) |
| 340 | if err != nil { |
| 341 | return err |
| 342 | } |
| 343 | |
| 344 | var contMap current.Interface |
| 345 | // Find interfaces for name whe know, that of host-device inside container |
| 346 | for _, intf := range result.Interfaces { |
| 347 | if args.IfName == intf.Name { |
| 348 | if args.Netns == intf.Sandbox { |
| 349 | contMap = *intf |
| 350 | continue |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // The namespace must be the same as what was configured |
| 356 | if args.Netns != contMap.Sandbox { |
| 357 | return fmt.Errorf("Sandbox in prevResult %s doesn't match configured netns: %s", |
| 358 | contMap.Sandbox, args.Netns) |
| 359 | } |
| 360 | |
| 361 | // |
| 362 | // Check prevResults for ips, routes and dns against values found in the container |
| 363 | if err := netns.Do(func(_ ns.NetNS) error { |
| 364 | // Check interface against values found in the container |
| 365 | err := validateCniContainerInterface(contMap) |
| 366 | if err != nil { |
| 367 | return err |
| 368 | } |
| 369 | |
| 370 | err = ip.ValidateExpectedInterfaceIPs(args.IfName, result.IPs) |
| 371 | if err != nil { |
| 372 | return err |
| 373 | } |
| 374 | |
| 375 | err = ip.ValidateExpectedRoute(result.Routes) |
| 376 | if err != nil { |
| 377 | return err |
| 378 | } |
| 379 | return nil |
| 380 | }); err != nil { |
| 381 | return err |
| 382 | } |
| 383 | |
| 384 | return nil |
| 385 | } |
| 386 | |
| 387 | func validateCniContainerInterface(intf current.Interface) error { |
| 388 | var link netlink.Link |
| 389 | var err error |
| 390 | |
| 391 | if intf.Name == "" { |
| 392 | return fmt.Errorf("Container interface name missing in prevResult: %v", intf.Name) |
| 393 | } |
| 394 | link, err = netlinksafe.LinkByName(intf.Name) |
| 395 | if err != nil { |
| 396 | return fmt.Errorf("ptp: Container Interface name in prevResult: %s not found", intf.Name) |
| 397 | } |
| 398 | if intf.Sandbox == "" { |
| 399 | return fmt.Errorf("ptp: Error: Container interface %s should not be in host namespace", link.Attrs().Name) |
| 400 | } |
| 401 | |
| 402 | _, isVeth := link.(*netlink.Veth) |
| 403 | if !isVeth { |
| 404 | return fmt.Errorf("Error: Container interface %s not of type veth/p2p", link.Attrs().Name) |
| 405 | } |
| 406 | |
| 407 | if intf.Mac != "" { |
| 408 | if intf.Mac != link.Attrs().HardwareAddr.String() { |
| 409 | return fmt.Errorf("ptp: Interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr) |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | return nil |
| 414 | } |
| 415 | |
| 416 | func cmdStatus(args *skel.CmdArgs) error { |
| 417 | conf := NetConf{} |
| 418 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 419 | return fmt.Errorf("failed to load netconf: %w", err) |
| 420 | } |
| 421 | |
| 422 | if err := ipam.ExecStatus(conf.IPAM.Type, args.StdinData); err != nil { |
| 423 | return err |
| 424 | } |
| 425 | |
| 426 | return nil |
| 427 | } |