2020-07-11 21:03:55 +00:00
|
|
|
package firewall
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
|
2020-07-26 12:07:06 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
2020-07-11 21:03:55 +00:00
|
|
|
)
|
|
|
|
|
|
2021-07-23 19:12:16 +00:00
|
|
|
type VPNConnectionSetter interface {
|
2021-08-19 23:22:55 +00:00
|
|
|
SetVPNConnection(ctx context.Context,
|
|
|
|
|
connection models.Connection, vpnIntf string) error
|
2021-07-23 19:12:16 +00:00
|
|
|
}
|
|
|
|
|
|
2021-08-19 23:22:55 +00:00
|
|
|
func (c *Config) SetVPNConnection(ctx context.Context,
|
|
|
|
|
connection models.Connection, vpnIntf string) (err error) {
|
2020-07-11 21:03:55 +00:00
|
|
|
c.stateMutex.Lock()
|
|
|
|
|
defer c.stateMutex.Unlock()
|
|
|
|
|
|
|
|
|
|
if !c.enabled {
|
2020-10-12 15:29:58 -04:00
|
|
|
c.logger.Info("firewall disabled, only updating internal VPN connection")
|
|
|
|
|
c.vpnConnection = connection
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-20 02:58:16 +00:00
|
|
|
c.logger.Info("allowing VPN connection...")
|
2020-07-11 21:03:55 +00:00
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
if c.vpnConnection.Equal(connection) {
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
remove := true
|
|
|
|
|
if c.vpnConnection.IP != nil {
|
|
|
|
|
if err := c.acceptOutputTrafficToVPN(ctx, c.defaultInterface, c.vpnConnection, remove); err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
c.logger.Error("cannot remove outdated VPN connection rule: " + err.Error())
|
2020-07-11 21:03:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
2021-08-19 14:09:41 +00:00
|
|
|
c.vpnConnection = models.Connection{}
|
2021-08-19 23:22:55 +00:00
|
|
|
|
|
|
|
|
if c.vpnIntf != "" {
|
|
|
|
|
if err = c.acceptOutputThroughInterface(ctx, c.vpnIntf, remove); err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
c.logger.Error("cannot remove outdated VPN interface rule: " + err.Error())
|
2021-08-19 23:22:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
c.vpnIntf = ""
|
|
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
remove = false
|
2021-08-19 23:22:55 +00:00
|
|
|
|
2020-10-12 15:29:58 -04:00
|
|
|
if err := c.acceptOutputTrafficToVPN(ctx, c.defaultInterface, connection, remove); err != nil {
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("cannot allow output traffic through VPN connection: %w", err)
|
2020-07-11 21:03:55 +00:00
|
|
|
}
|
2020-10-12 15:29:58 -04:00
|
|
|
c.vpnConnection = connection
|
2021-08-19 23:22:55 +00:00
|
|
|
|
|
|
|
|
if err = c.acceptOutputThroughInterface(ctx, vpnIntf, remove); err != nil {
|
|
|
|
|
return fmt.Errorf("cannot accept output traffic through interface %s: %w", vpnIntf, err)
|
|
|
|
|
}
|
|
|
|
|
c.vpnIntf = vpnIntf
|
|
|
|
|
|
2020-07-11 21:03:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|