github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/libnetwork/drivers/bridge/setup_ip_forwarding.go (about)

     1  package bridge
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  
     7  	"github.com/docker/libnetwork/iptables"
     8  	"github.com/sirupsen/logrus"
     9  )
    10  
    11  const (
    12  	ipv4ForwardConf     = "/proc/sys/net/ipv4/ip_forward"
    13  	ipv4ForwardConfPerm = 0644
    14  )
    15  
    16  func configureIPForwarding(enable bool) error {
    17  	var val byte
    18  	if enable {
    19  		val = '1'
    20  	}
    21  	return ioutil.WriteFile(ipv4ForwardConf, []byte{val, '\n'}, ipv4ForwardConfPerm)
    22  }
    23  
    24  func setupIPForwarding(enableIPTables bool, enableIP6Tables bool) error {
    25  	// Get current IPv4 forward setup
    26  	ipv4ForwardData, err := ioutil.ReadFile(ipv4ForwardConf)
    27  	if err != nil {
    28  		return fmt.Errorf("Cannot read IP forwarding setup: %v", err)
    29  	}
    30  
    31  	// Enable IPv4 forwarding only if it is not already enabled
    32  	if ipv4ForwardData[0] != '1' {
    33  		// Enable IPv4 forwarding
    34  		if err := configureIPForwarding(true); err != nil {
    35  			return fmt.Errorf("Enabling IP forwarding failed: %v", err)
    36  		}
    37  		// When enabling ip_forward set the default policy on forward chain to
    38  		// drop only if the daemon option iptables is not set to false.
    39  		if enableIPTables {
    40  			iptable := iptables.GetIptable(iptables.IPv4)
    41  			if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
    42  				if err := configureIPForwarding(false); err != nil {
    43  					logrus.Errorf("Disabling IP forwarding failed, %v", err)
    44  				}
    45  				return err
    46  			}
    47  			iptables.OnReloaded(func() {
    48  				logrus.Debug("Setting the default DROP policy on firewall reload")
    49  				if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
    50  					logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err)
    51  				}
    52  			})
    53  		}
    54  	}
    55  
    56  	// add only iptables rules - forwarding is handled by setupIPv6Forwarding in setup_ipv6
    57  	if enableIP6Tables {
    58  		iptable := iptables.GetIptable(iptables.IPv6)
    59  		if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
    60  			logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err)
    61  		}
    62  		iptables.OnReloaded(func() {
    63  			logrus.Debug("Setting the default DROP policy on firewall reload")
    64  			if err := iptable.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
    65  				logrus.Warnf("Setting the default DROP policy on firewall reload failed, %v", err)
    66  			}
    67  		})
    68  	}
    69  
    70  	return nil
    71  }