2020-10-29 19:23:44 -04:00
|
|
|
package firewall
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
2023-04-27 13:41:05 +00:00
|
|
|
"net/netip"
|
2021-08-25 17:22:48 +00:00
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/subnet"
|
2020-10-29 19:23:44 -04:00
|
|
|
)
|
|
|
|
|
|
2023-04-27 13:41:05 +00:00
|
|
|
func (c *Config) SetOutboundSubnets(ctx context.Context, subnets []netip.Prefix) (err error) {
|
2020-10-29 19:23:44 -04:00
|
|
|
c.stateMutex.Lock()
|
|
|
|
|
defer c.stateMutex.Unlock()
|
|
|
|
|
|
|
|
|
|
if !c.enabled {
|
|
|
|
|
c.logger.Info("firewall disabled, only updating allowed subnets internal list")
|
2023-04-27 13:41:05 +00:00
|
|
|
c.outboundSubnets = make([]netip.Prefix, len(subnets))
|
2020-10-29 19:23:44 -04:00
|
|
|
copy(c.outboundSubnets, subnets)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-20 02:58:16 +00:00
|
|
|
c.logger.Info("setting allowed subnets...")
|
2020-10-29 19:23:44 -04:00
|
|
|
|
2021-08-25 17:25:36 +00:00
|
|
|
subnetsToAdd, subnetsToRemove := subnet.FindSubnetsToChange(c.outboundSubnets, subnets)
|
2020-10-29 19:23:44 -04:00
|
|
|
if len(subnetsToAdd) == 0 && len(subnetsToRemove) == 0 {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.removeOutboundSubnets(ctx, subnetsToRemove)
|
|
|
|
|
if err := c.addOutboundSubnets(ctx, subnetsToAdd); err != nil {
|
2023-04-01 16:53:04 +00:00
|
|
|
return fmt.Errorf("setting allowed outbound subnets: %w", err)
|
2020-10-29 19:23:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-27 13:41:05 +00:00
|
|
|
func (c *Config) removeOutboundSubnets(ctx context.Context, subnets []netip.Prefix) {
|
2020-10-29 19:23:44 -04:00
|
|
|
const remove = true
|
2021-08-25 17:22:48 +00:00
|
|
|
for _, subNet := range subnets {
|
2022-03-13 13:26:09 +00:00
|
|
|
for _, defaultRoute := range c.defaultRoutes {
|
|
|
|
|
err := c.acceptOutputFromIPToSubnet(ctx, defaultRoute.NetInterface,
|
|
|
|
|
defaultRoute.AssignedIP, subNet, remove)
|
|
|
|
|
if err != nil {
|
|
|
|
|
c.logger.Error("cannot remove outdated outbound subnet: " + err.Error())
|
|
|
|
|
continue
|
|
|
|
|
}
|
2020-10-29 19:23:44 -04:00
|
|
|
}
|
2021-08-25 17:22:48 +00:00
|
|
|
c.outboundSubnets = subnet.RemoveSubnetFromSubnets(c.outboundSubnets, subNet)
|
2020-10-29 19:23:44 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-27 13:41:05 +00:00
|
|
|
func (c *Config) addOutboundSubnets(ctx context.Context, subnets []netip.Prefix) error {
|
2020-10-29 19:23:44 -04:00
|
|
|
const remove = false
|
|
|
|
|
for _, subnet := range subnets {
|
2022-03-13 13:26:09 +00:00
|
|
|
for _, defaultRoute := range c.defaultRoutes {
|
|
|
|
|
err := c.acceptOutputFromIPToSubnet(ctx, defaultRoute.NetInterface,
|
|
|
|
|
defaultRoute.AssignedIP, subnet, remove)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2020-10-29 19:23:44 -04:00
|
|
|
}
|
|
|
|
|
c.outboundSubnets = append(c.outboundSubnets, subnet)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|