Search code examples
c#asp.net-web-api.net-6.0iptables

How to add rule with IPTables.Net to iptables in real system with .NET 6 Web API


I have a .NET 6 Web API application and I want to edit my iptables rule in hosted system. (the system that Web API run on it)

I have rule like below

-A INPUT -m tcp  --protocol tcp --source 2.2.2.2 --destination 1.1.1.1 --source-port 111 --destination-port 222 --jump DROP

I try this rule in iptables command in bash and work correctly, but when I try to create rule for this like below

IpTablesRule rule = IpTablesRule.Parse($"-A  INPUT  -m tcp--protocol tcp --source 2.2.2.2 --destination 1.1.1.1 --source-port 111 --destination-port 222 --jump DROP", null, chains);

and then try to add to system like below

ipTablesSystem = new IpTablesSystem(system: new LocalFactory(), tableAdapter: new IPTablesBinaryAdapter());
inputChain = ipTablesSystem.GetChain(table: Table.FILTER, chain: Chain.INPUT, ipVersion: (int)IpVersion.V4);
inputChain.AddRule(rule);

No any error rise on system or something like that, but after I try to see system rules with bash (cli) with iptables -L I do not see my rules

Why my rule does not exist in system? and how to resolve this problem?


Solution

  • This is for bad using of API, the correct way is like below

    IpTablesRule rule = IpTablesRule.Parse($"-A  INPUT  -m tcp --protocol tcp --source 2.2.2.2 --destination 1.1.1.1 --source-port 111 --destination-port 222 --jump DROP", null, chains);
    
    var ipTablesSystem = new IpTablesSystem(system: new LocalFactory(), tableAdapter: ipTablesAdapter);
    
    IIPTablesAdapterClient table = ipTablesSystem.GetTableAdapter((int)IpVersion.V4);
    
    table.AddRule(rule);
    

    The note is, you must get table from IpTablesSystem and add or remove rulse from table.