Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flush nordvpn firewall rules that existed before daemon was started o… #641

Merged
merged 5 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions daemon/firewall/firewall.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ func (fw *Firewall) Disable() error {
return fw.swap(fw.working, fw.current)
}

func (fw *Firewall) Flush() error {
fw.mu.Lock()
defer fw.mu.Unlock()

return fw.current.Flush()
}

func (fw *Firewall) swap(current Agent, next Agent) error {
for _, rule := range fw.rules.rules {
if err := current.Delete(rule); err != nil {
Expand Down
9 changes: 9 additions & 0 deletions daemon/firewall/firewall_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ func (m *mockAgent) Delete(rule Rule) error {
return nil
}

func (m *mockAgent) Flush() error {
m.deleted++
return nil
}

func (f *failingAgent) Add(rule Rule) error {
f.added++
return fmt.Errorf("adding")
Expand All @@ -52,6 +57,10 @@ func (f *failingAgent) Delete(rule Rule) error {
return fmt.Errorf("deleting")
}

func (m *failingAgent) Flush() error {
return nil
}

func TestFirewallAdd(t *testing.T) {
category.Set(t, category.Unit)

Expand Down
43 changes: 40 additions & 3 deletions daemon/firewall/iptables/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package iptables

import (
"fmt"
"log"
"net"
"net/netip"
"os/exec"
"regexp"
"sort"
"strings"
"sync"
Expand All @@ -15,8 +17,9 @@ import (
)

const (
ipv4Table = "iptables"
ipv6Table = "ip6tables"
ipv4Table = "iptables"
ipv6Table = "ip6tables"
defaultComment = "nordvpn"
)

const (
Expand Down Expand Up @@ -118,6 +121,40 @@ func (ipt *IPTables) applyRule(rule firewall.Rule, add bool) error {
return nil
}

func generateFlushRules(rules string) []string {
re := regexp.MustCompile(fmt.Sprintf(`--comment\s+%s(?:\s|$)`, regexp.QuoteMeta(defaultComment)))
flushRules := []string{}
for _, rule := range strings.Split(rules, "\n") {
if re.MatchString(rule) {
newRule := strings.Replace(rule, "-A", "-D", 1)
flushRules = append(flushRules, newRule)
}
}

return flushRules
}

func (ipt *IPTables) Flush() error {
var finalErr error = nil
for _, iptableVersion := range ipt.supportedIPTables {
out, err := exec.Command(iptableVersion, "-S").CombinedOutput()
mariusSincovici marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return fmt.Errorf("listing rules: %w", err)
}

rules := string(out)
for _, rule := range generateFlushRules(rules) {
err := exec.Command(iptableVersion, strings.Split(rule, " ")...).Run()
if err != nil {
log.Printf("%s failed to delete rule %s: %s", internal.ErrorPrefix, rule, err)
finalErr = fmt.Errorf("failed to delete all rules")
}
}
}

return finalErr
}

// FilterSupportedIPTables filter supported versions based on what exists in the system
func FilterSupportedIPTables(supportedIPTables []string) []string {
var supported []string
Expand Down Expand Up @@ -395,7 +432,7 @@ func generateIPTablesRule(
jump := " -j "

if comment == "" {
comment = "nordvpn"
comment = defaultComment
}

var acceptComment string
Expand Down
40 changes: 40 additions & 0 deletions daemon/firewall/iptables/iptables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,46 @@ func TestPortsToRanges(t *testing.T) {
}
}

func TestGenerateFlushRules(t *testing.T) {
category.Set(t, category.Firewall)

currentRulesS := []string{
"-A FORWARD -i eth0 -o eth0 -m comment --comment nordvpn -j ACCEPT",
"-A FORWARD -s 192.168.42.56/24 -i eth0 -m comment --comment \"comment\" -j ACCEPT",
"-A FORWARD -d 10.55.97.34/24 -o eth0 -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment \"comment b\" -j ACCEPT",
"-A FORWARD -i eth0 -m comment --comment \"comment A\" -j REJECT --reject-with icmp-port-unreachable",
"-A FORWARD -o eth1 -m comment --comment \"comment B\" -j REJECT --reject-with icmp-port-unreachable",
"-A FORWARD -i eth0 -m comment --comment nordvpn-meshnet -j REJECT --reject-with icmp-port-unreachable",
"-A FORWARD -o eth1 -m comment --comment meshnet-nordvpn -j REJECT --reject-with icmp-port-unreachable",
"-A FORWARD -i eth0 -m comment --comment nordvpn-meshnet-test -j REJECT --reject-with icmp-port-unreachable",
"-A FORWARD -o eth1 -m comment --comment \"nordvpn test\" -j REJECT --reject-with icmp-port-unreachable",
"-A OUTPUT -d 169.254.0.0/16 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 169.254.0.0/16 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 192.168.0.0/16 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 192.168.0.0/16 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 172.16.0.0/12 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 172.16.0.0/12 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 10.0.0.0/8 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-A OUTPUT -d 10.0.0.0/8 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
}

expectedRules := []string{
"-D FORWARD -i eth0 -o eth0 -m comment --comment nordvpn -j ACCEPT",
"-D OUTPUT -d 169.254.0.0/16 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 169.254.0.0/16 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 192.168.0.0/16 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 192.168.0.0/16 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 172.16.0.0/12 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 172.16.0.0/12 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 10.0.0.0/8 -p tcp -m tcp --dport 53 -m comment --comment nordvpn -j DROP",
"-D OUTPUT -d 10.0.0.0/8 -p udp -m udp --dport 53 -m comment --comment nordvpn -j DROP",
}

currentRules := strings.Join(currentRulesS, "\n")
flushRules := generateFlushRules(currentRules)
assert.Equal(t, expectedRules, flushRules)
}

func containsSlice(t *testing.T, list, sublist []string) bool {
t.Helper()
for _, s := range sublist {
Expand Down
1 change: 1 addition & 0 deletions daemon/firewall/notables/notables.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ type Facade struct{}

func (*Facade) Add(firewall.Rule) error { return nil }
func (*Facade) Delete(firewall.Rule) error { return nil }
func (*Facade) Flush() error { return nil }
4 changes: 4 additions & 0 deletions daemon/firewall/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ type Service interface {
Enable() error
// Disable firewall
Disable() error
// Flushes firewall
Flush() error
}

// Agent carries out required firewall changes.
Expand All @@ -22,4 +24,6 @@ type Agent interface {
Add(Rule) error
// Delete a firewall rule
Delete(Rule) error
// Flush removes all nordvpn rules
Flush() error
}
4 changes: 1 addition & 3 deletions daemon/rpc_disconnect.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
package daemon

import (
"errors"
"log"

"github.com/NordSecurity/nordvpn-linux/config"
"github.com/NordSecurity/nordvpn-linux/daemon/firewall"
"github.com/NordSecurity/nordvpn-linux/daemon/pb"
"github.com/NordSecurity/nordvpn-linux/events"
"github.com/NordSecurity/nordvpn-linux/internal"
)

func (r *RPC) Disconnect(_ *pb.Empty, srv pb.Daemon_DisconnectServer) error {
if !r.netw.IsVPNActive() {
if err := r.netw.UnsetFirewall(); err != nil && !errors.Is(err, firewall.ErrRuleNotFound) {
if err := r.netw.UnsetFirewall(); err != nil {
log.Println(internal.WarningPrefix, "failed to force unset firewall on disconnect:", err)
}
return srv.Send(&pb.Payload{
Expand Down
2 changes: 2 additions & 0 deletions network/resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ type workingAgent struct{}

func (workingAgent) Add(firewall.Rule) error { return nil }
func (workingAgent) Delete(firewall.Rule) error { return nil }
func (workingAgent) Flush() error { return nil }

type failingAgent struct{}

func (failingAgent) Add(firewall.Rule) error { return mock.ErrOnPurpose }
func (failingAgent) Delete(firewall.Rule) error { return mock.ErrOnPurpose }
func (failingAgent) Flush() error { return mock.ErrOnPurpose }

func TestAllowlistIP(t *testing.T) {
category.Set(t, category.Route)
Expand Down
22 changes: 14 additions & 8 deletions networker/networker.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ const (
allowIncomingRule = "-allow-rule-"
// a string to be prepended with peers public key and appended with peers ip address to form the internal rule name
// for blocking incoming connections into local networks
blockLanRule = "-block-lan-rule-"
blockLanRule = "-block-lan-rule-"
meshnetFirewallRuleComment = "nordvpn-meshnet"
)

// ConnectionStatus of a currently active connection
Expand Down Expand Up @@ -1080,10 +1081,10 @@ func (netw *Combined) UnsetFirewall() error {
netw.mu.Lock()
defer netw.mu.Unlock()

if !netw.isKillSwitchSet {
bartoszWojciechO marked this conversation as resolved.
Show resolved Hide resolved
return netw.unsetNetwork()
if netw.isKillSwitchSet {
return nil
}
return nil
return netw.fw.Flush()
}

func (netw *Combined) unsetNetwork() error {
Expand Down Expand Up @@ -1459,7 +1460,8 @@ func (netw *Combined) allowIncoming(publicKey string, address netip.Addr, lanAll
RemoteNetworks: []netip.Prefix{
netip.PrefixFrom(address, address.BitLen()),
},
Allow: true,
Allow: true,
Comment: meshnetFirewallRuleComment,
}
rules = append(rules, rule)

Expand All @@ -1483,7 +1485,8 @@ func (netw *Combined) allowIncoming(publicKey string, address netip.Addr, lanAll
RemoteNetworks: []netip.Prefix{
netip.PrefixFrom(address, address.BitLen()),
},
Allow: false,
Allow: false,
Comment: meshnetFirewallRuleComment,
}

rules = append(rules, rule)
Expand Down Expand Up @@ -1515,7 +1518,8 @@ func (netw *Combined) allowFileshare(publicKey string, address netip.Addr) error
RemoteNetworks: []netip.Prefix{
netip.PrefixFrom(address, address.BitLen()),
},
Allow: true,
Allow: true,
Comment: meshnetFirewallRuleComment,
}}

ruleIndex := slices.Index(netw.rules, ruleName)
Expand Down Expand Up @@ -1695,6 +1699,7 @@ func (netw *Combined) defaultMeshBlock(ip netip.Addr) error {
Direction: firewall.Inbound,
RemoteNetworks: []netip.Prefix{defaultMeshSubnet},
Allow: false,
Comment: meshnetFirewallRuleComment,
},
// Allow inbound traffic for the existing connections
// E. g. this device is making some calls to another
Expand All @@ -1711,7 +1716,8 @@ func (netw *Combined) defaultMeshBlock(ip netip.Addr) error {
firewall.Established,
},
},
Allow: true,
Allow: true,
Comment: meshnetFirewallRuleComment,
},
}); err != nil {
return err
Expand Down
Loading
Loading