Code Blog

Displaying 1-1 of 1 result.
2016/04/03 Network

Linux comes with a built-in firewall called IPTables. It has 3 default chains - INPUT, OUTPUT and FORWARD.

Input chain Coming from outside the firewall to destination inside the firewall
Output chain From inside the firewall going to outside the firewall
Forward chain Routing through the firewall (coming from the outside the firewall passing on to outside the firewall) 

 IPTables rules are normally put in a script file and run during start-up. Each chain will need to have a default policy (set with -P, see example below). The default policy for a chain can be either DROP or ACCEPT. 

Usage Examples:

iptables -P INPUT DROP // Set policy for chain to deny connections (drop packets)

iptables -A INPUT -p tcp --dport 8080 -j ACCEPT   // Add rule to end of chain: Accept incoming tcp connections at port 8080

iptables -A INPUT -j SHADOWSOCKS // Add to end of chain: Jump from Input chain to Shadowssocks chain (and will automatically go back to Input chain after finishing Shadowsocks rules)  

 Nat table (network address translation)

 iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080 // Redirect incoming tcp traffic from port 80 to port 8080

 iptables -I INPUT -j SHADOWSOCKS // Insert at beginning of Input chain

// Count traffic coming in/out from 192.168.0.117

iptables -A FORWARD -s 192.168.0.117

iptables -A FORWARD -d 192.168.0.117 

iptables -nvx -L FORWARD // Print traffic counters

iptables -Z  // Clear all counters (for all rules)

iptables -Z FORWARD // Clear counters for Forward rule

iptables -R FORWARD 1 -s 192.168.0.117 // Replace rule nr 1 in Forward chain with same rule. This will reset counter

iptables -I FORWARD -i eth0 -j TRAFFIC_ACCT_IN // incoming interface eth0

iptables -I FORWARD -o eth0 -j TRAFFIC_ACCT_OUT // outgoing interface eth0

iptables -vnxL FORWARD | awk '{print $2}' // print the 2nd column

iptables -vnxL FORWARD | awk '/delegate_forward/ {print $2}' // Print 2nd word in line that contains 'delegate_forward' text

The important rules regarding NAT are found in the 'nat'-table. This table has three predefinded chains: PREROUTING, OUTPUT und POSTROUTING.

 

// How is Shadowsocks set-up? I want to count the total traffic going through the router, but I also want to count the amount of data sent through Shadowsocks tunnel. The Shadowsocks tunnel is listening at port 1080. 

iptables -N SHADOWSOCKS // Create new chain with name "Shadowsocks"

iptables -A INPUT -j SHADOWSOCKS

iptables -A SHADOWSOCKS -p tcp // Count all incoming traffic

iptables -A SHADOWSOCKS -p tcp -dport 1080 // Does this work?

iptables -L SHADOWSOCKS -n -v -x // Display traffic data for Shadowsocks chain

The -x flag means you will get the exact value of the packet and byte counters, instead of only the rounded number in K’s (multiples of 1000) M’s (multiples of 1000K) or G’s (multiples of 1000M).