Archive

Articles taggués ‘netfilter’

Simple stateful firewall

29/09/2023 Comments off

Source: archlinux.org

This page explains how to set up a stateful firewall using iptables. It also explains what the rules mean and why they are needed. For simplicity, it is split into two major sections. The first section deals with a firewall for a single machine, the second sets up a NAT gateway in addition to the firewall from the first section.

Warning: The rules are given in the order that they are executed. If you are logged into a remote machine, you may be locked out of the machine while setting up the rules. You should only follow the steps below while you are logged in locally.The example config file can be used to get around this problem.

Prerequisites

Note: Your kernel needs to be compiled with iptables support. All stock Arch Linux kernels have iptables support.

First, install the userland utilities iptables or verify that they are already installed.

This article assumes that there are currently no iptables rules set. To check the current ruleset and verify that there are currently no rules run the following:

# iptables-save
# Generated by iptables-save v1.4.19.1 on Thu Aug  1 19:28:53 2013
*filter
:INPUT ACCEPT [50:3763]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [30:3472]
COMMIT
# Completed on Thu Aug  1 19:28:53 2013

or

# iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 156 packets, 12541 bytes)
num   pkts bytes target     prot opt in     out     source               destination

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

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

If there are rules, you may be able to reset the rules by loading a default rule set:

# iptables-restore < /etc/iptables/empty.rules

Otherwise, see Iptables#Resetting rules.

Lire la suite…

Iptables Firewall

25/09/2023 Aucun commentaire

Source: tty1.netthere

This page presents a simple firewall script. It is probably not the best of all possible firewalls, nor the most secure, but may be a starting point for your experiments. Please send any comments and suggestions to <tehpeh-web@tty1.net>.

Update 2011-05-28: IPv6 script

Please see the page for a newer firewall script with IPv6 support.

Turning on native Kernel IPv4 protection

The Linux kernel provides some basic protections against manipulated IP packets. A configuration could be:

echo 1 > /proc/sys/net/ipv4/tcp_syncookies                          # enable syn cookies (prevent against the common 'syn flood attack')
echo 0 > /proc/sys/net/ipv4/ip_forward                              # disable Packet forwarning between interfaces
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts             # ignore all ICMP ECHO and TIMESTAMP requests sent to it via broadcast/multicast
echo 1 > /proc/sys/net/ipv4/conf/all/log_martians                   # log packets with impossible addresses to kernel log
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses       # disable logging of bogus responses to broadcast frames
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter                      # do source validation by reversed path (Recommended option for single homed hosts)
echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects                 # don't send redirects
echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route            # don't accept packets with SRR option

Further reading:

  • The file Documentation/networking/ip-sysctl.txt in your kernel source directory
  • Network Security with /proc/sys/net/ipv4

Limit ping responses

Any iptables rule can be tuned to respond only to a limited number of times per time unit by using the limit module. This can be extremely useful for log entries (A ping flooding will not lock down your computer by writing to log files). I will show an example on how to limit on ICMP responses. This is not really useful, because it imposes a maximum number of responses for ALL source IP addresses, but it may help to reduce network traffic on brute force attacks (and reduce volume in the log file).

iptables -A INPUT  -p icmp -m limit --limit 10/second -j ACCEPT
iptables -A INPUT  -p icmp -j DROP

This will limit the ICMP responses to a maximum of 10 replies per second. All the rest is silently dropped. Beware: dropping ICMP responses may slow down or cut off legitimate users (for example when ICMP “Fragmentation Needed” packets are dropped).

Dealing with brute force ssh attacks

A stateful firewall can make brute force ssh scans more painful to the attacker by slowing down the responses. I will present a simple teergrubing strategy against ssh scans. This method relies on the IPTables/Netfilter Recent Module, written by Snow-man. The idea is simple: permit only a limited number of new connections per source IP address; drop any further connection attempt for a while.

iptables -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 60 --hitcount 2 --name SSH -j LOG --log-prefix "SH "
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 2 --name SSH -j DROP
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH -j ACCEPT
iptables -A INPUT  -i $int_if -m state --state ESTABLISHED,RELATED -j ACCEPT

Line 1 of the script checks if the source IP has already marked as ‘Bad Guy’ and logs the packet, if so. The second line drops the packet if it comes from a marked IP address and marks the source again. This ensures that the source will stay blacklisted as long as the attack continues. The third line marks the source IP as ‘Bad Guy’ if there are more than 2 connection attempts per minute. Note that already established connections continue to work (because the packets will no more arriving on 22).

Further reading:

Lire la suite…

Communication Networks/IP Tables

22/09/2023 Comments off

Operational summary

The netfilter framework, of which iptables is a part of, allows the system administrator to define rules for how to deal with network packets. Rules are grouped into chains—each chain is an ordered list of rules. Chains are grouped into tables—each table is associated with a different kind of packet processing.

Each rule contains a specification of which packets match it and a target that specifies what to do with the packet if it is matched by that rule. Every network packet arriving at or leaving from the computer traverses at least one chain, and each rule on that chain attempts to match the packet. If the rule matches the packet, the traversal stops, and the rule’s target dictates what to do with the packet. If a packet reaches the end of a predefined chain without being matched by any rule on the chain, the chain’s policy target dictates what to do with the packet. If a packet reaches the end of a user-defined chain without being matched by any rule on the chain or the user-defined chain is empty, traversal continues on the calling chain (implicit target RETURN). Only predefined chains have policies.

Rules in iptables are grouped into chains. A chain is a set of rules for IP packets, determining what to do with them. Each rule can possibly dump the packet out of the chain (short-circuit), and further chains are not considered. A chain may contain a link to another chain – if either the packet passes through that entire chain or matches a RETURN target rule it will continue in the first chain. There is no limit to how many nested chains there can be. There are three basic chains (INPUT, OUTPUT, and FORWARD), and the user can create as many as desired. A rule can merely be a pointer to a chain.

Tables

There are three built-in tables, each of which contains some predefined chains. It is possible for extension modules to create new tables. The administrator can create and delete user-defined chains within any table. Initially, all chains are empty and have a policy target that allows all packets to pass without being blocked or altered in any fashion.

  • filter table — This table is responsible for filtering (blocking or permitting a packet to proceed). Every packet passes through the filter table. It contains the following predefined chains, and any packet will pass through one of them:
    • INPUT chain — All packets destined for this system go through this chain (hence sometimes referred to as LOCAL_INPUT)
    • OUTPUT chain — All packets created by this system go through this chain (aka. LOCAL_OUTPUT)
    • FORWARD chain — All packets merely passing through the system (being routed) go through this chain.
  • nat table — This table is responsible for setting up the rules for rewriting packet addresses or ports. The first packet in any connection passes through this table: any verdicts here determine how all packets in that connection will be rewritten. It contains the following predefined chains:
    • PREROUTING chain — Incoming packets pass through this chain before the local routing table is consulted, primarily for DNAT (destination-NAT).
    • POSTROUTING chain — Outgoing packets pass through this chain after the routing decision has been made, primarily for SNAT (source-NAT).
    • OUTPUT chain — Allows limited DNAT on locally-generated packets
  • mangle table — This table is responsible for adjusting packet options, such as quality of service. All packets pass through this table. Because it is designed for advanced effects, it contains all the possible predefined chains:
    • PREROUTING chain — All packets entering the system in any way, before routing decides whether the packet is to be forwarded (FORWARD chain) or is destined locally (INPUT chain).
    • INPUT chain — All packets destined for this system go through this chain
    • FORWARD chain — All packets merely passing through the system go through this chain.
    • OUTPUT chain — All packets created by this system go through this chain
    • POSTROUTING chain — All packets leaving the system go through this chain.

In addition to the built-in chains, the user can create any number of user-defined chains within each table, which allows them to group rules logically.

Each chain contains a list of rules. When a packet is sent to a chain, it is compared against each rule in the chain in order. The rule specifies what properties the packet must have for the rule to match, such as the port number or IP address. If the rule does not match then processing continues with the next rule. If, however, the rule does match the packet, then the rule’s target instructions are followed (and further processing of the chain is usually aborted). Some packet properties can only be examined in certain chains (for example, the outgoing network interface is not valid in the INPUT chain). Some targets can only be used in certain chains, and/or certain tables (for example, the SNAT target can only be used in the POSTROUTING chain of the nat table).

Lire la suite…

Simple Stateful Load Balancer with iptables and NAT

21/09/2023 Comments off

To demonstrate how iptables can perform network address translation this how-to shows how to use it to implement a over-simplified load balancer. In practice we would use a daemon such as HAProxy allowing IP tables to check packets before forwarding them.

Using the method presented in this tutorial packets get forwarded without going through the INPUT, FORWARD and OUTPUT chains.

iptables is a powerful tool that is used to create rules for how incoming or outgoing packets are handled. It keeps track of a packets state – there is NEW, ESTABLISHED, RELATED, INVALID and UNTRACKED. It can make filtering decisions based on the packets header data and the payload section of the packet, for these purposes iptables even has regular expression matching.

On top of that iptables has extensions that can be used to filter packets based on a packets history so we can keep track of packets and sessions. We can set filters to only trigger at specific times, parse the packet contents and header information searching for specific patterns, differentiate protocols such as tcp, udp, icmp, etc.

For load balancing behavior we want the incoming packets on one machine to be routed to another machine. iptables has extentions that helps us achieve this aim but we also need to muck around with its internal PREROUTING and POSTROUTING table, which is not recommended as this could potentially pose a security risk. lets use iptables to route all traffic coming in on an interface eth0 with a destination port 80 and route it to another IP address:

Allow IP forwarding

(Note: if your testing this on the same box your doing this on it won’t work, you need at least 3 machines to test this out, virtual ones work nicely)

First we enable ipv4 forwarding or this will not work:
# echo "1" > /proc/sys/net/ipv4/ip_forward

XOR

# sysctl net.ipv4.ip_forward=1

next we add a filter that changes the packets destination ip and allows us to masquerade:

# iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 10.0.0.3:80
# iptables -t nat -A POSTROUTING -j MASQUERADE

The above filter gets added to iptables PREROUTING chain. The packets first go through the filters in the PREROUTING chain before iptables decides where they go. The above filter says all packets input into eth0 that use tcp protocol and have a destination port 80 will have their destination address changed to 1.2.3.4 port 80. The DNAT target in this case is responsible for changing the packets Destination IP address. Variations of this might include mapping to a different port on the same machine or perhaps to another interface all together, that is how one could implement a simple stateful vlan (in theory).

The masquerade option acts as a one to many NAT server allowing one machine to route traffic with one centralized point of access. This is similar to how many commercial firewalls and network routers function.

The above ruleset results in all incoming packets to dport 80 traversing the iptables chains in a straight line from INCOMING to OUTGOING in the image below, effectively bypassing any rules we might have had in our INPUT chain. If we were to choose to implement nat like this we would need to implement those – our desired INPUT filter rules – on the machines where traffic is forwarded OR add them to the FORWARD chain if we want to block things before they are forwarded (Note: packets might go through FORWARD chain in both directions so direction needs to be considered when writing filters for this chain).

560x260xbuilt-in-chains-in-filter-table.png.pagespeed.ic.CVAYVeFJ96

Path incoming packets take through iptables chains

Lire la suite…

Advanced Features of netfilter/iptables

14/09/2023 Comments off

Source: linuxgazette.net

Introduction

It is commonly known that netfilter/iptables is the firewall of the Linux operating system. What is not commonly known is that iptables has many hidden gems that can allow you do things with your firewall that you might never have even imagined. In this article I am going to introduce many of these features with some practical uses. If you are not au fait with the basics of iptables then you should read my previous article in the Gazette, “Firewalling with netfilter/iptables“.

The following features are discussed:

  1. Specifying multiple ports in one rule
  2. Load balancing
  3. Restricting the number of connections
  4. Maintaining a list of recent connections to match against
  5. Matching against a string in a packet’s data payload
  6. Time-based rules
  7. Setting transfer quotas
  8. Packet matching based on TTL values

All of the features discussed in this article are extensions to the packet matching modules of iptables. I used only two of these extensions in the previous article: the --state module which allowed us to filter packets based on whether they were NEW, ESTABLISHED, RELATED or INVALID connections; and the multiport extension, of which I will go into more detail on in this article.

Some of the modules introduced in this article (marked with an asterisk) have not made their way into the default Linux kernel yet but a netfilter utility called “patch-o-matic” can be used to add them to your own kernel and this will be discussed at the end of the article.

1. Specifying Multiple Ports with multiport

The multiport module allows one to specify a number of different ports in one rule. This allows for fewer rules and easier maintenance of iptables configuration files. For example, if we wanted to allow global access to the SMTP, HTTP, HTTPS and SSH ports on our server we would normally use something like the following:

-A INPUT -i eth0 -p tcp -m state --state NEW --dport ssh   -j ACCEPT
-A INPUT -i eth0 -p tcp -m state --state NEW --dport smtp  -j ACCEPT
-A INPUT -i eth0 -p tcp -m state --state NEW --dport http  -j ACCEPT
-A INPUT -i eth0 -p tcp -m state --state NEW --dport https -j ACCEPT

Using the multiport matching module, we can now write:

-A INPUT -i eth0 -p tcp -m state --state NEW -m multiport --dports ssh,smtp,http,https -j ACCEPT

It must be used in conjunction with either -p tcp or -p udp and only up to 15 ports may be specified. The supported options are:

--sports port[,port,port...]
matches source port(s)
--dports port[,port,port...]
matches destination port(s)
--ports port[,port,port...]
matches both source and destination port(s)

mport* is another similar extension that also allows you to specify port ranges, e.g. --dport 22,80,6000:6100.

Lire la suite…