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