Using linux server as router for network

Solution 1:

Here is a setup I've used with great success in an almost identical situation to yours. I understand your circumstances to be as follows (please correct me if I'm wrong):

  • Clients on the LAN have full access to the internet. Outgoing connections from LAN clients are masqueraded to the public IP address given to your server/router by your ISP.
  • Clients on the LAN have full access to your server via its LAN-connected interface (eth1).
  • All incoming internet traffic (via eth0) is blocked, except for: (1) traffic involved in a preexisting connection, (2) traffic bound for TCP ports 22 or 80, or (3) ICMP ping requests.
  • TCP Ports 22 and 80 are open to the internet (via eth0) and are handled by your server.
  • Your server responds to ICMP ping requests from the internet.
  • For convenience, I will assume your LAN network address range is 10.10.10.0/24. Modify the script below as needed to use your actual address.

First, ensure that IP forwarding is turned on. In /etc/sysctl.conf, you should have this:

net.ipv4.ip_forward=1

Then, create your netfilter rules as per the following script:

#!/bin/sh
IPT=/sbin/iptables

# Flush all chains, to start with a clean slate.
$IPT -F
$IPT -t nat -F

# Set filter Policies. By default, DROP everything.
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP

# Set server INPUT rules.
$IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -i eth1 -j ACCEPT
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
$IPT -A INPUT -p icmp -m icmp --icmp-type echo-request -j ACCEPT

# Set server OUTPUT rules.
$IPT -A OUTPUT -j ACCEPT

# Set router FORWARD rules.
$IPT -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A FORWARD -i eth1 -o eth0 -j ACCEPT

# Masquerade outgoing LAN traffic.
$IPT -t nat -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE

This should be enough of a framework to build upon.

Solution 2:

You need a set of rules like the following:

$ sudo iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
# Forward SSH packets destined to port 22
$ sudo iptables -A FORWARD -i eth0 -o eth1 -p tcp -m tcp --dport 22 -j allowed
# Forward HTTP packets destined to port 80
$ sudo iptables -A FORWARD -i eth0 -o eth1 -p tcp -m tcp --dport 80 -j allowed
# NATing rules for SSH and HTTP
$ sudo iptables -A PREROUTING -d your_public_ip -p tcp -m tcp --dport 22 -j DNAT --to-destination your_private_ip:22
$ sudo iptables -A PREROUTING -d your_public_ip -p tcp -m tcp --dport 80 -j DNAT --to-destination your_private_ip:80

Please, note that these rules might not be the complete list. However, it will help you get started. Also, don't forget to enable IP forwarding!