-
-
Notifications
You must be signed in to change notification settings - Fork 324
/
outboundsubnets.go
94 lines (80 loc) · 2.45 KB
/
outboundsubnets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package firewall
import (
"context"
"fmt"
"net/netip"
"github.com/qdm12/gluetun/internal/netlink"
"github.com/qdm12/gluetun/internal/subnet"
)
func (c *Config) SetOutboundSubnets(ctx context.Context, subnets []netip.Prefix) (err error) {
c.stateMutex.Lock()
defer c.stateMutex.Unlock()
if !c.enabled {
c.logger.Info("firewall disabled, only updating allowed subnets internal list")
c.outboundSubnets = make([]netip.Prefix, len(subnets))
copy(c.outboundSubnets, subnets)
return nil
}
c.logger.Info("setting allowed subnets...")
subnetsToAdd, subnetsToRemove := subnet.FindSubnetsToChange(c.outboundSubnets, subnets)
if len(subnetsToAdd) == 0 && len(subnetsToRemove) == 0 {
return nil
}
c.removeOutboundSubnets(ctx, subnetsToRemove)
if err := c.addOutboundSubnets(ctx, subnetsToAdd); err != nil {
return fmt.Errorf("setting allowed outbound subnets: %w", err)
}
return nil
}
func (c *Config) removeOutboundSubnets(ctx context.Context, subnets []netip.Prefix) {
const remove = true
for _, subNet := range subnets {
subnetIsIPv6 := subNet.Addr().Is6()
firewallUpdated := false
for _, defaultRoute := range c.defaultRoutes {
defaultRouteIsIPv6 := defaultRoute.Family == netlink.FamilyV6
ipFamilyMatch := subnetIsIPv6 == defaultRouteIsIPv6
if !ipFamilyMatch {
continue
}
firewallUpdated = true
err := c.acceptOutputFromIPToSubnet(ctx, defaultRoute.NetInterface,
defaultRoute.AssignedIP, subNet, remove)
if err != nil {
c.logger.Error("cannot remove outdated outbound subnet: " + err.Error())
continue
}
}
if !firewallUpdated {
c.logIgnoredSubnetFamily(subNet)
continue
}
c.outboundSubnets = subnet.RemoveSubnetFromSubnets(c.outboundSubnets, subNet)
}
}
func (c *Config) addOutboundSubnets(ctx context.Context, subnets []netip.Prefix) error {
const remove = false
for _, subnet := range subnets {
subnetIsIPv6 := subnet.Addr().Is6()
firewallUpdated := false
for _, defaultRoute := range c.defaultRoutes {
defaultRouteIsIPv6 := defaultRoute.Family == netlink.FamilyV6
ipFamilyMatch := subnetIsIPv6 == defaultRouteIsIPv6
if !ipFamilyMatch {
continue
}
firewallUpdated = true
err := c.acceptOutputFromIPToSubnet(ctx, defaultRoute.NetInterface,
defaultRoute.AssignedIP, subnet, remove)
if err != nil {
return err
}
}
if !firewallUpdated {
c.logIgnoredSubnetFamily(subnet)
continue
}
c.outboundSubnets = append(c.outboundSubnets, subnet)
}
return nil
}