Coder Social home page Coder Social logo

go-iptables's Introduction

go-iptables

GoDoc Build status

Go bindings for iptables utility.

In-kernel netfilter does not have a good userspace API. The tables are manipulated via setsockopt that sets/replaces the entire table. Changes to existing table need to be resolved by userspace code which is difficult and error-prone. Netfilter developers heavily advocate using iptables utlity for programmatic manipulation.

go-iptables wraps invocation of iptables utility with functions to append and delete rules; create, clear and delete chains.

go-iptables's People

Contributors

alegrey91 avatar aojea avatar bgilbert avatar bvandewalle avatar coreosbot avatar costasd avatar danwinship avatar dcbw avatar dthadi3 avatar eyakubovich avatar jonboulle avatar kuroa-me avatar lucab avatar machooo-x avatar mars1024 avatar mccv1r0 avatar nick-parry avatar phensley avatar rhafer avatar robbertkl avatar robertabbott avatar sanbornm avatar sh4d1 avatar sirphuttel avatar skitt avatar squeed avatar steveej avatar terratech avatar vainu-arto avatar yannh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-iptables's Issues

CAP_NET_ADMIN capability ?

Hi,

Is it possible to run a program using go-iptables as an unprivileged user with the cap_net_admincap ?

From the the capabilities(7) man page :

     CAP_NET_ADMIN
              Perform various network-related operations:
              * interface configuration;
              * administration of IP firewall, masquerading, and
                accounting;
              * modify routing tables;
              * bind to any address for transparent proxying;
              * set type-of-service (TOS);
              * clear driver statistics;
              * set promiscuous mode;
              * enabling multicasting;

administration of IP firewall is somewhat vague, but I've tried with a small example by setting cap_net_admin using setcap on the compiled binary but I get :

exit status 4: Fatal: can't open lock file /run/xtables.lock: Permission denied

Thanks for this project.

nftables support

@squeed, I am running nftables:

$ iptables --version
iptables v1.8.2 (nf_tables)

I recently opened an containernetworking/plugins#461. In a nutshell, CNI uses go-iptables library to configure IP masquerading. Some of the commands succeed, but some fail (e.g. iptables -t nat -S --wait):

ERRO[0000] Error adding network: failed to list chains: running [/usr/sbin/iptables -t nat -S --wait]: exit status 1: iptables v1.8.2 (nf_tables): table `nat' is incompatible, use 'nft' tool.

ERRO[0000] Error while adding pod to CNI network "podman": failed to list chains: running [/usr/sbin/iptables -t nat -S --wait]: exit status 1: iptables v1.8.2 (nf_tables): table `nat' is incompatible, use 'nft' tool.

Error: error configuring network namespace for container 51f6adbaed7d674fb4b48d501eb7ce0605d09e003ac09f6588b98dea7230ca9f: failed to list chains: running [/usr/sbin/iptables -t nat -S --wait]: exit status 1: iptables v1.8.2 (nf_tables): table `nat' is incompatible, use 'nft' tool.

Is there a plan to support nftables? Are you open to PR on it?

hostnames not supported?

If I use this syntax

iptables -N testing

iptables -A testing -s server.marathon.mesos -j ACCEPT

I am getting this output

[@.bak]# iptables -L testing -vn
Chain testing (0 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      *       192.168.10.151       0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       192.168.10.153       0.0.0.0/0
    0     0 ACCEPT     all  --  *      *       192.168.10.114       0.0.0.0/0

Would be nice to have such functionality.

Cannot parse negated CIDR ex: "!192.168.122.0/24"

Calling ipt.StructuredStats("nat", "POSTROUTING") when rules have negated ranges can error:

invalid CIDR address: !192.168.122.0/24%!(EXTRA string=could not parse destination)

On my machine, I set up a virtual bridge for this subnet, and these iptables rules were auto-created:

ifconfig virbr0; \
sudo iptables -L | grep 192.168; \
sudo iptables -t nat -L POSTROUTING | grep 192.168 \

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 06:79:79:15:1a:de  txqueuelen 1000  (Ethernet)
        RX packets 76642  bytes 4332785 (4.3 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 476675  bytes 726146534 (726.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ACCEPT     all  --  anywhere             192.168.122.0/24     ctstate RELATED,ESTABLISHED
ACCEPT     all  --  192.168.122.0/24     anywhere            
RETURN     all  --  192.168.122.0/24     base-address.mcast.net/24 
RETURN     all  --  192.168.122.0/24     255.255.255.255     
MASQUERADE  tcp  --  192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
MASQUERADE  udp  --  192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
MASQUERADE  all  --  192.168.122.0/24    !192.168.122.0/24   

ignite uses this library call to cleanup chains, and these MASQ rules fail to net.ParseCIDR due to the leading exclamation mark negating the subnet: weaveworks/ignite#393


Here's a minimal reproduction:

Test Code
package main

import (
	"fmt"

	"github.com/coreos/go-iptables/iptables"
)

// testActual is a forked version of ipt.StructuredStats() that prints debug info
func testActual(ipt *iptables.IPTables) ([]iptables.Stat, error) {
	table := "nat"
	chain := "POSTROUTING"

	rawStats, err := ipt.Stats(table, chain)
	if err != nil {
		return nil, err
	}

	structStats := []iptables.Stat{}
	for _, rawStat := range rawStats {
		fmt.Println(rawStat[7], rawStat[8])
		stat, err := ipt.ParseStat(rawStat)
		if err != nil {
			fmt.Println("rawStat: ", rawStat)
			fmt.Println("stat:    ", stat)
			fmt.Println("err:     ", err)
			return nil, err
		}
		structStats = append(structStats, stat)
	}

	return structStats, nil
}

func minimalReproduction(ipt *iptables.IPTables) (iptables.Stat, error) {
	return ipt.ParseStat(
		[]string{
			"1859",
			"112600",
			"MASQUERADE",
			"tcp",
			"--",
			"*",
			"*",
			"192.168.122.0/24",
			"!192.168.122.0/24",
			"masq ports: 1024-65535",
		},
	)
}

func main() {
	ipt, _ := iptables.NewWithProtocol(iptables.ProtocolIPv4)
	fmt.Println("minimalReproduction")
	fmt.Println(minimalReproduction(ipt))
	fmt.Println()
	fmt.Println("testActual")
	fmt.Println(testActual(ipt))
}

Test logs:

sudo $(which go) run ./testnet.go
minimalReproduction
{1859 112600      192.168.122.0/24 <nil> } invalid CIDR address: !192.168.122.0/24%!(EXTRA string=could not parse destination)

testActual
172.19.0.0/16 0.0.0.0/0
172.17.0.0/16 0.0.0.0/0
192.168.122.0/24 224.0.0.0/24
192.168.122.0/24 255.255.255.255/32
192.168.122.0/24 !192.168.122.0/24
rawStat:  [1883 114040 MASQUERADE tcp -- * * 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535]
stat:     {1883 114040      192.168.122.0/24 <nil> }
err:      invalid CIDR address: !192.168.122.0/24%!(EXTRA string=could not parse destination)
[] invalid CIDR address: !192.168.122.0/24%!(EXTRA string=could not parse destination)

Issues when parsing output from NFTables

Running on a system using nftables for firewalling (IPTables version iptables v1.8.0 (nf_tables)), go-iptables causes a slice out of bounds panic while trying to adjust some firewall rules.

Relevant error message (generated by CNI portmap plugin): https://paste.fedoraproject.org/paste/Lt73H2OSbAzJJoc5eNJqRQ

This is seemingly caused by https://github.com/containernetworking/plugins/blob/master/plugins/meta/portmap/chain.go#L80 returning a slice with fewer than 2 entries.

I'm told this is likely a result of an error parsing the output of nftables-backed IPTables which seems to have slightly different field arrangement.

Catch when specific tables are not present

I have been using go-iptables a lot over the last months.
One of the main issues we have is that we use the raw table that is not always present in all distributions.
As such, some API calls fail randomly, and I'm trying to figure out if there is a way in which go-iptables could detect the host capabilities and return the set of tables that could be used ?
Would be happy to submit this as a PR if it is agreed it could be useful.

BUILD file not found in directory 'iptables' of external repository

ERROR: /private/var/tmp/_bazel_ishmeets/a97eed571e7502676f54512ea1625825/external/com_github_containernetworking_plugins/pkg/ip/BUILD.bazel:3:11: no such package '@com_github_coreos_go_iptables//iptables': BUILD file not found in directory 'iptables' of external repository @com_github_coreos_go_iptables. Add a BUILD file to a directory to mark it as a package. and referenced by '@com_github_containernetworking_plugins//pkg/ip:ip'

WORKSPACE

go_repository(
    name = "com_github_coreos_go_iptables",
    importpath = "github.com/coreos/go-iptables",
    sum = "h1:is9qnZMPYjLd8LYqmm/qlE+wwEgJIkTYdhV3rfZo4jk=",
    version = "v0.6.0",
)

When used as a module, does it still require iptables in PATH?

I have used go-iptables as a module (in github.com/pepa65/fail2drop), but I just encountered this message: exec: "iptables": executable file not found in $PATH'. When using go-iptables, does it still require the /usr/sbin/iptables-nft` binary from Netfilter to be present??

Add `GetRuleById()` function

I recently used your package to manage iptables forwards (thanks!).
I would introduce a new function:

func GetRuleById(table string, chain string, id int) error {
    ...
}

This allow you to retrieve a specific rule by passing its number identifier.
The number is retrievable using the following (example) command:

$ sudo iptables -t nat -L PREROUTING -n --line-number
Chain PREROUTING (policy ACCEPT)
num  target     prot opt source               destination         
1    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:29
2    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:22
3    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:25

This is really useful when you need information or need to delete a specific rule.

tryLock() should return an error if it fails to acquire a lock

The documentation of tryLock states that "if the exclusive lock would block (i.e. because another process already holds it), no error is returned". This seems counter-intuitive - if tryLock fails to acquire a lock, shouldn't it return an error, so that the calling function could retry?

Here: https://github.com/coreos/go-iptables/blob/master/iptables/iptables.go#L438 if the file was locked and we failed to acquire a lock, we would still try to run iptables, which might lead to errors. What would you think of returning an error in tryLock if it fails to acquire the lock, and looping over tryLock (at least a few times) here https://github.com/coreos/go-iptables/blob/master/iptables/iptables.go#L438 in case a EWOULDBLOCK error is returned, until it can acquire the lock?

Note: the behaviour of iptables is actually to sleep 1s and try to acquire the lock again: https://git.netfilter.org/iptables/tree/iptables/xshared.c?h=v1.6.0#n260 would you accept a patch to mimic this behaviour?

Add `DeleteById()` function

I would introduce a new function:

func DeleteById(table string, chain string, id int) error {
    ...
}

This allow you to delete a specific rule by passing its number identifier.
The number is retrievable using the following (example) command:

$ sudo iptables -t nat -L PREROUTING -n --line-number
Chain PREROUTING (policy ACCEPT)
num  target     prot opt source               destination         
1    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:29
2    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:22
3    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1242 to:127.0.0.1:25

Redirection for already established TCP connection

I did Podman container live migration to another machine using Podman checkpoint/restore with "--tcp-established" argument. My question: is there a way to redirect an opened TCP connection to the new destination machine? I tested iptables forwarding and ssh tunneling but established tcp client hanged when i installed the forwarding rules. I want to have seamless live migration so already established tcp connection continue on the new server. The client connects to a gateway linux and this gw redirects traffic to the intended server. And when live migration happens, the gateway will redirect the client traffic to the new server location. The client uses the gateway IP as destination IP. This works for new tcp connections but not for already established tcp connections. Usually for Nat or similar there are rules which only react on new connections with syn set. Maybe we need different rules for existing connections (unset syn for established state)?

To make a Linux machine acts as Gateway, i used iptables with the following rules:
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination x.x.x.x:80
iptables -t nat -A POSTROUTING -j MASQUERADE)

x.x.x.x is the destination of the migration ip

Steps to reproduce the issue:

1. Send GET request to a webserver for a big file size
2. In the middle of the transfer, do live migration using commit_cmd = 'sudo podman container checkpoint %s --export=/tmp/%s.tar.gz --tcp-established' % (container, container, )
3. scp /tmp/%s.tar.gz to the destination of migration
4. And restore: restore_cmd = "sudo podman container restore --import=%s%s.tar.gz --tcp-established" % (remote_path, container, )
5. Run the above rules to make the middle man acts as a gateway

Describe the results you received:

I ran tcpdump; it seems there is no redirection happened for already established connection. Redirection only happened for new connections.
Redirection worked for new tcp connections but not for already established tcp connections.
The clients hanged when they are on established tcp state after checkpoint/restore steps.

Describe the results you expected:

Redirection works for established tcp connections. Clients continue the tcp connection with the new migrated server.

Exists() method returns false for existing rule.

I am using go-iptables v0.4.5,
The following function returns false for existing rules.

// Exists checks if given rulespec in specified table/chain exists
func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {

My application is deployed on a node running ubuntu 20.04.1 LTS release.
For the below arg, the exists method return false whereas checking it manually I see it there.
table: filter, Chain: CUSTOM_CHAIN, rule: [-m comment --comment "Comment text" -j ACCEPT]

Also, the List(table, chain) method call works as expected and I am able to find my rule in its return value.

root@test-worker:/# iptables -t filter -C CUSTOM_CHAIN -m comment --comment "Comment text" -j ACCEPT
root@test-worker:/# echo $?
0

iptables 1.8.4 (nf_tables) - Test Failures

Test failures observed for iptables 1.8.4 (nf_tables) on a 4.18 kernel. They appear to just be ordering of the jump and counter args. This appears to have originally been addressed in 5c15b20 (#51), but i'm assuming that a more recent version of iptables has amended this output.

# uname -a
Linux worker-2 4.18.0-425.10.1.el8_7.x86_64 #1 SMP Thu Jan 12 16:32:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

# iptables -V
iptables v1.8.4 (nf_tables)

# go test
--- FAIL: TestRules (0.08s)
    --- FAIL: TestRules/0 (0.02s)
        iptables_test.go:254: testing iptables (hasWait=true, hasCheck=true)
        iptables_test.go:353: ListWithCounters mismatch: 
            got  []string{"-N TEST-195596", "-A TEST-195596 -s 192.0.2.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT", "-A TEST-195596 -s 198.51.100.0/24 -d 203.0.113.2/32 -c 0 0 -j ACCEPT", "-A TEST-195596 -s 198.51.100.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT", "-A TEST-195596 -s 203.0.113.1/32 -d 198.51.100.0/24 -c 0 0 -j ACCEPT"} 
            need []string{"-N TEST-195596", "-A TEST-195596 -s 192.0.2.0/24 -d 203.0.113.1/32 -j ACCEPT -c 0 0", "-A TEST-195596 -s 198.51.100.0/24 -d 203.0.113.2/32 -j ACCEPT -c 0 0", "-A TEST-195596 -s 198.51.100.0/24 -d 203.0.113.1/32 -j ACCEPT -c 0 0", "-A TEST-195596 -s 203.0.113.1/32 -d 198.51.100.0/24 -j ACCEPT -c 0 0"}
    --- FAIL: TestRules/1 (0.02s)
        iptables_test.go:254: testing ip6tables (hasWait=true, hasCheck=true)
        iptables_test.go:353: ListWithCounters mismatch: 
            got  []string{"-N TEST-462060", "-A TEST-462060 -s 2001:db8:a::/48 -d 2001:db8::1/128 -c 0 0 -j ACCEPT", "-A TEST-462060 -s 2001:db8:b::/48 -d 2001:db8::2/128 -c 0 0 -j ACCEPT", "-A TEST-462060 -s 2001:db8:b::/48 -d 2001:db8::1/128 -c 0 0 -j ACCEPT", "-A TEST-462060 -s 2001:db8::1/128 -d 2001:db8:b::/48 -c 0 0 -j ACCEPT"} 
            need []string{"-N TEST-462060", "-A TEST-462060 -s 2001:db8:a::/48 -d 2001:db8::1/128 -j ACCEPT -c 0 0", "-A TEST-462060 -s 2001:db8:b::/48 -d 2001:db8::2/128 -j ACCEPT -c 0 0", "-A TEST-462060 -s 2001:db8:b::/48 -d 2001:db8::1/128 -j ACCEPT -c 0 0", "-A TEST-462060 -s 2001:db8::1/128 -d 2001:db8:b::/48 -j ACCEPT -c 0 0"}
    --- FAIL: TestRules/2 (0.02s)
        iptables_test.go:254: testing iptables (hasWait=true, hasCheck=false)
        iptables_test.go:353: ListWithCounters mismatch: 
            got  []string{"-N TEST-331035", "-A TEST-331035 -s 192.0.2.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT", "-A TEST-331035 -s 198.51.100.0/24 -d 203.0.113.2/32 -c 0 0 -j ACCEPT", "-A TEST-331035 -s 198.51.100.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT", "-A TEST-331035 -s 203.0.113.1/32 -d 198.51.100.0/24 -c 0 0 -j ACCEPT"} 
            need []string{"-N TEST-331035", "-A TEST-331035 -s 192.0.2.0/24 -d 203.0.113.1/32 -j ACCEPT -c 0 0", "-A TEST-331035 -s 198.51.100.0/24 -d 203.0.113.2/32 -j ACCEPT -c 0 0", "-A TEST-331035 -s 198.51.100.0/24 -d 203.0.113.1/32 -j ACCEPT -c 0 0", "-A TEST-331035 -s 203.0.113.1/32 -d 198.51.100.0/24 -j ACCEPT -c 0 0"}
    --- FAIL: TestRules/3 (0.02s)
        iptables_test.go:254: testing ip6tables (hasWait=true, hasCheck=false)
        iptables_test.go:353: ListWithCounters mismatch: 
            got  []string{"-N TEST-814892", "-A TEST-814892 -s 2001:db8:a::/48 -d 2001:db8::1/128 -c 0 0 -j ACCEPT", "-A TEST-814892 -s 2001:db8:b::/48 -d 2001:db8::2/128 -c 0 0 -j ACCEPT", "-A TEST-814892 -s 2001:db8:b::/48 -d 2001:db8::1/128 -c 0 0 -j ACCEPT", "-A TEST-814892 -s 2001:db8::1/128 -d 2001:db8:b::/48 -c 0 0 -j ACCEPT"} 
            need []string{"-N TEST-814892", "-A TEST-814892 -s 2001:db8:a::/48 -d 2001:db8::1/128 -j ACCEPT -c 0 0", "-A TEST-814892 -s 2001:db8:b::/48 -d 2001:db8::2/128 -j ACCEPT -c 0 0", "-A TEST-814892 -s 2001:db8:b::/48 -d 2001:db8::1/128 -j ACCEPT -c 0 0", "-A TEST-814892 -s 2001:db8::1/128 -d 2001:db8:b::/48 -j ACCEPT -c 0 0"}
-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3000
-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3001
-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3002
FAIL

# iptables -v -S TEST-346908
-N TEST-346908
-A TEST-346908 -s 192.0.2.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT
-A TEST-346908 -s 198.51.100.0/24 -d 203.0.113.2/32 -c 0 0 -j ACCEPT
-A TEST-346908 -s 198.51.100.0/24 -d 203.0.113.1/32 -c 0 0 -j ACCEPT
-A TEST-346908 -s 203.0.113.1/32 -d 198.51.100.0/24 -c 0 0 -j ACCEPT

Running test failed

When I try to run test, the following error occurred:

$ SUDO_PERMITTED=1 ./test
Building go-iptables...
Checking gofmt...
Running tests...
--- FAIL: TestChain (0.02s)
	iptables_test.go:107: testing iptables (hasWait=true, hasCheck=true)
	iptables_test.go:107: testing ip6tables (hasWait=true, hasCheck=true)
	iptables_test.go:107: testing iptables (hasWait=false, hasCheck=false)
	iptables_test.go:114: ListChains of Initial failed: exit status 4: Another app is currently holding the xtables lock. Perhaps you want to use the -w option?
--- FAIL: TestRules (0.02s)
	iptables_test.go:185: testing iptables (hasWait=true, hasCheck=true)
	iptables_test.go:185: testing ip6tables (hasWait=true, hasCheck=true)
	iptables_test.go:185: testing iptables (hasWait=false, hasCheck=false)
	iptables_test.go:205: ClearChain (of missing) failed: exit status 4: Another app is currently holding the xtables lock. Perhaps you want to use the -w option?
FAIL
coverage: 74.3% of statements
FAIL	github.com/coreos/go-iptables/iptables	0.050s

Running the failed command directly in terminal works well.

iptables version:

$ iptables --version
iptables v1.6.0

How get --line-numbers ?

I have need get line-number for remove rules,
how get --line-numbers list with detail?

iptables -L --line-numbers

I should how to insert rules with go-iptables

hi ,
I tried insert rule,but I do not what format should be inserted?
go-iptables only get but not insert rules?

version

system version:centos7
golang version:1.15.3

code

func main() {
	ips, err := iptables.New()
	if err != nil {
		panic(err)
	}

	stas, err := ips.StructuredStats("filter", "IN_public_allow")
	if err != nil {
		panic(err)
	}

	fmt.Printf("%#v\n\n	", stas)

	stasstr, err := ips.Stats("filter", "IN_public_allow")

	for _, v := range stasstr {
		if err := ips.Append("filter", "INPUT", v...); err != nil {
			panic(err)
		}
	}

	stasstr, err = ips.Stats("filter", "IN_public_allow")
	if err != nil {
		panic(err)
	}

	fmt.Printf("%#v\n\n	", stasstr)
}

phenomenon

I I tried insert rule,but I do not what format should be inserted?but I tried used Results obtained by go-iptables,but or not insert.

[root@node01 ~]# ./iptables-api 
[]iptables.Stat{iptables.Stat{Packets:0x2, Bytes:0xa8, Target:"ACCEPT", Protocol:"tcp", Opt:"--", Input:"*", Output:"*", Source:(*net.IPNet)(0xc000058870), Destination:(*net.IPNet)(0xc0000588a0), Options:"tcp dpt:22 ctstate NEW,UNTRACKED"}, iptables.Stat{Packets:0x0, Bytes:0x0, Target:"ACCEPT", Protocol:"tcp", Opt:"--", Input:"*", Output:"*", Source:(*net.IPNet)(0xc0000588d0), Destination:(*net.IPNet)(0xc000058900), Options:"tcp dpt:1088 ctstate NEW,UNTRACKED"}}

	panic: running [/usr/sbin/iptables -t filter -A INPUT 2 168 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 ctstate NEW,UNTRACKED --wait]: exit status 2: Bad argument `2'
Try `iptables -h' or 'iptables --help' for more information.


goroutine 1 [running]:
main.main()
	/mnt/d/go_work/src/netlink/main.go:58 +0x488

go-iptables generated format cannot be inserted , it's not iptables cli format? I should how to insert rules with go-iptables?

go-iptables throws panic

2017/04/13 22:29:33 fork/exec /usr/sbin/iptables: cannot allocate memory
panic: interface conversion: error is *os.PathError, not *exec.ExitError

My Fix:

	if err := cmd.Run(); err != nil {
		switch err.(type) {
		default:
			return err
		case *exec.ExitError:
			return &Error{*(err.(*exec.ExitError)), stderr.String()}
		}
	}

Incorrect exit code for ClearChain

These lines claims the exit code is different for the nf_tables mode:

// the exit code for "this table already exists" is different for
// different iptables modes
existsErr := 1
if ipt.mode == "nf_tables" {
existsErr = 4
}

While this might have been the case, with the "current" iptables version the exit code is the same for both modes (1):

/ # ip6tables -V
ip6tables v1.8.2 (nf_tables)
/ # ip6tables -t filter -N DOCKER --wait 
ip6tables v1.8.2 (nf_tables): Chain already exists
/ # echo $?
1

--wait can not set timeout on 1.4.21

func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {

This func check wait.

abea47c
This commit add timeout.

But, version >= 1.6.0, support --wait second, 1.4.21 just support --wait no second.

So,

exit status 2: Bad argument `5'
Try `iptables -h' or 'iptables --help' for more information.
# /usr/sbin/iptables -t filter -N ttttt --wait 5
Bad argument `5'
Try `iptables -h' or 'iptables --help' for more information.
# iptables -h
iptables v1.4.21

The Exist method not work for chain

Seems like the Exist function not work for chain, I have to use ListChains and then find the target in the returned slice to check the existence of some chain. Maybe this is a general usecase, ChainExists?

Panic: when target is empty

❯ iptables -A OUTPUT -d 1.0.0.1
❯ iptables -t filter -L OUTPUT -n -v -x --wait
Chain OUTPUT (policy ACCEPT * packets, * bytes)
    pkts      bytes target     prot opt in     out     source               destination
       0        0            tcp  --  *      *       0.0.0.0/0            1.0.0.1

Like this traget is empty, so len(fiels[]) == 8 in now.

fields[8] = appendSubnet(fields[8])

StructuredStats fails to parse negated source/dest CIDRs

I have the following chain:

target     prot opt source               destination         
RETURN     all  --  anywhere             192.168.0.0/16      
RETURN     all  --  anywhere             172.16.0.0/12       
RETURN     all  --  anywhere            !127.0.0.0/8    

Invoking StructuredStats returns the following error:

invalid CIDR address: !127.0.0.0/8%!(EXTRA string=could not parse destination)

filelock generate too many open files

I have to refresh iptable frequently, on suse11 which iptables version is iptables v1.4.16.

It will open filelock /var/run/xtables.lock each time when I do the update, but the filelock wasn't really closed, after a few days it shows too many files open and failed. How could I close these filelocks?

[BUG] Prepending iptables path to list of args in `runWithOutput` makes some methods fail unexpectedly

Description of the issue

It seems like in the function runWithOutput the iptables path is erroneously prepended to the list of args, resulting in some methods failing unexpectedly, as in the example below. I've only tested Exists so far. The solution is to simply remove the prepended iptables path, everything seems to work correctly this way.

func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
args = append([]string{ipt.path}, args...)

Then further down in the same function:

cmd := exec.Cmd{
Path: ipt.path,
Args: args,
Stdout: stdout,
Stderr: &stderr,
}

How to reproduce

Example:

package main

import (
	"bytes"
	"fmt"
	"os/exec"

	"github.com/coreos/go-iptables/iptables"
)

func main() {
	const setName = "some-unexisting-set"
	const filterTableName = "filter"

	ipv4, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
	if err != nil {
		panic(err)
	}

	fmt.Println("Using go-iptables:")
	_, err = ipv4.Exists(filterTableName, "INPUT", "-m set --match-set", setName, "src", "-j DROP")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println()
	fmt.Println("Using exec.Command without repetition:")
	var stdout, stderr bytes.Buffer
	cmd := exec.Command("/usr/sbin/iptables", "-t", filterTableName, "-C", "INPUT", "-m", "set", "--match-set", setName, "src", "-j", "DROP", "--wait")
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		fmt.Printf("running %v: exit status %v: %v", append([]string{"/usr/sbin/iptables"}, cmd.Args...), cmd.ProcessState.ExitCode(), stderr.String())
	}
}

Output:

Using go-iptables:
cmd /usr/sbin/iptables [/usr/sbin/iptables -t filter -C INPUT -m set --match-set some-unexisting-set src -j DROP --wait]
running [/usr/sbin/iptables -t filter -C INPUT -m set --match-set some-unexisting-set src -j DROP --wait]: exit status 2: iptables v1.8.4 (legacy): Couldn't load match ` set --match-set':No such file or directory

Try `iptables -h' or 'iptables --help' for more information.


Using exec.Command without repetition:
running [/usr/sbin/iptables /usr/sbin/iptables -t filter -C INPUT -m set --match-set some-unexisting-set src -j DROP --wait]: exit status 2: iptables v1.8.4 (legacy): Set some-unexisting-set doesn't exist.

Try `iptables -h' or 'iptables --help' for more information.

Please note "Couldn't load match ` set --match-set':No such file or directory" vs "Set some-unexisting-set doesn't exist." in the error.

How do I set FORWARD policy with this lib?

When I want set FORWARD policy of filter, I find that IPTables struct have no method can do it.

Should we add some method to set policy?

or

Change private method run to public.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.