CCNA HUB

CCNA and Linux Training Hub!

CCNA and Linux Training Hub!

  • Home
  • R&S
    • IP Fundamentals
    • Switching
    • Routing
    • IPv4 Suite
    • IPv6 Suite
    • Labs
  • Linux
    • Virtualization 101
    • Basic Configuration
    • Security Measures
    • Database Server
    • Web Server
    • HTTP Tuneup
    • FTP Server
    • Mail Server
    • DNS Server
    • Control Panels
    • Monitoring
    • Backup and Maintenance
  • WordPress
  • About
    • Contact Us
    • Be part of It
    • Under the Hood
CCNA HUB > Blog > Linux > Linux Hardening Rules and IPtables Firewall > Implementing Stateful Firewall Using IPtables

Implementing Stateful Firewall Using IPtables

By Imad Daou Leave a Comment

Post Views: 5,651

Building Professional Web Hosting Solution
<< Securing and Protecting Linux System Course
>> Linux Hardening Rules and IPtables Firewall Section

section table
  1. Preparing Linux Script Startup Environment
  2. Applying Linux Kernel Hardening Rules
  3. Applying System and Network Tuneup Rules
  4. Implementing Stateful Firewall Using IPtables
  5. Redirecting IPtables Firewall Logging Location
  6. Testing IPtables using Nmap Scanning Tool
  7. Logging and Trapping Port Scanning Tools
Image Source
Image Source

Implementing Stateful Firewall Using IPtables is the most known way to protect Linux systems. As you probably know, there are too many ways to apply IPtables Firewall Rules, my favorite is to use a bash Script. Below, I will show you how easy to apply Stateful Firewall on your VPS using well structured script especially crafted for Web Hosting Solution Servers; tested and verified to work on Single VPS.

Objectives:

1. Preparing IPtables Firewall Environment

2. Applying IPtables Stateful Firewall Rules

3. Verifying and Adding IPtables to Startup

Prerequisites:

A. Basic Debian or Red Hat System Knowledge

B. Login to your DigitalOcean or Vultr Account

C. Preparing Linux Script Startup Environment

D. Applying Linux Kernel Hardening Rules

E. Applying System and Network Tuneup Rules

Recommendations:

1. For better performance, use VPS with at least 2 CPUs, 4G Memory, 1G Bandwidth, and SSD Storage drive.

2. All public VPS Nodes must equipped with Web command line Interface, hence, login to the web interface and have it ready in case you need to stop the Firewall. Everything was tested and it should not lock you out or terminate the SSH session, but just to be on the safe side, have the web command line interface ready.

Table of Contents

  • Preparing IPtables Firewall Environment
  • Applying IPtables Stateful Firewall Rules
  • Verifying and Adding IPtables Script to Startup

Preparing IPtables Firewall Environment

After creating the IPtables Firewall Script, make sure your VPS ready for IPtables Firewall before running the script.

Run the following steps (1 to 5)

1. Create IPtables Workspace Folder

Note: If you already created the iptables directory, you can skip this step.

mkdir -p /etc/network/iptables

2. Create IPtables Firewall Script

nano /etc/network/iptables/iptfw4and6-single-node.sh

Click the following IPtables Firewall Script to open it, select all content, copy, and paste it inside the newly created script iptfw4and6-single-node.sh ssh window.

Note: It depends on your security needs, either Version will work. Version 2 is more restrictive if needed.

Type 1 >> No Outgoing Restriction

IPtables Firewall Single Node Script Type1 V1

Type 2 >> Outgoing Restriction

IPtables Firewall Single Node Script Type2 V1

As mentioned, modify if needed and Save the file.

Ctrl-X, Hit Y Key, and Enter to close.

3. Create Stop Firewall Script

nano /etc/network/iptables/stopfw.sh

Same thing, click the following “Stop IPtables Firewall Script”, copy and paste its content inside the newly created script stopfw.sh ssh window.

Stop IPtables Firewall Script

Save: Ctrl-X, Hit Y Key, and Enter

4. Allow Only root access to the Scripts

chmod 700 -R /etc/network/iptables

5. Have the Stop Firewall Script Ready

Every Public VPS comes with Web Console Interface. VMware Station and VirtualBox comes with their own console window as well. Have the console open and ready in case you need to stop the firewall. Type the following command at the console.

/etc/network/iptables/stopfw.sh

Test it, run stopfw.sh script from the web Console interface or VirtualBox Window to make sure it’s working.

/etc/network/iptables/stopfw.sh
Stopping firewall and allowing everyone...

Before you Apply IPtables Script

Using DigitalOcean or Vultr VPS, the script should work just fine without any adjustment, however, confirm the following requirements before applying the script. You might need to edit the IPtables Script again as needed if required before applying the Script.

a. Is it OpenVZ VPS or KVM VPS?

DigitalOcean VPS or Vultr VPS are based on KVM that use “ethx” label for network interface which the default in the script. VPS that are based on OpenVZ, they use “venetx” for labeling instead. If you are using OpenVZ base VPS, you need to comment eth0 line and comment out venet0 line inside the IPtables Firewall Script before applying. Use ifconfig or ip addr command to determine your interface name. If you see venet0 in the output, then it’s OpenVZ VPS.

Those are the IPtables interface identification rules inside IPtables Script

After you edit the IPtables script, press Ctrl-w to search for “PUB_IF” – don’t include quotes.

PUB_IF="eth0" # Public Ethernet Card that is connected to the Internet
#PUB_IF="venet0" # Public Ethernet Card that is connected to the Internet

Note: eth0 is selected by default inside the script. However, always run ifconfig command at the command line to make sure that you are using the proper interface name inside the script. For instance, Vultr Ubuntu16.04 uses “ens3” instead of “eth0” label for the interface name. So you need to replace “eth0” inside the script using “ens3” like such:

PUB_IF="ens3" # Public Ethernet Card that is connected to the Internet

b. Using Proper Interface number

In most cases, Public VPS uses “eth0” as main Internet connection. In case your Public VPS uses different number, then you need to adjust the Firewall Script as needed to reflect proper (ethx) number before applying. E.g., eth1, eth2, or it might be venet1, venet2, and so on.

c. IPv4 Spoofing Countermeasures Section

Make sure you run command ifconfig to show the Interface name and IP address, note this information down. Edit the IPtables firewall script, press Ctrl-w to search for “IPv4 Spoofing” don’t include the quotes, and adjust the “SERTVERADDR” field if 1) Your VPS uses different interface name, 2) You are using Red Hat Based system then you need specify the VPS Public IP.

After you edit the IPtables script, press Ctrl-w and search for “IPv4 Spoofing” – don’t include quotes.

Debian Based

Unless you are using OpenVZ, or a VPS that uses different ethernet number, then default setting below should be fine for Debian Based.

SERVERIPADDR=$(ifconfig eth0 | grep 'inet addr:' | awk -F'inet addr:' '{ print $2}' | awk '{ print $1}')

Note: Vultr Ubuntu16.04 uses “ens3” instead of “eth0” label for the interface name. So you need to replace “eth0” inside the script using “ens3” like such:

SERVERIPADDR=$(ifconfig ens3 | grep 'inet addr:' | awk -F'inet addr:' '{ print $2}' | awk '{ print $1}')

Red Hat Based

For Red Hat Based systems, using the following command to grap IP address under spoofing rules:

CenOS6

SERVERIPADDR=$(ifconfig eth0 | grep 'inet addr:' | awk -F'inet addr:' '{ print $2}' | awk '{ print $1}')

CentOS7

SERVERIPADDR=$(ifconfig eth0 | grep 'inet ' | awk -F'inet ' '{ print $2}' | awk '{ print $1}')

Or specify your VPS Public IP Address instead.

SERVERIPADDR=162.243.96.168 >> Replace this IP using your VPS IP.

d. Private Network

For those who are testing this article inside a Private Network Environment such VirtualBox or VMware Station, you need to comment 2 lines under spoofing, otherwise the firewall will block SSH when you attempt to reconnect.

So, to disable the spoofing feature for Class C network, scroll down little bit more and under “Block packets claiming to be from a Class C private network” comment the following IPtables 2 lines as shown below using the hash sign.

# Drop packets claiming to be from a Class C private network.
#$IPT -A INPUT -i $PUB_IF -s $CLASS_C -j LOG --log-prefix "IPT Spoofing as-Class-C IP: " --log-level 7
#$IPT -A INPUT -i $PUB_IF -s $CLASS_C -j DROP

Again, I am assuming that you are using Public KVM VPS machine, then you don’t need to disable Class C network Spoofing.

e. Enable xt_recent Module

If you applied the previous Lab, then you don’t need to worry about enabling xt_recent module, jump to the next step. However, if you haven’t, then the following xt_recent Module rules required for IPtables to work properly, or you will face errors when you apply the the script.

For Debian and Red Hat Based systems, make sure the following 2 rules applied at the startup before the IPtables Firewall Script.

echo 255 > /sys/module/xt_recent/parameters/ip_pkt_list_tot
echo 5000 > /sys/module/xt_recent/parameters/ip_list_tot

Note: if you are using Ubuntu16.04, please use the following rules instead.

# Enable only if you are using Ubuntu 16.04 Linux.
modprobe -r xt_recent
modprobe xt_recent ip_pkt_list_tot=255
modprobe xt_recent ip_list_tot=5000

f. Is IPtables Services Installed?

Most Public VPS providers have their VPS instances ready with IPtables firewall and had disabled firewalld for you. But if you are using Private VM, most probably you will need the following steps below only for CentOS7 before you apply the IPtables script. In either case, it ‘s good to check your Public VPS as well. If you are using Systemd base system such Debian8, Ubuntu16.04, or CentOS7, then most probably you have to make sure firewalld is disabled first and IPtables package is installed.

Make sure Firewalld Service disabled

For Systemd Based Only

systemctl stop firewalld.service

Note: If it shows: “Failed to stop firewalld.service: Unit firewalld.service not loaded“. Then jump to creating IPtables Script.

Disable and Mask Firewalld

systemctl disable firewalld.service

Check Firewalld Status

firewall-cmd --state
[[email protected] ~]# firewall-cmd --state
not running

Remove Firewalld

yum remove firewalld -y

Check if IPtables Installed

Debian Based

apt-get install iptables

Red Hat Based

yum install iptables-services net-tools

Enable IPtables Firewall

systemctl enable iptables

After making sure that all above requirements are met, now you can create the IPtables Firewall script.

Applying IPtables Stateful Firewall Rules

Run the following steps (1 to 9)

1. List IPtables Rules

iptables -L -nvx

Usually, it’s empty similar to the following:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

2. Check if VPS IPv6 Ready

[ -f /proc/net/if_inet6 ] && echo 'IPv6 ready system!' || echo 'No IPv6 support found! Upgrade your kernel!!'

Or ping ipv6 google using ping6 command

ping6 ipv6.google.com

Ctrl-c to end pining command.

3. List IP6tables Rules

ip6tables -L -nvx

It might be empty as well as follows:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Note: Even if your VPS got no IPv6 connection, still the IP6tables Firewall Rules can be applied.

8. Now Enable the Firewall

Run the following command from SSH session:

/etc/network/iptables/iptfw4and6-single-node.sh

Make sure the Firewall started with no errors, you should see something similar to the following:

Note: if your SSH window get disconnected, that’s fine, wait few seconds and reconnect again. Re-apply the script again to make sure it was applied properly as shown.

####                                                      ####
#    Preparing IPtables v4 and v6 Script for Single VPS...   #
####                                                      ####

 [+] Enabling IPTables v4 and v6 Firewall Rules...

 [+] Setting Global Policy: Dropping All IPv4/IPv6 Traffic...

 [+] Setting Stateful INPUT/OUPUT IPtables Firewall Rules...

 [+] Setting Rules Against TCP and UDP Port Scanning...

 [+] Setting Rules Against IPv4 Finger Printing...

 [+] Setting Rules Against Denial Of Service Attacks...

 [+] Allowing SSH Access with Brute Force Protection...

 [+] Allowing TCP or UDP Services such HTTP, HTTPS, and FTP...

 [+] Stateful IPtables Firewall Rules have been successfully Loaded!

9. Set IPv4 DNS Resolve over IPv6

Note: I noticed sometime SSH connection takes few more seconds than normal to fully establish if IPv6 enabled at the VPS and other connection issues when running apt-get update/yum update, therefore, based on this thread https://www.digitalocean.com/community/questions/how-to-disable-ubuntu-14-04-ipv6 configure IPv4 over IPv6 DNS resolve to solve these issues.

a. Edit Get Address Info file

nano /etc/gai.conf

b. Comment out precedence ::ffff:0:0/96

From:

#precedence ::ffff:0:0/96  10

To:

precedence ::ffff:0:0/96  10

Verifying and Adding IPtables Script to Startup

Run the following steps (1 to 2)

1. Show the IPtables Firewall Rules

iptables -L -nvx | less

And

ip6tables -L -nvx | less

You should see IPtables Rules listed. Press Space to move to next page, or q key to close less command.

Or Watch them LIVE!

watch iptables -L -nvx

Or

watch ip6tables -L -nvx

Ctrl-c to terminate watch command.

2. Add IPtables to Startup

Note: Although the persistent iptables rules will save and restore iptables rules, however, I recommend adding firewall script to startup as well.

nano /etc/init.d/custom-scripts.sh
#!/bin/bash
### BEGIN INIT INFO
# Provides:          custom-scripts
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: custom-scripts
# Description:       Applying Customized Startup Scripts
### END INIT INFO
echo
echo "Applying Customized Startup Scripts..."
echo
#################################################
# Write down your script's path below
# Kernel Hardening Rules
/etc/network/iptables/kernel-hardening-rules.sh
# Loading IPtables Firewall Modules 
/etc/network/iptables/iptables-modules-check.sh
# System and Network Tuneups 
/etc/network/iptables/system-and-network-tuneup.sh
# IPTables 4 and 6 Firewall Script
/etc/network/iptables/iptfw4and6-single-node.sh

Save: Ctrl-X, Hit Y Key, and Enter

By Linux IPtables Firewall by Arch | Debian IPtables Firewall | CentOS IPtables Firewall

Subject Related

Building Professional Web Hosting Solution
<< Securing and Protecting Linux System Course
>> Linux Hardening Rules and IPtables Firewall Section

section table
  1. Preparing Linux Script Startup Environment
  2. Applying Linux Kernel Hardening Rules
  3. Applying System and Network Tuneup Rules
  4. Implementing Stateful Firewall Using IPtables
  5. Redirecting IPtables Firewall Logging Location
  6. Testing IPtables using Nmap Scanning Tool
  7. Logging and Trapping Port Scanning Tools
  • Was this information helpful?
  • Yes(0)   No(0)
Get Linux Updates!

tux_toilet

Filed Under: Linux, Linux Hardening Rules and IPtables Firewall Tagged With: Linux Security, IPtables Firewall

About Imad Daou

CCNA HUB Founder, Imad has been in IT field since 2007. Currently holding A+, Network+, Server+, Security+, and Storage+. HP, Dell, and IBM Hardware Certified. Pursuing Linux+, LPIC-2, RHCSA, RHCE, AWS, CCNA, and JNCIA.

LEAVE A COMMENT Cancel reply

We're glad you have chosen to leave a comment. All comments are moderated according to our comment policy. Use your real name and not keywords in the name field. Let's have a personal and meaningful conversation.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

Get CCNA HUB Updates!

MISSION

CCNA, Linux, and Wordpress Training Hub. For Students, Network Pros, DevOps, Linux/Wordpress Lovers, and Entrepreneurs. CCNA HUB Articles and Labs will help you build a solid foundation in Network, Linux, and Wordpress. E.g. Linux WHS will show you how to build a Professional Web Hosting Solution using DigitalOcean or Vultr VPS provider.

TAG CLOUD

transmission control protocol sudo wide area network TCP wordpress.org CMS Wordpress Hosting Hub WAN switches VPS Hosting transport layer protocols SSH Agent Forwarding transport layer su T1 subnet mask tcp sockets VLSM virtual circuit understanding Routing udp sockets Wordpress Multisite wordpress CMS SSH Client TCP/IP understanding switching

RSS UPDATES

  • IP Fundamentals
  • CCNA R&S
  • CCNA Labs
  • Linux WHS
  • Wordpress
  • All CCNA HUB Topics

Copyright © 2022 ·Genesis Sample Theme - Genesis Framework by StudioPress - WordPress - Log in

This website uses cookies. By continuing to browse the site, you are agreeing to our use of cookies
  • Home
  • R&S
    • IP Fundamentals
    • Switching
    • Routing
    • IPv4 Suite
    • IPv6 Suite
    • Labs
  • Linux
    • Virtualization 101
    • Basic Configuration
    • Security Measures
    • Database Server
    • Web Server
    • HTTP Tuneup
    • FTP Server
    • Mail Server
    • DNS Server
    • Control Panels
    • Monitoring
    • Backup and Maintenance
  • WordPress
  • About
    • Contact Us
    • Be part of It
    • Under the Hood