Debian Codegraph @

plugins/main/bridge/bridge.go

raw symbols SCIP
1 // Copyright 2014 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 "sort"
25 "syscall"
26 "time"
27
28 "github.com/vishvananda/netlink"
29
30 "github.com/containernetworking/cni/pkg/skel"
31 "github.com/containernetworking/cni/pkg/types"
32 current "github.com/containernetworking/cni/pkg/types/100"
33 "github.com/containernetworking/cni/pkg/version"
34 "github.com/containernetworking/plugins/pkg/ip"
35 "github.com/containernetworking/plugins/pkg/ipam"
36 "github.com/containernetworking/plugins/pkg/link"
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 // For testcases to force an error after IPAM has been performed
44 var debugPostIPAMError error
45
46 const defaultBrName = "cni0"
47
48 type NetConf struct {
49 types.NetConf
50 BrName string `json:"bridge"`
51 IsGW bool `json:"isGateway"`
52 IsDefaultGW bool `json:"isDefaultGateway"`
53 ForceAddress bool `json:"forceAddress"`
54 IPMasq bool `json:"ipMasq"`
55 IPMasqBackend *string `json:"ipMasqBackend,omitempty"`
56 MTU int `json:"mtu"`
57 HairpinMode bool `json:"hairpinMode"`
58 PromiscMode bool `json:"promiscMode"`
59 Vlan int `json:"vlan"`
60 VlanTrunk []*VlanTrunk `json:"vlanTrunk,omitempty"`
61 PreserveDefaultVlan bool `json:"preserveDefaultVlan"`
62 MacSpoofChk bool `json:"macspoofchk,omitempty"`
63 EnableDad bool `json:"enabledad,omitempty"`
64 DisableContainerInterface bool `json:"disableContainerInterface,omitempty"`
65 PortIsolation bool `json:"portIsolation,omitempty"`
66
67 Args struct {
68 Cni BridgeArgs `json:"cni,omitempty"`
69 } `json:"args,omitempty"`
70 RuntimeConfig struct {
71 Mac string `json:"mac,omitempty"`
72 } `json:"runtimeConfig,omitempty"`
73
74 mac string
75 vlans []int
76 }
77
78 type VlanTrunk struct {
79 MinID *int `json:"minID,omitempty"`
80 MaxID *int `json:"maxID,omitempty"`
81 ID *int `json:"id,omitempty"`
82 }
83
84 type BridgeArgs struct {
85 Mac string `json:"mac,omitempty"`
86 }
87
88 // MacEnvArgs represents CNI_ARGS
89 type MacEnvArgs struct {
90 types.CommonArgs
91 MAC types.UnmarshallableString `json:"mac,omitempty"`
92 }
93
94 type gwInfo struct {
95 gws []net.IPNet
96 family int
97 defaultRouteFound bool
98 }
99
100 func init() {
101 // this ensures that main runs only on main thread (thread group leader).
102 // since namespace ops (unshare, setns) are done for a single thread, we
103 // must ensure that the goroutine does not jump from OS thread to thread
104 runtime.LockOSThread()
105 }
106
107 func loadNetConf(bytes []byte, envArgs string) (*NetConf, string, error) {
108 n := &NetConf{
109 BrName: defaultBrName,
110 }
111 if err := json.Unmarshal(bytes, n); err != nil {
112 return nil, "", fmt.Errorf("failed to load netconf: %v", err)
113 }
114 if n.Vlan < 0 || n.Vlan > 4094 {
115 return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4094)", n.Vlan)
116 }
117 var err error
118 n.vlans, err = collectVlanTrunk(n.VlanTrunk)
119 if err != nil {
120 // fail to parsing
121 return nil, "", err
122 }
123
124 if envArgs != "" {
125 e := MacEnvArgs{}
126 if err := types.LoadArgs(envArgs, &e); err != nil {
127 return nil, "", err
128 }
129
130 if e.MAC != "" {
131 n.mac = string(e.MAC)
132 }
133 }
134
135 if mac := n.Args.Cni.Mac; mac != "" {
136 n.mac = mac
137 }
138
139 if mac := n.RuntimeConfig.Mac; mac != "" {
140 n.mac = mac
141 }
142
143 return n, n.CNIVersion, nil
144 }
145
146 // This method is copied from https://github.com/k8snetworkplumbingwg/ovs-cni/blob/v0.27.2/pkg/plugin/plugin.go
147 func collectVlanTrunk(vlanTrunk []*VlanTrunk) ([]int, error) {
148 if vlanTrunk == nil {
149 return nil, nil
150 }
151
152 vlanMap := make(map[int]struct{})
153 for _, item := range vlanTrunk {
154 var minID int
155 var maxID int
156 var ID int
157
158 switch {
159 case item.MinID != nil && item.MaxID != nil:
160 minID = *item.MinID
161 if minID <= 0 || minID > 4094 {
162 return nil, errors.New("incorrect trunk minID parameter")
163 }
164 maxID = *item.MaxID
165 if maxID <= 0 || maxID > 4094 {
166 return nil, errors.New("incorrect trunk maxID parameter")
167 }
168 if maxID < minID {
169 return nil, errors.New("minID is greater than maxID in trunk parameter")
170 }
171 for v := minID; v <= maxID; v++ {
172 vlanMap[v] = struct{}{}
173 }
174 case item.MinID == nil && item.MaxID != nil:
175 return nil, errors.New("minID and maxID should be configured simultaneously, minID is missing")
176 case item.MinID != nil && item.MaxID == nil:
177 return nil, errors.New("minID and maxID should be configured simultaneously, maxID is missing")
178 }
179
180 // single vid
181 if item.ID != nil {
182 ID = *item.ID
183 if ID <= 0 || ID > 4094 {
184 return nil, errors.New("incorrect trunk id parameter")
185 }
186 vlanMap[ID] = struct{}{}
187 }
188 }
189
190 if len(vlanMap) == 0 {
191 return nil, nil
192 }
193 vlans := make([]int, 0, len(vlanMap))
194 for k := range vlanMap {
195 vlans = append(vlans, k)
196 }
197 sort.Slice(vlans, func(i int, j int) bool { return vlans[i] < vlans[j] })
198 return vlans, nil
199 }
200
201 // calcGateways processes the results from the IPAM plugin and does the
202 // following for each IP family:
203 // - Calculates and compiles a list of gateway addresses
204 // - Adds a default route if needed
205 func calcGateways(result *current.Result, n *NetConf) (*gwInfo, *gwInfo, error) {
206 gwsV4 := &gwInfo{}
207 gwsV6 := &gwInfo{}
208
209 for _, ipc := range result.IPs {
210
211 // Determine if this config is IPv4 or IPv6
212 var gws *gwInfo
213 defaultNet := &net.IPNet{}
214 switch {
215 case ipc.Address.IP.To4() != nil:
216 gws = gwsV4
217 gws.family = netlink.FAMILY_V4
218 defaultNet.IP = net.IPv4zero
219 case len(ipc.Address.IP) == net.IPv6len:
220 gws = gwsV6
221 gws.family = netlink.FAMILY_V6
222 defaultNet.IP = net.IPv6zero
223 default:
224 return nil, nil, fmt.Errorf("Unknown IP object: %v", ipc)
225 }
226 defaultNet.Mask = net.IPMask(defaultNet.IP)
227
228 // All IPs currently refer to the container interface
229 ipc.Interface = current.Int(2)
230
231 // If not provided, calculate the gateway address corresponding
232 // to the selected IP address
233 if ipc.Gateway == nil && n.IsGW {
234 ipc.Gateway = calcGatewayIP(&ipc.Address)
235 }
236
237 // Add a default route for this family using the current
238 // gateway address if necessary.
239 if n.IsDefaultGW && !gws.defaultRouteFound {
240 for _, route := range result.Routes {
241 if route.GW != nil && defaultNet.String() == route.Dst.String() {
242 gws.defaultRouteFound = true
243 break
244 }
245 }
246 if !gws.defaultRouteFound {
247 result.Routes = append(
248 result.Routes,
249 &types.Route{Dst: *defaultNet, GW: ipc.Gateway},
250 )
251 gws.defaultRouteFound = true
252 }
253 }
254
255 // Append this gateway address to the list of gateways
256 if n.IsGW {
257 gw := net.IPNet{
258 IP: ipc.Gateway,
259 Mask: ipc.Address.Mask,
260 }
261 gws.gws = append(gws.gws, gw)
262 }
263 }
264 return gwsV4, gwsV6, nil
265 }
266
267 func ensureAddr(br netlink.Link, family int, ipn *net.IPNet, forceAddress bool) error {
268 addrs, err := netlinksafe.AddrList(br, family)
269 if err != nil && err != syscall.ENOENT {
270 return fmt.Errorf("could not get list of IP addresses: %v", err)
271 }
272
273 ipnStr := ipn.String()
274 for _, a := range addrs {
275
276 // string comp is actually easiest for doing IPNet comps
277 if a.IPNet.String() == ipnStr {
278 return nil
279 }
280
281 // Multiple IPv6 addresses are allowed on the bridge if the
282 // corresponding subnets do not overlap. For IPv4 or for
283 // overlapping IPv6 subnets, reconfigure the IP address if
284 // forceAddress is true, otherwise throw an error.
285 if family == netlink.FAMILY_V4 || a.IPNet.Contains(ipn.IP) || ipn.Contains(a.IPNet.IP) {
286 if forceAddress {
287 if err = deleteAddr(br, a.IPNet); err != nil {
288 return err
289 }
290 } else {
291 return fmt.Errorf("%q already has an IP address different from %v", br.Attrs().Name, ipnStr)
292 }
293 }
294 }
295
296 addr := &netlink.Addr{IPNet: ipn, Label: ""}
297 if err := netlink.AddrAdd(br, addr); err != nil && err != syscall.EEXIST {
298 return fmt.Errorf("could not add IP address %s to %q: %v", ipnStr, br.Attrs().Name, err)
299 }
300
301 // Set the bridge's MAC to itself. Otherwise, the bridge will take the
302 // lowest-numbered mac on the bridge, and will change as ifs churn
303 if err := netlink.LinkSetHardwareAddr(br, br.Attrs().HardwareAddr); err != nil {
304 return fmt.Errorf("could not set bridge's mac: %v", err)
305 }
306
307 return nil
308 }
309
310 func deleteAddr(br netlink.Link, ipn *net.IPNet) error {
311 addr := &netlink.Addr{IPNet: ipn, Label: ""}
312
313 if err := netlink.AddrDel(br, addr); err != nil {
314 return fmt.Errorf("could not remove IP address from %q: %v", br.Attrs().Name, err)
315 }
316
317 return nil
318 }
319
320 func bridgeByName(name string) (*netlink.Bridge, error) {
321 l, err := netlinksafe.LinkByName(name)
322 if err != nil {
323 return nil, fmt.Errorf("could not lookup %q: %v", name, err)
324 }
325 br, ok := l.(*netlink.Bridge)
326 if !ok {
327 return nil, fmt.Errorf("%q already exists but is not a bridge", name)
328 }
329 return br, nil
330 }
331
332 func ensureBridge(brName string, mtu int, promiscMode, vlanFiltering bool) (*netlink.Bridge, error) {
333 linkAttrs := netlink.NewLinkAttrs()
334 linkAttrs.Name = brName
335 linkAttrs.MTU = mtu
336 br := &netlink.Bridge{
337 LinkAttrs: linkAttrs,
338 }
339 if vlanFiltering {
340 br.VlanFiltering = &vlanFiltering
341 }
342
343 err := netlink.LinkAdd(br)
344 if err != nil && err != syscall.EEXIST {
345 return nil, fmt.Errorf("could not add %q: %v", brName, err)
346 }
347
348 if promiscMode {
349 if err := netlink.SetPromiscOn(br); err != nil {
350 return nil, fmt.Errorf("could not set promiscuous mode on %q: %v", brName, err)
351 }
352 }
353
354 // Re-fetch link to read all attributes and if it already existed,
355 // ensure it's really a bridge with similar configuration
356 br, err = bridgeByName(brName)
357 if err != nil {
358 return nil, err
359 }
360
361 // we want to own the routes for this interface
362 _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv6/conf/%s/accept_ra", brName), "0")
363
364 if err := netlink.LinkSetUp(br); err != nil {
365 return nil, err
366 }
367
368 return br, nil
369 }
370
371 func ensureVlanInterface(br *netlink.Bridge, vlanID int, preserveDefaultVlan bool) (netlink.Link, error) {
372 name := fmt.Sprintf("%s.%d", br.Name, vlanID)
373
374 brGatewayVeth, err := netlinksafe.LinkByName(name)
375 if err != nil {
376 if err.Error() != "Link not found" {
377 return nil, fmt.Errorf("failed to find interface %q: %v", name, err)
378 }
379
380 hostNS, err := ns.GetCurrentNS()
381 if err != nil {
382 return nil, fmt.Errorf("faild to find host namespace: %v", err)
383 }
384
385 _, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanID, nil, preserveDefaultVlan, "", false)
386 if err != nil {
387 return nil, fmt.Errorf("faild to create vlan gateway %q: %v", name, err)
388 }
389
390 brGatewayVeth, err = netlinksafe.LinkByName(brGatewayIface.Name)
391 if err != nil {
392 return nil, fmt.Errorf("failed to lookup %q: %v", brGatewayIface.Name, err)
393 }
394
395 err = netlink.LinkSetUp(brGatewayVeth)
396 if err != nil {
397 return nil, fmt.Errorf("failed to up %q: %v", brGatewayIface.Name, err)
398 }
399 }
400
401 return brGatewayVeth, nil
402 }
403
404 func setupVeth(
405 netns ns.NetNS,
406 br *netlink.Bridge,
407 ifName string,
408 mtu int,
409 hairpinMode bool,
410 vlanID int,
411 vlans []int,
412 preserveDefaultVlan bool,
413 mac string,
414 portIsolation bool,
415 ) (*current.Interface, *current.Interface, error) {
416 contIface := &current.Interface{}
417 hostIface := &current.Interface{}
418
419 err := netns.Do(func(hostNS ns.NetNS) error {
420 // create the veth pair in the container and move host end into host netns
421 hostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, mac, hostNS)
422 if err != nil {
423 return err
424 }
425 contIface.Name = containerVeth.Name
426 contIface.Mac = containerVeth.HardwareAddr.String()
427 contIface.Sandbox = netns.Path()
428 hostIface.Name = hostVeth.Name
429 return nil
430 })
431 if err != nil {
432 return nil, nil, err
433 }
434
435 // need to lookup hostVeth again as its index has changed during ns move
436 hostVeth, err := netlinksafe.LinkByName(hostIface.Name)
437 if err != nil {
438 return nil, nil, fmt.Errorf("failed to lookup %q: %v", hostIface.Name, err)
439 }
440 hostIface.Mac = hostVeth.Attrs().HardwareAddr.String()
441
442 // connect host veth end to the bridge
443 if err := netlink.LinkSetMaster(hostVeth, br); err != nil {
444 return nil, nil, fmt.Errorf("failed to connect %q to bridge %v: %v", hostVeth.Attrs().Name, br.Attrs().Name, err)
445 }
446
447 // set hairpin mode
448 if err = netlink.LinkSetHairpin(hostVeth, hairpinMode); err != nil {
449 return nil, nil, fmt.Errorf("failed to setup hairpin mode for %v: %v", hostVeth.Attrs().Name, err)
450 }
451
452 // set isolation mode
453 if err = netlink.LinkSetIsolated(hostVeth, portIsolation); err != nil {
454 return nil, nil, fmt.Errorf("failed to set isolated on for %v: %v", hostVeth.Attrs().Name, err)
455 }
456
457 if (vlanID != 0 || len(vlans) > 0) && !preserveDefaultVlan {
458 err = removeDefaultVlan(hostVeth)
459 if err != nil {
460 return nil, nil, fmt.Errorf("failed to remove default vlan on interface %q: %v", hostIface.Name, err)
461 }
462 }
463
464 if vlanID != 0 {
465 err = netlink.BridgeVlanAdd(hostVeth, uint16(vlanID), true, true, false, true)
466 if err != nil {
467 return nil, nil, fmt.Errorf("failed to setup vlan tag on interface %q: %v", hostIface.Name, err)
468 }
469 }
470
471 for _, v := range vlans {
472 err = netlink.BridgeVlanAdd(hostVeth, uint16(v), false, false, false, true)
473 if err != nil {
474 return nil, nil, fmt.Errorf("failed to setup vlan tag on interface %q: %w", hostIface.Name, err)
475 }
476 }
477
478 // Backwards compatibility with users that did not specify a vlanID
479 if vlanID == 0 && len(vlans) > 0 {
480 // If no vlan is specified, we set the native vlan on the trunk equal to 1
481 err = netlink.BridgeVlanAdd(hostVeth, 1, true, true, false, true)
482 if err != nil {
483 return nil, nil, fmt.Errorf("failed to setup default native vlan tag on interface %q: %v", hostIface.Name, err)
484 }
485 }
486
487 return hostIface, contIface, nil
488 }
489
490 func removeDefaultVlan(hostVeth netlink.Link) error {
491 vlanInfo, err := netlinksafe.BridgeVlanList()
492 if err != nil {
493 return err
494 }
495
496 brVlanInfo, ok := vlanInfo[int32(hostVeth.Attrs().Index)]
497 if ok {
498 for _, info := range brVlanInfo {
499 err = netlink.BridgeVlanDel(hostVeth, info.Vid, false, false, false, true)
500 if err != nil {
501 return err
502 }
503 }
504 }
505
506 return nil
507 }
508
509 func calcGatewayIP(ipn *net.IPNet) net.IP {
510 nid := ipn.IP.Mask(ipn.Mask)
511 return ip.NextIP(nid)
512 }
513
514 func setupBridge(n *NetConf) (*netlink.Bridge, *current.Interface, error) {
515 vlanFiltering := n.Vlan != 0 || n.VlanTrunk != nil
516 // create bridge if necessary
517 br, err := ensureBridge(n.BrName, n.MTU, n.PromiscMode, vlanFiltering)
518 if err != nil {
519 return nil, nil, fmt.Errorf("failed to create bridge %q: %v", n.BrName, err)
520 }
521
522 return br, &current.Interface{
523 Name: br.Attrs().Name,
524 Mac: br.Attrs().HardwareAddr.String(),
525 }, nil
526 }
527
528 func enableIPForward(family int) error {
529 if family == netlink.FAMILY_V4 {
530 return ip.EnableIP4Forward()
531 }
532 return ip.EnableIP6Forward()
533 }
534
535 func cmdAdd(args *skel.CmdArgs) error {
536 success := false
537
538 n, cniVersion, err := loadNetConf(args.StdinData, args.Args)
539 if err != nil {
540 return err
541 }
542
543 isLayer3 := n.IPAM.Type != ""
544
545 if isLayer3 && n.DisableContainerInterface {
546 return fmt.Errorf("cannot use IPAM when DisableContainerInterface flag is set")
547 }
548
549 if n.IsDefaultGW {
550 n.IsGW = true
551 }
552
553 if n.HairpinMode && n.PromiscMode {
554 return fmt.Errorf("cannot set hairpin mode and promiscuous mode at the same time")
555 }
556
557 br, brInterface, err := setupBridge(n)
558 if err != nil {
559 return err
560 }
561
562 netns, err := ns.GetNS(args.Netns)
563 if err != nil {
564 return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
565 }
566 defer netns.Close()
567
568 hostInterface, containerInterface, err := setupVeth(netns, br, args.IfName, n.MTU, n.HairpinMode, n.Vlan, n.vlans, n.PreserveDefaultVlan, n.mac, n.PortIsolation)
569 if err != nil {
570 return err
571 }
572
573 // Assume L2 interface only
574 result := &current.Result{
575 CNIVersion: current.ImplementedSpecVersion,
576 Interfaces: []*current.Interface{
577 brInterface,
578 hostInterface,
579 containerInterface,
580 },
581 }
582
583 if n.MacSpoofChk {
584 sc := link.NewSpoofChecker(hostInterface.Name, containerInterface.Mac, uniqueID(args.ContainerID, args.IfName))
585 if err := sc.Setup(); err != nil {
586 return err
587 }
588 defer func() {
589 if !success {
590 if err := sc.Teardown(); err != nil {
591 fmt.Fprintf(os.Stderr, "%v", err)
592 }
593 }
594 }()
595 }
596
597 if isLayer3 {
598 // run the IPAM plugin and get back the config to apply
599 r, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
600 if err != nil {
601 return err
602 }
603
604 // release IP in case of failure
605 defer func() {
606 if !success {
607 ipam.ExecDel(n.IPAM.Type, args.StdinData)
608 }
609 }()
610
611 // Convert whatever the IPAM result was into the current Result type
612 ipamResult, err := current.NewResultFromResult(r)
613 if err != nil {
614 return err
615 }
616
617 result.IPs = ipamResult.IPs
618 result.Routes = ipamResult.Routes
619 result.DNS = ipamResult.DNS
620
621 if len(result.IPs) == 0 {
622 return errors.New("IPAM plugin returned missing IP config")
623 }
624
625 // Gather gateway information for each IP family
626 gwsV4, gwsV6, err := calcGateways(result, n)
627 if err != nil {
628 return err
629 }
630
631 // Configure the container hardware address and IP address(es)
632 if err := netns.Do(func(_ ns.NetNS) error {
633 if n.EnableDad {
634 _, _ = sysctl.Sysctl(fmt.Sprintf("/net/ipv6/conf/%s/enhanced_dad", args.IfName), "1")
635 _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv6/conf/%s/accept_dad", args.IfName), "1")
636 } else {
637 _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv6/conf/%s/accept_dad", args.IfName), "0")
638 }
639 _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv4/conf/%s/arp_notify", args.IfName), "1")
640
641 // Add the IP to the interface
642 return ipam.ConfigureIface(args.IfName, result)
643 }); err != nil {
644 return err
645 }
646
647 if n.IsGW {
648 var vlanInterface *current.Interface
649 // Set the IP address(es) on the bridge and enable forwarding
650 for _, gws := range []*gwInfo{gwsV4, gwsV6} {
651 for _, gw := range gws.gws {
652 if n.Vlan != 0 {
653 vlanIface, err := ensureVlanInterface(br, n.Vlan, n.PreserveDefaultVlan)
654 if err != nil {
655 return fmt.Errorf("failed to create vlan interface: %v", err)
656 }
657
658 if vlanInterface == nil {
659 vlanInterface = &current.Interface{
660 Name: vlanIface.Attrs().Name,
661 Mac: vlanIface.Attrs().HardwareAddr.String(),
662 }
663 result.Interfaces = append(result.Interfaces, vlanInterface)
664 }
665
666 err = ensureAddr(vlanIface, gws.family, &gw, n.ForceAddress)
667 if err != nil {
668 return fmt.Errorf("failed to set vlan interface for bridge with addr: %v", err)
669 }
670 } else {
671 err = ensureAddr(br, gws.family, &gw, n.ForceAddress)
672 if err != nil {
673 return fmt.Errorf("failed to set bridge addr: %v", err)
674 }
675 }
676 }
677
678 if gws.gws != nil {
679 if err = enableIPForward(gws.family); err != nil {
680 return fmt.Errorf("failed to enable forwarding: %v", err)
681 }
682 }
683 }
684 }
685
686 if n.IPMasq {
687 ipns := []*net.IPNet{}
688 for _, ipc := range result.IPs {
689 ipns = append(ipns, &ipc.Address)
690 }
691 if err = ip.SetupIPMasqForNetworks(n.IPMasqBackend, ipns, n.Name, args.IfName, args.ContainerID); err != nil {
692 return err
693 }
694 }
695 } else if !n.DisableContainerInterface {
696 if err := netns.Do(func(_ ns.NetNS) error {
697 link, err := netlinksafe.LinkByName(args.IfName)
698 if err != nil {
699 return fmt.Errorf("failed to retrieve link: %v", err)
700 }
701
702 // If layer 2 we still need to set the container veth to up
703 if err = netlink.LinkSetUp(link); err != nil {
704 return fmt.Errorf("failed to set %q up: %v", args.IfName, err)
705 }
706 return nil
707 }); err != nil {
708 return err
709 }
710 }
711
712 hostVeth, err := netlinksafe.LinkByName(hostInterface.Name)
713 if err != nil {
714 return err
715 }
716
717 if !n.DisableContainerInterface {
718 // check bridge port state
719 retries := []int{0, 50, 500, 1000, 1000}
720 for idx, sleep := range retries {
721 time.Sleep(time.Duration(sleep) * time.Millisecond)
722
723 hostVeth, err = netlinksafe.LinkByName(hostInterface.Name)
724 if err != nil {
725 return err
726 }
727 if hostVeth.Attrs().OperState == netlink.OperUp {
728 break
729 }
730
731 if idx == len(retries)-1 {
732 return fmt.Errorf("bridge port in error state: %s", hostVeth.Attrs().OperState)
733 }
734 }
735 }
736
737 // In certain circumstances, the host-side of the veth may change addrs
738 hostInterface.Mac = hostVeth.Attrs().HardwareAddr.String()
739
740 // Refetch the bridge since its MAC address may change when the first
741 // veth is added or after its IP address is set
742 br, err = bridgeByName(n.BrName)
743 if err != nil {
744 return err
745 }
746 brInterface.Mac = br.Attrs().HardwareAddr.String()
747
748 // Return an error requested by testcases, if any
749 if debugPostIPAMError != nil {
750 return debugPostIPAMError
751 }
752
753 // Use incoming DNS settings if provided, otherwise use the
754 // settings that were already configured by the IPAM plugin
755 if dnsConfSet(n.DNS) {
756 result.DNS = n.DNS
757 }
758
759 success = true
760
761 return types.PrintResult(result, cniVersion)
762 }
763
764 func dnsConfSet(dnsConf types.DNS) bool {
765 return dnsConf.Nameservers != nil ||
766 dnsConf.Search != nil ||
767 dnsConf.Options != nil ||
768 dnsConf.Domain != ""
769 }
770
771 func cmdDel(args *skel.CmdArgs) error {
772 n, _, err := loadNetConf(args.StdinData, args.Args)
773 if err != nil {
774 return err
775 }
776
777 isLayer3 := n.IPAM.Type != ""
778
779 ipamDel := func() error {
780 if isLayer3 {
781 if err := ipam.ExecDel(n.IPAM.Type, args.StdinData); err != nil {
782 return err
783 }
784 }
785 return nil
786 }
787
788 if args.Netns == "" {
789 return ipamDel()
790 }
791
792 // There is a netns so try to clean up. Delete can be called multiple times
793 // so don't return an error if the device is already removed.
794 // If the device isn't there then don't try to clean up IP masq either.
795 var ipnets []*net.IPNet
796 err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
797 var err error
798 ipnets, err = ip.DelLinkByNameAddr(args.IfName)
799 if err != nil && err == ip.ErrLinkNotFound {
800 return nil
801 }
802 return err
803 })
804 if err != nil {
805 // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times
806 // so don't return an error if the device is already removed.
807 // https://github.com/kubernetes/kubernetes/issues/43014#issuecomment-287164444
808 _, ok := err.(ns.NSPathNotExistErr)
809 if ok {
810 return ipamDel()
811 }
812 return err
813 }
814
815 // call ipam.ExecDel after clean up device in netns
816 if err := ipamDel(); err != nil {
817 return err
818 }
819
820 if n.MacSpoofChk {
821 sc := link.NewSpoofChecker("", "", uniqueID(args.ContainerID, args.IfName))
822 if err := sc.Teardown(); err != nil {
823 fmt.Fprintf(os.Stderr, "%v", err)
824 }
825 }
826
827 if isLayer3 && n.IPMasq {
828 if err := ip.TeardownIPMasqForNetworks(ipnets, n.Name, args.IfName, args.ContainerID); err != nil {
829 return err
830 }
831 }
832
833 return err
834 }
835
836 func main() {
837 skel.PluginMainFuncs(skel.CNIFuncs{
838 Add: cmdAdd,
839 Check: cmdCheck,
840 Del: cmdDel,
841 Status: cmdStatus,
842 /* FIXME GC */
843 }, version.All, bv.BuildString("bridge"))
844 }
845
846 type cniBridgeIf struct {
847 Name string
848 ifIndex int
849 peerIndex int
850 masterIndex int
851 found bool
852 }
853
854 func validateInterface(intf current.Interface, expectInSb bool) (cniBridgeIf, netlink.Link, error) {
855 ifFound := cniBridgeIf{found: false}
856 if intf.Name == "" {
857 return ifFound, nil, fmt.Errorf("Interface name missing ")
858 }
859
860 link, err := netlinksafe.LinkByName(intf.Name)
861 if err != nil {
862 return ifFound, nil, fmt.Errorf("Interface name %s not found", intf.Name)
863 }
864
865 if expectInSb {
866 if intf.Sandbox == "" {
867 return ifFound, nil, fmt.Errorf("Interface %s is expected to be in a sandbox", intf.Name)
868 }
869 } else {
870 if intf.Sandbox != "" {
871 return ifFound, nil, fmt.Errorf("Interface %s should not be in sandbox", intf.Name)
872 }
873 }
874
875 return ifFound, link, err
876 }
877
878 func validateCniBrInterface(intf current.Interface, n *NetConf) (cniBridgeIf, error) {
879 brFound, link, err := validateInterface(intf, false)
880 if err != nil {
881 return brFound, err
882 }
883
884 _, isBridge := link.(*netlink.Bridge)
885 if !isBridge {
886 return brFound, fmt.Errorf("Interface %s does not have link type of bridge", intf.Name)
887 }
888
889 if intf.Mac != "" {
890 if intf.Mac != link.Attrs().HardwareAddr.String() {
891 return brFound, fmt.Errorf("Bridge interface %s Mac doesn't match: %s", intf.Name, intf.Mac)
892 }
893 }
894
895 linkPromisc := link.Attrs().Promisc != 0
896 if linkPromisc != n.PromiscMode {
897 return brFound, fmt.Errorf("Bridge interface %s configured Promisc Mode %v doesn't match current state: %v ",
898 intf.Name, n.PromiscMode, linkPromisc)
899 }
900
901 brFound.found = true
902 brFound.Name = link.Attrs().Name
903 brFound.ifIndex = link.Attrs().Index
904 brFound.masterIndex = link.Attrs().MasterIndex
905
906 return brFound, nil
907 }
908
909 func validateCniVethInterface(intf *current.Interface, brIf cniBridgeIf, contIf cniBridgeIf) (cniBridgeIf, error) {
910 vethFound, link, err := validateInterface(*intf, false)
911 if err != nil {
912 return vethFound, err
913 }
914
915 _, isVeth := link.(*netlink.Veth)
916 if !isVeth {
917 // just skip it, it's not what CNI created
918 return vethFound, nil
919 }
920
921 _, vethFound.peerIndex, err = ip.GetVethPeerIfindex(link.Attrs().Name)
922 if err != nil {
923 return vethFound, fmt.Errorf("Unable to obtain veth peer index for veth %s", link.Attrs().Name)
924 }
925 vethFound.ifIndex = link.Attrs().Index
926 vethFound.masterIndex = link.Attrs().MasterIndex
927
928 if vethFound.ifIndex != contIf.peerIndex {
929 return vethFound, nil
930 }
931
932 if contIf.ifIndex != vethFound.peerIndex {
933 return vethFound, nil
934 }
935
936 if vethFound.masterIndex != brIf.ifIndex {
937 return vethFound, nil
938 }
939
940 if intf.Mac != "" {
941 if intf.Mac != link.Attrs().HardwareAddr.String() {
942 return vethFound, fmt.Errorf("Interface %s Mac doesn't match: %s not found", intf.Name, intf.Mac)
943 }
944 }
945
946 vethFound.found = true
947 vethFound.Name = link.Attrs().Name
948
949 return vethFound, nil
950 }
951
952 func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error) {
953 vethFound, link, err := validateInterface(intf, true)
954 if err != nil {
955 return vethFound, err
956 }
957
958 _, isVeth := link.(*netlink.Veth)
959 if !isVeth {
960 return vethFound, fmt.Errorf("Error: Container interface %s not of type veth", link.Attrs().Name)
961 }
962 _, vethFound.peerIndex, err = ip.GetVethPeerIfindex(link.Attrs().Name)
963 if err != nil {
964 return vethFound, fmt.Errorf("Unable to obtain veth peer index for veth %s", link.Attrs().Name)
965 }
966 vethFound.ifIndex = link.Attrs().Index
967
968 if intf.Mac != "" {
969 if intf.Mac != link.Attrs().HardwareAddr.String() {
970 return vethFound, fmt.Errorf("Interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr)
971 }
972 }
973
974 vethFound.found = true
975 vethFound.Name = link.Attrs().Name
976
977 return vethFound, nil
978 }
979
980 func cmdCheck(args *skel.CmdArgs) error {
981 n, _, err := loadNetConf(args.StdinData, args.Args)
982 if err != nil {
983 return err
984 }
985 netns, err := ns.GetNS(args.Netns)
986 if err != nil {
987 return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
988 }
989 defer netns.Close()
990
991 // run the IPAM plugin and get back the config to apply
992 err = ipam.ExecCheck(n.IPAM.Type, args.StdinData)
993 if err != nil {
994 return err
995 }
996
997 // Parse previous result.
998 if n.NetConf.RawPrevResult == nil {
999 return fmt.Errorf("Required prevResult missing")
1000 }
1001
1002 if err := version.ParsePrevResult(&n.NetConf); err != nil {
1003 return err
1004 }
1005
1006 result, err := current.NewResultFromResult(n.PrevResult)
1007 if err != nil {
1008 return err
1009 }
1010
1011 var errLink error
1012 var contCNI, vethCNI cniBridgeIf
1013 var brMap, contMap current.Interface
1014
1015 // Find interfaces for names whe know, CNI Bridge and container
1016 for _, intf := range result.Interfaces {
1017 if n.BrName == intf.Name {
1018 brMap = *intf
1019 continue
1020 } else if args.IfName == intf.Name {
1021 if args.Netns == intf.Sandbox {
1022 contMap = *intf
1023 continue
1024 }
1025 }
1026 }
1027
1028 brCNI, err := validateCniBrInterface(brMap, n)
1029 if err != nil {
1030 return err
1031 }
1032
1033 // The namespace must be the same as what was configured
1034 if args.Netns != contMap.Sandbox {
1035 return fmt.Errorf("Sandbox in prevResult %s doesn't match configured netns: %s",
1036 contMap.Sandbox, args.Netns)
1037 }
1038
1039 // Check interface against values found in the container
1040 if err := netns.Do(func(_ ns.NetNS) error {
1041 contCNI, errLink = validateCniContainerInterface(contMap)
1042 if errLink != nil {
1043 return errLink
1044 }
1045 return nil
1046 }); err != nil {
1047 return err
1048 }
1049
1050 // Now look for veth that is peer with container interface.
1051 // Anything else wasn't created by CNI, skip it
1052 for _, intf := range result.Interfaces {
1053 // Skip this result if name is the same as cni bridge
1054 // It's either the cni bridge we dealt with above, or something with the
1055 // same name in a different namespace. We just skip since it's not ours
1056 if brMap.Name == intf.Name {
1057 continue
1058 }
1059
1060 // same here for container name
1061 if contMap.Name == intf.Name {
1062 continue
1063 }
1064
1065 vethCNI, errLink = validateCniVethInterface(intf, brCNI, contCNI)
1066 if errLink != nil {
1067 return errLink
1068 }
1069
1070 if vethCNI.found {
1071 // veth with container interface as peer and bridge as master found
1072 break
1073 }
1074 }
1075
1076 if !brCNI.found {
1077 return fmt.Errorf("CNI created bridge %s in host namespace was not found", n.BrName)
1078 }
1079 if !contCNI.found {
1080 return fmt.Errorf("CNI created interface in container %s not found", args.IfName)
1081 }
1082 if !vethCNI.found {
1083 return fmt.Errorf("CNI veth created for bridge %s was not found", n.BrName)
1084 }
1085
1086 // Check prevResults for ips, routes and dns against values found in the container
1087 return netns.Do(func(_ ns.NetNS) error {
1088 err = ip.ValidateExpectedInterfaceIPs(args.IfName, result.IPs)
1089 if err != nil {
1090 return err
1091 }
1092
1093 err = ip.ValidateExpectedRoute(result.Routes)
1094 if err != nil {
1095 return err
1096 }
1097 return nil
1098 })
1099 }
1100
1101 func uniqueID(containerID, cniIface string) string {
1102 return containerID + "-" + cniIface
1103 }
1104
1105 func cmdStatus(args *skel.CmdArgs) error {
1106 conf := NetConf{}
1107 if err := json.Unmarshal(args.StdinData, &conf); err != nil {
1108 return fmt.Errorf("failed to load netconf: %w", err)
1109 }
1110
1111 if conf.IPAM.Type != "" {
1112 if err := ipam.ExecStatus(conf.IPAM.Type, args.StdinData); err != nil {
1113 return err
1114 }
1115 }
1116
1117 return nil
1118 }