github.com/rish1988/moby@v25.0.2+incompatible/libnetwork/drivers/bridge/setup_ip_tables_linux.go (about)

     1  package bridge
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net"
     8  	"strings"
     9  
    10  	"github.com/containerd/log"
    11  	"github.com/docker/docker/libnetwork/iptables"
    12  	"github.com/docker/docker/libnetwork/types"
    13  	"github.com/vishvananda/netlink"
    14  )
    15  
    16  // DockerChain: DOCKER iptable chain name
    17  const (
    18  	DockerChain = "DOCKER"
    19  
    20  	// Isolation between bridge networks is achieved in two stages by means
    21  	// of the following two chains in the filter table. The first chain matches
    22  	// on the source interface being a bridge network's bridge and the
    23  	// destination being a different interface. A positive match leads to the
    24  	// second isolation chain. No match returns to the parent chain. The second
    25  	// isolation chain matches on destination interface being a bridge network's
    26  	// bridge. A positive match identifies a packet originated from one bridge
    27  	// network's bridge destined to another bridge network's bridge and will
    28  	// result in the packet being dropped. No match returns to the parent chain.
    29  
    30  	IsolationChain1 = "DOCKER-ISOLATION-STAGE-1"
    31  	IsolationChain2 = "DOCKER-ISOLATION-STAGE-2"
    32  )
    33  
    34  func setupIPChains(config configuration, version iptables.IPVersion) (natChain *iptables.ChainInfo, filterChain *iptables.ChainInfo, isolationChain1 *iptables.ChainInfo, isolationChain2 *iptables.ChainInfo, retErr error) {
    35  	// Sanity check.
    36  	if !config.EnableIPTables {
    37  		return nil, nil, nil, nil, errors.New("cannot create new chains, EnableIPTable is disabled")
    38  	}
    39  
    40  	hairpinMode := !config.EnableUserlandProxy
    41  
    42  	iptable := iptables.GetIptable(version)
    43  
    44  	natChain, err := iptable.NewChain(DockerChain, iptables.Nat, hairpinMode)
    45  	if err != nil {
    46  		return nil, nil, nil, nil, fmt.Errorf("failed to create NAT chain %s: %v", DockerChain, err)
    47  	}
    48  	defer func() {
    49  		if retErr != nil {
    50  			if err := iptable.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
    51  				log.G(context.TODO()).Warnf("failed on removing iptables NAT chain %s on cleanup: %v", DockerChain, err)
    52  			}
    53  		}
    54  	}()
    55  
    56  	filterChain, err = iptable.NewChain(DockerChain, iptables.Filter, false)
    57  	if err != nil {
    58  		return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER chain %s: %v", DockerChain, err)
    59  	}
    60  	defer func() {
    61  		if err != nil {
    62  			if err := iptable.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {
    63  				log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", DockerChain, err)
    64  			}
    65  		}
    66  	}()
    67  
    68  	isolationChain1, err = iptable.NewChain(IsolationChain1, iptables.Filter, false)
    69  	if err != nil {
    70  		return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
    71  	}
    72  	defer func() {
    73  		if retErr != nil {
    74  			if err := iptable.RemoveExistingChain(IsolationChain1, iptables.Filter); err != nil {
    75  				log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain1, err)
    76  			}
    77  		}
    78  	}()
    79  
    80  	isolationChain2, err = iptable.NewChain(IsolationChain2, iptables.Filter, false)
    81  	if err != nil {
    82  		return nil, nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
    83  	}
    84  	defer func() {
    85  		if retErr != nil {
    86  			if err := iptable.RemoveExistingChain(IsolationChain2, iptables.Filter); err != nil {
    87  				log.G(context.TODO()).Warnf("failed on removing iptables FILTER chain %s on cleanup: %v", IsolationChain2, err)
    88  			}
    89  		}
    90  	}()
    91  
    92  	if err := iptable.AddReturnRule(IsolationChain1); err != nil {
    93  		return nil, nil, nil, nil, err
    94  	}
    95  
    96  	if err := iptable.AddReturnRule(IsolationChain2); err != nil {
    97  		return nil, nil, nil, nil, err
    98  	}
    99  
   100  	return natChain, filterChain, isolationChain1, isolationChain2, nil
   101  }
   102  
   103  func (n *bridgeNetwork) setupIP4Tables(config *networkConfiguration, i *bridgeInterface) error {
   104  	d := n.driver
   105  	d.Lock()
   106  	driverConfig := d.config
   107  	d.Unlock()
   108  
   109  	// Sanity check.
   110  	if !driverConfig.EnableIPTables {
   111  		return errors.New("Cannot program chains, EnableIPTable is disabled")
   112  	}
   113  
   114  	maskedAddrv4 := &net.IPNet{
   115  		IP:   i.bridgeIPv4.IP.Mask(i.bridgeIPv4.Mask),
   116  		Mask: i.bridgeIPv4.Mask,
   117  	}
   118  	return n.setupIPTables(iptables.IPv4, maskedAddrv4, config, i)
   119  }
   120  
   121  func (n *bridgeNetwork) setupIP6Tables(config *networkConfiguration, i *bridgeInterface) error {
   122  	d := n.driver
   123  	d.Lock()
   124  	driverConfig := d.config
   125  	d.Unlock()
   126  
   127  	// Sanity check.
   128  	if !driverConfig.EnableIP6Tables {
   129  		return errors.New("Cannot program chains, EnableIP6Tables is disabled")
   130  	}
   131  
   132  	maskedAddrv6 := &net.IPNet{
   133  		IP:   i.bridgeIPv6.IP.Mask(i.bridgeIPv6.Mask),
   134  		Mask: i.bridgeIPv6.Mask,
   135  	}
   136  
   137  	return n.setupIPTables(iptables.IPv6, maskedAddrv6, config, i)
   138  }
   139  
   140  func (n *bridgeNetwork) setupIPTables(ipVersion iptables.IPVersion, maskedAddr *net.IPNet, config *networkConfiguration, i *bridgeInterface) error {
   141  	var err error
   142  
   143  	d := n.driver
   144  	d.Lock()
   145  	driverConfig := d.config
   146  	d.Unlock()
   147  
   148  	// Pickup this configuration option from driver
   149  	hairpinMode := !driverConfig.EnableUserlandProxy
   150  
   151  	iptable := iptables.GetIptable(ipVersion)
   152  
   153  	if config.Internal {
   154  		if err = setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, true); err != nil {
   155  			return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
   156  		}
   157  		n.registerIptCleanFunc(func() error {
   158  			return setupInternalNetworkRules(config.BridgeName, maskedAddr, config.EnableICC, false)
   159  		})
   160  	} else {
   161  		if err = setupIPTablesInternal(ipVersion, config, maskedAddr, hairpinMode, true); err != nil {
   162  			return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
   163  		}
   164  		n.registerIptCleanFunc(func() error {
   165  			return setupIPTablesInternal(ipVersion, config, maskedAddr, hairpinMode, false)
   166  		})
   167  		natChain, filterChain, _, _, err := n.getDriverChains(ipVersion)
   168  		if err != nil {
   169  			return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
   170  		}
   171  
   172  		err = iptable.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
   173  		if err != nil {
   174  			return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
   175  		}
   176  
   177  		err = iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
   178  		if err != nil {
   179  			return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
   180  		}
   181  
   182  		n.registerIptCleanFunc(func() error {
   183  			return iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
   184  		})
   185  
   186  		if ipVersion == iptables.IPv4 {
   187  			n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
   188  		} else {
   189  			n.portMapperV6.SetIptablesChain(natChain, n.getNetworkBridgeName())
   190  		}
   191  	}
   192  
   193  	d.Lock()
   194  	err = iptable.EnsureJumpRule("FORWARD", IsolationChain1)
   195  	d.Unlock()
   196  	return err
   197  }
   198  
   199  type iptRule struct {
   200  	ipv   iptables.IPVersion
   201  	table iptables.Table
   202  	chain string
   203  	args  []string
   204  }
   205  
   206  // Exists returns true if the rule exists in the kernel.
   207  func (r iptRule) Exists() bool {
   208  	return iptables.GetIptable(r.ipv).Exists(r.table, r.chain, r.args...)
   209  }
   210  
   211  func (r iptRule) cmdArgs(op iptables.Action) []string {
   212  	return append([]string{"-t", string(r.table), string(op), r.chain}, r.args...)
   213  }
   214  
   215  func (r iptRule) exec(op iptables.Action) error {
   216  	return iptables.GetIptable(r.ipv).RawCombinedOutput(r.cmdArgs(op)...)
   217  }
   218  
   219  // Append appends the rule to the end of the chain. If the rule already exists anywhere in the
   220  // chain, this is a no-op.
   221  func (r iptRule) Append() error {
   222  	if r.Exists() {
   223  		return nil
   224  	}
   225  	return r.exec(iptables.Append)
   226  }
   227  
   228  // Insert inserts the rule at the head of the chain. If the rule already exists anywhere in the
   229  // chain, this is a no-op.
   230  func (r iptRule) Insert() error {
   231  	if r.Exists() {
   232  		return nil
   233  	}
   234  	return r.exec(iptables.Insert)
   235  }
   236  
   237  // Delete deletes the rule from the kernel. If the rule does not exist, this is a no-op.
   238  func (r iptRule) Delete() error {
   239  	if !r.Exists() {
   240  		return nil
   241  	}
   242  	return r.exec(iptables.Delete)
   243  }
   244  
   245  func (r iptRule) String() string {
   246  	cmd := append([]string{"iptables"}, r.cmdArgs("-A")...)
   247  	if r.ipv == iptables.IPv6 {
   248  		cmd[0] = "ip6tables"
   249  	}
   250  	return strings.Join(cmd, " ")
   251  }
   252  
   253  func setupIPTablesInternal(ipVer iptables.IPVersion, config *networkConfiguration, addr *net.IPNet, hairpin, enable bool) error {
   254  	var (
   255  		address   = addr.String()
   256  		skipDNAT  = iptRule{ipv: ipVer, table: iptables.Nat, chain: DockerChain, args: []string{"-i", config.BridgeName, "-j", "RETURN"}}
   257  		outRule   = iptRule{ipv: ipVer, table: iptables.Filter, chain: "FORWARD", args: []string{"-i", config.BridgeName, "!", "-o", config.BridgeName, "-j", "ACCEPT"}}
   258  		natArgs   []string
   259  		hpNatArgs []string
   260  	)
   261  	hostIP := config.HostIPv4
   262  	if ipVer == iptables.IPv6 {
   263  		hostIP = config.HostIPv6
   264  	}
   265  	// If hostIP is set, the user wants IPv4/IPv6 SNAT with the given address.
   266  	if hostIP != nil {
   267  		hostAddr := hostIP.String()
   268  		natArgs = []string{"-s", address, "!", "-o", config.BridgeName, "-j", "SNAT", "--to-source", hostAddr}
   269  		hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", config.BridgeName, "-j", "SNAT", "--to-source", hostAddr}
   270  		// Else use MASQUERADE which picks the src-ip based on NH from the route table
   271  	} else {
   272  		natArgs = []string{"-s", address, "!", "-o", config.BridgeName, "-j", "MASQUERADE"}
   273  		hpNatArgs = []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", config.BridgeName, "-j", "MASQUERADE"}
   274  	}
   275  
   276  	natRule := iptRule{ipv: ipVer, table: iptables.Nat, chain: "POSTROUTING", args: natArgs}
   277  	hpNatRule := iptRule{ipv: ipVer, table: iptables.Nat, chain: "POSTROUTING", args: hpNatArgs}
   278  
   279  	// Set NAT.
   280  	if config.EnableIPMasquerade {
   281  		if err := programChainRule(natRule, "NAT", enable); err != nil {
   282  			return err
   283  		}
   284  	}
   285  
   286  	if config.EnableIPMasquerade && !hairpin {
   287  		if err := programChainRule(skipDNAT, "SKIP DNAT", enable); err != nil {
   288  			return err
   289  		}
   290  	}
   291  
   292  	// In hairpin mode, masquerade traffic from localhost. If hairpin is disabled or if we're tearing down
   293  	// that bridge, make sure the iptables rule isn't lying around.
   294  	if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable && hairpin); err != nil {
   295  		return err
   296  	}
   297  
   298  	// Set Inter Container Communication.
   299  	if err := setIcc(ipVer, config.BridgeName, config.EnableICC, enable); err != nil {
   300  		return err
   301  	}
   302  
   303  	// Set Accept on all non-intercontainer outgoing packets.
   304  	return programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable)
   305  }
   306  
   307  func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
   308  	operation := "disable"
   309  	fn := rule.Delete
   310  	if insert {
   311  		operation = "enable"
   312  		fn = rule.Insert
   313  	}
   314  	if err := fn(); err != nil {
   315  		return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
   316  	}
   317  	return nil
   318  }
   319  
   320  func setIcc(version iptables.IPVersion, bridgeIface string, iccEnable, insert bool) error {
   321  	args := []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
   322  	acceptRule := iptRule{ipv: version, table: iptables.Filter, chain: "FORWARD", args: append(args, "ACCEPT")}
   323  	dropRule := iptRule{ipv: version, table: iptables.Filter, chain: "FORWARD", args: append(args, "DROP")}
   324  	if insert {
   325  		if !iccEnable {
   326  			acceptRule.Delete()
   327  			if err := dropRule.Append(); err != nil {
   328  				return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
   329  			}
   330  		} else {
   331  			dropRule.Delete()
   332  			if err := acceptRule.Insert(); err != nil {
   333  				return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
   334  			}
   335  		}
   336  	} else {
   337  		// Remove any ICC rule.
   338  		if !iccEnable {
   339  			dropRule.Delete()
   340  		} else {
   341  			acceptRule.Delete()
   342  		}
   343  	}
   344  	return nil
   345  }
   346  
   347  // Control Inter Network Communication. Install[Remove] only if it is [not] present.
   348  func setINC(version iptables.IPVersion, iface string, enable bool) error {
   349  	iptable := iptables.GetIptable(version)
   350  	var (
   351  		action    = iptables.Insert
   352  		actionMsg = "add"
   353  		chains    = []string{IsolationChain1, IsolationChain2}
   354  		rules     = [][]string{
   355  			{"-i", iface, "!", "-o", iface, "-j", IsolationChain2},
   356  			{"-o", iface, "-j", "DROP"},
   357  		}
   358  	)
   359  
   360  	if !enable {
   361  		action = iptables.Delete
   362  		actionMsg = "remove"
   363  	}
   364  
   365  	for i, chain := range chains {
   366  		if err := iptable.ProgramRule(iptables.Filter, chain, action, rules[i]); err != nil {
   367  			msg := fmt.Sprintf("unable to %s inter-network communication rule: %v", actionMsg, err)
   368  			if enable {
   369  				if i == 1 {
   370  					// Rollback the rule installed on first chain
   371  					if err2 := iptable.ProgramRule(iptables.Filter, chains[0], iptables.Delete, rules[0]); err2 != nil {
   372  						log.G(context.TODO()).Warnf("Failed to rollback iptables rule after failure (%v): %v", err, err2)
   373  					}
   374  				}
   375  				return fmt.Errorf(msg)
   376  			}
   377  			log.G(context.TODO()).Warn(msg)
   378  		}
   379  	}
   380  
   381  	return nil
   382  }
   383  
   384  // Obsolete chain from previous docker versions
   385  const oldIsolationChain = "DOCKER-ISOLATION"
   386  
   387  func removeIPChains(version iptables.IPVersion) {
   388  	ipt := iptables.GetIptable(version)
   389  
   390  	// Remove obsolete rules from default chains
   391  	ipt.ProgramRule(iptables.Filter, "FORWARD", iptables.Delete, []string{"-j", oldIsolationChain})
   392  
   393  	// Remove chains
   394  	for _, chainInfo := range []iptables.ChainInfo{
   395  		{Name: DockerChain, Table: iptables.Nat, IPVersion: version},
   396  		{Name: DockerChain, Table: iptables.Filter, IPVersion: version},
   397  		{Name: IsolationChain1, Table: iptables.Filter, IPVersion: version},
   398  		{Name: IsolationChain2, Table: iptables.Filter, IPVersion: version},
   399  		{Name: oldIsolationChain, Table: iptables.Filter, IPVersion: version},
   400  	} {
   401  		if err := chainInfo.Remove(); err != nil {
   402  			log.G(context.TODO()).Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
   403  		}
   404  	}
   405  }
   406  
   407  func setupInternalNetworkRules(bridgeIface string, addr *net.IPNet, icc, insert bool) error {
   408  	var version iptables.IPVersion
   409  	var inDropRule, outDropRule iptRule
   410  
   411  	if addr.IP.To4() != nil {
   412  		version = iptables.IPv4
   413  		inDropRule = iptRule{
   414  			ipv:   version,
   415  			table: iptables.Filter,
   416  			chain: IsolationChain1,
   417  			args:  []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
   418  		}
   419  		outDropRule = iptRule{
   420  			ipv:   version,
   421  			table: iptables.Filter,
   422  			chain: IsolationChain1,
   423  			args:  []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
   424  		}
   425  	} else {
   426  		version = iptables.IPv6
   427  		inDropRule = iptRule{
   428  			ipv:   version,
   429  			table: iptables.Filter,
   430  			chain: IsolationChain1,
   431  			args:  []string{"-i", bridgeIface, "!", "-o", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"},
   432  		}
   433  		outDropRule = iptRule{
   434  			ipv:   version,
   435  			table: iptables.Filter,
   436  			chain: IsolationChain1,
   437  			args:  []string{"!", "-i", bridgeIface, "-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"},
   438  		}
   439  	}
   440  
   441  	if err := programChainRule(inDropRule, "DROP INCOMING", insert); err != nil {
   442  		return err
   443  	}
   444  	if err := programChainRule(outDropRule, "DROP OUTGOING", insert); err != nil {
   445  		return err
   446  	}
   447  
   448  	// Set Inter Container Communication.
   449  	return setIcc(version, bridgeIface, icc, insert)
   450  }
   451  
   452  // clearConntrackEntries flushes conntrack entries matching endpoint IP address
   453  // or matching one of the exposed UDP port.
   454  // In the first case, this could happen if packets were received by the host
   455  // between userland proxy startup and iptables setup.
   456  // In the latter case, this could happen if packets were received whereas there
   457  // were nowhere to route them, as netfilter creates entries in such case.
   458  // This is required because iptables NAT rules are evaluated by netfilter only
   459  // when creating a new conntrack entry. When Docker latter adds NAT rules,
   460  // netfilter ignore them for any packet matching a pre-existing conntrack entry.
   461  // As such, we need to flush all those conntrack entries to make sure NAT rules
   462  // are correctly applied to all packets.
   463  // See: #8795, #44688 & #44742.
   464  func clearConntrackEntries(nlh *netlink.Handle, ep *bridgeEndpoint) {
   465  	var ipv4List []net.IP
   466  	var ipv6List []net.IP
   467  	var udpPorts []uint16
   468  
   469  	if ep.addr != nil {
   470  		ipv4List = append(ipv4List, ep.addr.IP)
   471  	}
   472  	if ep.addrv6 != nil {
   473  		ipv6List = append(ipv6List, ep.addrv6.IP)
   474  	}
   475  	for _, pb := range ep.portMapping {
   476  		if pb.Proto == types.UDP {
   477  			udpPorts = append(udpPorts, pb.HostPort)
   478  		}
   479  	}
   480  
   481  	iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
   482  	iptables.DeleteConntrackEntriesByPort(nlh, types.UDP, udpPorts)
   483  }