shorewall-docs-xml-5.0.4/ 0000755 0000000 0000000 00000000000 12647736671 013765 5 ustar root root shorewall-docs-xml-5.0.4/ECN.xml 0000644 0000000 0000000 00000007170 12647470621 015107 0 ustar root root
ECNTomEastep2001200220032005Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.2006-01-17. The ECN Netfilter target in recent 2.6 Linux Kernels is
broken. Symptoms are that you will be unable to establish a TCP connection
to hosts defined in the /etc/shorewall/ecn file.Explicit Congestion Notification (ECN)Explicit Congestion Notification (ECN) is described in RFC 3168 and
is a proposed Internet standard. Unfortunately, not all sites support ECN
and when a TCP connection offering ECN is sent to sites that don't support
it, the result is often that the connection request is ignored.To allow ECN to be used, Shorewall allows you to enable ECN on your
Linux systems then disable it in your firewall when the destination
matches a list that you create (the /etc/shorewall/ecn file).You enable ECN byecho 1 > /proc/sys/net/ipv4/tcp_ecnYou must arrange for that command to be executed at system boot.
Most distributions have a method for doing that -- on RedHat, you make an
entry in /etc/sysctl.conf.net.ipv4.tcp_ecn = 1Entries in /etc/shorewall/ecn have two columns as follows:INTERFACEThe name of an interface on your systemHOST(S)An address (host or subnet) of a system or group of systems
accessed through the interface in the first column. You may include
a comma-separated list of such addresses in this column.Your external interface is eth0 and you want to disable ECN for
tcp connections to 192.0.2.0/24:
shorewall-docs-xml-5.0.4/Anatomy.xml 0000644 0000000 0000000 00000077003 12647470621 016114 0 ustar root root
Anatomy of Shorewall 4.5TomEastep2007200920122015Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.ProductsShorewall 4.5 consists of six packages.Shorewall Core. This package
contains the core Shorewall shell libraries and is required to install
any of the other packages.Shorewall. This package must be
installed on at least one system in your network. It contains
everything needed to create an IPv4 firewall.Shorewall6. This package
requires the Shorewall package and adds those components needed to
create an IPv6 fireawall.Shorewall-lite. Shorewall
allows for central administration of multiple IPv4 firewalls through
use of Shorewall lite. The full Shorewall product is installed on a
central administrative system where compiled Shorewall scripts are
generated. These scripts are copied to the firewall systems where they
run under the control of Shorewall-lite.Shorewall6-lite. Shorewall
allows for central administration of multiple IPv4 firewalls through
use of Shorewall lite. The full Shorewall product is installed on a
central administrative system where compiled Shorewall scripts are
generated. These scripts are copied to the firewall systems where they
run under the control of Shorewall-lite.Shorewall-init. An add-on to any of the above packages that
allows the firewall state to be altered in reaction to interfaces
coming up and going down. Where Upstart is not being used, this
package can also be configured to place the firewall in a safe state
prior to bringing up the network interfaces.ShorewallThe Shorewall package includes a large number of files which were
traditionally installed in /sbin,
/usr/share/shorewall, /etc/shorewall,
/etc/init.d and /var/lib/shorewall/. These are described in
the sub-sections that follow. Since Shorewall 4.5.2, each of these
directories is now relocatable using the configure scripts included with Shorewall
Core./sbinThe /sbin/shorewall shell program is used to
interact with Shorewall. See shorewall(8)./usr/share/shorewallThe bulk of Shorewall is installed here.action.template - template file for
creating actions.action.* - standard Shorewall
actions.actions.std - file listing the standard
actions.compiler.pl - The configuration compiler
perl program.configfiles - A
directory containing configuration files to copy to create a Shorewall-lite export
directory.configpath - A file
containing distribution-specific path assignments.firewall - A shell program that handles
the add and delete commands
(see shorewall(8)). It
also handles the stop and
clear commands when there is no current compiled
firewall script on the system.functions - A symbolic
link to lib.base that provides for
compatibility with older versions of Shorewall.init - A symbolic link to
the init script (usually
/etc/init.d/shorewall).lib.* - Shell function libraries used by
the other shell programs. Most of these are actually provided by
Shorewall-core.Macros/* - The standard Shorewall macros.modules.* - File that drives the loading
of Netfilter kernel modules. May be overridden by
/etc/shorewall/modules.prog.* - Shell program fragments used as
input to the compiler.Shorewall - Directory
containing the Shorewall Perl modules used by the compiler.shorewallrc - A file that specifies where
all of the other installed components (from all packages) are
installed.version - A file containing the currently
install version of Shorewall.wait4ifup - A shell program that extension scripts can
use to delay until a network interface is available./etc/shorewallThis is where the modifiable IPv4 configuration files are
installed./etc/init.d or /etc/rc.d (depends on distribution)An init script is installed here. Depending on the distribution,
it is named shorewall or
rc.firewall./var/lib/shorewallShorewall doesn't install any files in this directory but rather
uses the directory for storing state information. This directory may be
relocated using shorewall-vardir(5)..iptables-restore-input - The file passed
as input to the iptables-restore program to initialize the firewall
during the last start or
restart command (see shorewall(8))..modules - The contents of the modules
file used during the last start or
restart command (see shorewall(8) for command
information)..modulesdir - The MODULESDIR setting
(shorewall.conf(5)) at the
last start or restart.nat - This unfortunately-named file
records the IP addresses added by ADD_SNAT_ALIASES=Yes and
ADD_IP_ALIASES=Yes in shorewall.conf(5).proxyarp - Records the arp entries added
by entries in shorewall-proxyarp(5)..refresh - The shell program that
performed the last successful refresh
command..restart - The shell program that
performed the last successful restart
command.restore - The default shell program used
to execute restore commands..restore - The shell program that
performed the last successful refresh, restart or
start command.save - File created by the
save command and used to restore the dynamic
blacklist during start/restart..start - The shell program that performed
the last successful start command.state - Records the current firewall
state.zones - Records the current zone
contents.Shorewall6Shorewall6 installs its files in a number of directories:/sbinThe /sbin/shorewall6 shell program is used to
interact with Shorewall6. See shorewall6(8)./usr/share/shorewall6The bulk of Shorewall6 is installed here.action.template - template file for
creating actions.action.* - standard Shorewall
actions.actions.std - file listing the standard
actions.configfiles - A
directory containing configuration files to copy to create a Shorewall6-lite export
directory.configpath - A file
containing distribution-specific path assignments.firewall - A shell program that handles
the add and delete commands
(see shorewall(8)). It
also handles the stop and
clear commands when there is no current compiled
firewall script on the system.functions - A symbolic
link to lib.base that provides for
compatibility with older versions of Shorewall.lib.* - Shell function libraries used by
the other shell programs.Macros/* - The standard Shorewall6 macros.modules - File that drives the loading of
Netfilter kernel modules. May be overridden by
/etc/shorewall/modules.version - A file containing the currently
install version of Shorewall.wait4ifup - A shell program that extension scripts can
use to delay until a network interface is available./etc/shorewall6This is where the modifiable IPv6 configuration files are
installed./var/lib/shorewall6Shorewall6 doesn't install any files in this directory but rather
uses the directory for storing state information. This directory may be
relocated using shorewall-vardir(5)..ip6tables-restore-input - The file
passed as input to the ip6tables-restore program to initialize the
firewall during the last start or
restart command (see shorewall6(8))..modules - The contents of the modules
file used during the last start or
restart command (see shorewall(8) for command
information)..modulesdir - The MODULESDIR setting
(shorewall.conf(5)) at the
last start or restart..refresh - The shell program that
performed the last successful refresh
command..restart - The shell program that
performed the last successful restart
command.restore - The default shell program used
to execute restore commands..restore - The shell program that
performed the last successful refresh, restart or
start command.save - File created by the
save command and used to restore the dynamic
blacklist during start/restart..start - The shell program that performed
the last successful start command.state - Records the current firewall
state.zones - Records the current zone
contents.Shorewall-liteThe Shorewall-lite product includes files installed in /sbin, /usr/share/shorewall-lite, /etc/shorewall-lite,
/etc/init.d and /var/lib/shorewall-lite/. These are described
in the sub-sections that follow./sbinThe /sbin/shorewall-lite shell program is
used to interact with Shorewall lite. See shorewall-lite(8)./etc/init.d or /etc/rc.d (depends on distribution)An init script is installed here. Depending on the distribution,
it is named shorewall-lite or
rc.firewall./etc/shorewall-liteThis is where the modifiable configuration files are
installed./usr/share/shorewall-liteThe bulk of Shorewall-lite is installed here.configpath - A file
containing distribution-specific path assignments.functions - A symbolic
link to lib.base that provides for
compatibility with older versions of Shorewall.lib.base - Shell function librarie used
by the other shell programs. This is a thin wrapper around
/usr/share/shorewall/lib.base.modules* - Files that drive the loading
of Netfilter kernel modules. May be overridden by
/etc/shorewall-lite/modules.shorecap - A shell program used for
generating capabilities files. See the Shorewall-lite
documentation.version - A file containing the currently
install version of Shorewall.wait4ifup - A shell program that extension scripts can
use to delay until a network interface is available./var/lib/shorewall-liteShorewall-lite doesn't install any files in this directory but
rather uses the directory for storing state information. This directory
may be relocated using shorewall-lite-vardir(5).firewall - Compiled shell script
installed by running the load or reload command on the
administrative system (see shorewall(8)).firewall.conf - Digest of the
shorewall.conf file used to compile the firewall script on the
administrative system..iptables-restore-input - The file passed
as input to the iptables-restore program to initialize the firewall
during the last start or
restart command (see shorewall-lite(8))..modules - The contents of the modules
file used during the last start or
restart command (see shorewall-lite(8) for
command information)..modulesdir - The MODULESDIR setting
(shorewall.conf(5)) at the
last start or restart.nat - This unfortunately-named file
records the IP addresses added by ADD_SNAT_ALIASES=Yes and
ADD_IP_ALIASES=Yes in shorewall.conf(5).proxyarp - Records the arp entries added
by entries in shorewall-proxyarp(5)..refresh - The shell program that
performed the last successful refresh
command..restart - The shell program that
performed the last successful restart
command.restore - The default shell program used
to execute restore commands..restore - The shell program that
performed the last successful refresh, restart or
start command.save - File created by the
save command and used to restore the dynamic
blacklist during start/restart..start - The shell program that performed
the last successful start command.state - Records the current firewall
state.zones - Records the current zone
contents.Shorewall6-liteThe Shorewall6-lite product includes files installed in /sbin, /usr/share/shorewall6-lite, /etc/shorewall6-lite,
/etc/init.d and /var/lib/shorewall6-lite/. These are
described in the sub-sections that follow./sbinThe /sbin/shorewall6-lite shell program is
use to interact with Shorewall lite. See shorewall6-lite(8)./etc/init.d or /etc/rc.d (depends on distribution)An init script is installed here. Depending on the distribution,
it is named shorewall6-lite or
rc.firewall./etc/shorewall6-liteThis is where the modifiable configuration files are
installed./usr/share/shorewall6-liteThe bulk of Shorewall-lite is installed here.configpath - A file
containing distribution-specific path assignments.functions - A symbolic
link to lib.base that provides for
compatibility with older versions of Shorewall.lib.base - Shell function librarie used
by the other shell programs. This is a thin wrapper around
/usr/share/shorewall/lib.base.modules* - Files that drive the loading
of Netfilter kernel modules. May be overridden by
/etc/shorewall-lite/modules.shorecap - A shell program used for
generating capabilities files. See the Shorewall-lite
documentation.version - A file containing the currently
install version of Shorewall.wait4ifup - A shell program that extension scripts can
use to delay until a network interface is available./var/lib/shorewall6-liteShorewall6-lite doesn't install any files in this directory but
rather uses the directory for storing state information. This directory
may be relocated using shorewall-lite-vardir(5).firewall - Compiled shell script
installed by running the load or reload command on the
administrative system (see shorewall6(8)).firewall.conf - Digest of the
shorewall.conf file used to compile the firewall script on the
administrative system..ip6tables-restore-input - The file
passed as input to the ip6tables-restore program to initialize the
firewall during the last start or
restart command (see shorewall-lite(8))..modules - The contents of the modules
file used during the last start or
restart command (see shorewall-lite(8) for
command information)..modulesdir - The MODULESDIR setting
(shorewall.conf(5)) at the
last start or restart..refresh - The shell program that
performed the last successful refresh
command..restart - The shell program that
performed the last successful restart
command.restore - The default shell program used
to execute restore commands..restore - The shell program that
performed the last successful refresh, restart or
start command.save - File created by the
save command and used to restore the dynamic
blacklist during start/restart..start - The shell program that performed
the last successful start command.state - Records the current firewall
state.zones - Records the current zone
contents.
shorewall-docs-xml-5.0.4/PPTP.xml 0000644 0000000 0000000 00000047446 12647470621 015277 0 ustar root root
PPTP - UnmaintainedTomEastep2001200220032004200520062007Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Shorewall easily supports PPTP in a number of
configurations.I have not used PPTP in years and as a consequence, this document is
no longer maintained (any volunteers?).As far as I know, the information regarding Shorewall configuration
is still valid but the configurations shown for for the other components
may no longer work. For the most part, they show configuration files that
I used when I worked for Compaq and used PPTP as my
work VPN.Preliminary ReadingI recommend reading the VPN
Basics article if you plan to implement any type of VPN.PPTP Server Running on your FirewallConfiguring SambaYou will need a WINS server (Samba configured to run as a WINS
server is fine). Global section from /etc/samba/smb.conf on my WINS
server (192.168.1.3) is:[global]
workgroup = TDM-NSTOP
netbios name = WOOKIE
server string = GNU/Linux Box
encrypt passwords = Yes
log file = /var/log/samba/%m.log
max log size = 0
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
os level = 65
domain master = True
preferred master = True
dns proxy = No
wins support = Yes
printing = lprng
[homes]
comment = Home Directories
valid users = %S
read only = No
create mask = 0664
directory mask = 0775
[printers]
comment = All Printers
path = /var/spool/samba
printable = YesConfiguring pppdHere is a copy of my /etc/ppp/options.poptop file:ipparam PoPToP
lock
mtu 1490
mru 1490
ms-wins 192.168.1.3
ms-dns 206.124.146.177
multilink
proxyarp
auth
+chap
+chapms
+chapms-v2
ipcp-accept-local
ipcp-accept-remote
lcp-echo-failure 30
lcp-echo-interval 5
deflate 0
mppe-128
mppe-stateless
require-mppe
require-mppe-statelessSystem 192.168.1.3 acts as a WINS server so I have included
that IP as the ms-wins value.I have pointed the remote clients at my DNS server -- it has
external address 206.124.146.177.I am requiring 128-bit stateless compression.Here's my /etc/ppp/chap-secrets:Secrets for authentication using CHAP
# client server secret IP addresses
CPQTDM\\TEastep * <shhhhhh> 192.168.1.7
TEastep * <shhhhhh> 192.168.1.7I am the only user who connects to the server but I may connect
either with or without a domain being specified. The system I connect
from is my laptop so I give it the same IP address when tunneled in at
it has when I use its wireless LAN card around the house.You will also want the following in /etc/modules.conf:alias ppp-compress-18 ppp_mppe
alias ppp-compress-21 bsd_comp
alias ppp-compress-24 ppp_deflate
alias ppp-compress-26 ppp_deflateConfiguring pptpdPoPTop (pptpd) is available from http://www.poptop.org/.Here is a copy of my /etc/pptpd.conf file:option /etc/ppp/options.poptop
speed 115200
localip 192.168.1.254
remoteip 192.168.1.33-38I specify the /etc/ppp/options.poptop file as my ppp options
file (I have several).The local IP is the same as my internal interface's
(192.168.1.254).I have assigned a remote IP range that overlaps my local
network. This, together with proxyarp in my
/etc/ppp/options.poptop file make the remote hosts look like they
are part of the local subnetwork.I use this file to start/stop pptpd -- I have this in
/etc/init.d/pptpd:#!/bin/sh
#
# /etc/rc.d/init.d/pptpd
#
# chkconfig: 5 12 85
# description: control pptp server
#
case "$1" in
start)
echo 1 > /proc/sys/net/ipv4/ip_forward
modprobe ppp_async
modprobe ppp_generic
modprobe ppp_mppe
modprobe slhc
if /usr/local/sbin/pptpd; then
touch /var/lock/subsys/pptpd
fi
;;
stop)
killall pptpd
rm -f /var/lock/subsys/pptpd
;;
restart)
killall pptpd
if /usr/local/sbin/pptpd; then
touch /var/lock/subsys/pptpd
fi
;;
status)
ifconfig
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
;;
esacConfiguring ShorewallBasic SetupHere' a basic setup that treats your remote users as if they
were part of your loc zone. Note that
if your primary Internet connection uses ppp0, then be sure that
loc follows net in /etc/shorewall/zones./etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY ZONE
pptpserver net 0.0.0.0/0/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
loc ppp+Remote Users in a Separate ZoneIf you want to place your remote users in their own zone so that
you can control connections between these users and the local network,
follow this example. Note that if your primary Internet connection
uses ppp0 then be sure that vpn
follows net in /etc/shorewall/zones
as shown below./etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY ZONE
pptpserver net 0.0.0.0/0/etc/shorewall/zones:#ZONE TYPE
net ipv4
loc ipv4
vpn ipv4/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net eth0 206.124.146.255
loc eth2 192.168.10.255
vpn ppp+Your policies and rules may now be configured for traffic
to/from the vpn zone.Multiple Remote NetworksOften there will be situations where you want multiple
connections from remote networks with these networks having different
firewalling requirements.Here's how you configure this in Shorewall. Note that if your
primary Internet connection uses ppp0 then be sure that the vpn{1-3} zones follows net in /etc/shorewall/zones as shown
below./etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY ZONE
pptpserver net 0.0.0.0/0/etc/shorewall/zones:#ZONE TYPE
fw firewall
net ipv4
loc ipv4
vpn1 ipv4
vpn2 ipv4
vpn3 ipv4/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net eth0 206.124.146.255
loc eth2 192.168.10.255
- ppp+/etc/shorewall/hosts:#ZONE HOST(S) OPTIONS
vpn1 ppp+:192.168.1.0/24
vpn2 ppp+:192.168.2.0/24
vpn3 ppp+:192.168.3.0/24Your policies and rules can now be configured using separate
zones (vpn1, vpn2, and vpn3) for the three remote network.PPTP Server Running Behind your FirewallIf you have a single external IP address, add the following to your
/etc/shorewall/rules file:/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DEST PORT(S)
DNAT net loc:<server address> tcp 1723
DNAT net loc:<server address> 47If you have multiple external IP address and you want to forward a
single <external address>, add the following to
your /etc/shorewall/rules file:/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DEST PORT(S) SOURCE ORIGINAL
# PORT(S) DEST
DNAT net loc:<server address> tcp 1723 - <external address>
DNAT net loc:<server address> 47 - - <external address>You will also want to add this entry to your
/etc/shorewall/masq file:#INTERFACE SUBNET ADDRESS PROTO
<external interface> <server address> <external address> 47Be sure that the above entry comes before any other entry that might match the
server's address.PPTP Clients Running Behind your FirewallPlease see this article.PPTP Client Running on your FirewallThe key elements of this setup are as follows:Define a zone for the remote network accessed via PPTP.Associate that zone with a ppp interface.Define rules for PPTP traffic to/from the firewall.Define rules for traffic two and from the remote zone.Here are examples from one of my old setups:/etc/shorewall/zones:#ZONE TYPE
cpq ipv4/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
- ppp+/etc/shorewall/hosts:#ZONE HOST(S) OPTIONS
cpq ppp+:!192.168.1.0/24/etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY ZONE
pptpclient net 0.0.0.0/0I use the combination of interface and hosts file to define the
cpq zone because I also run a PPTP server on my firewall
(see above). Using this technique allows me to distinguish clients of my
own PPTP server from arbitrary hosts at Compaq; I assign addresses in
192.168.1.0/24 to my PPTP clients and Compaq doesn't use that RFC1918
Class C subnet.I use this script in /etc/init.d to control the client. The reason
that I disable ECN when connecting is that the Compaq tunnel servers don't
do ECN yet and reject the initial TCP connection request if I enable ECN
:-(#!/bin/sh
#
# /etc/rc.d/init.d/pptp
#
# chkconfig: 5 60 85
# description: PPTP Link Control
#
NAME="Tandem"
ADDRESS=tunnel-tandem.compaq.com
USER='Tandem\tommy'
ECN=0
DEBUG=
start_pptp() {
echo $ECN > /proc/sys/net/ipv4/tcp_ecn
if /usr/sbin/pptp $ADDRESS user $USER noauth $DEBUG; then
touch /var/lock/subsys/pptp
echo "PPTP Connection to $NAME Started"
fi
}
stop_pptp() {
if killall /usr/sbin/pptp 2> /dev/null; then
echo "Stopped pptp"
else
rm -f /var/run/pptp/*
fi
# if killall pppd; then
# echo "Stopped pppd"
# fi
rm -f /var/lock/subsys/pptp
echo 1 > /proc/sys/net/ipv4/tcp_ecn
}
case "$1" in
start)
echo "Starting PPTP Connection to ${NAME}..."
start_pptp
;;
stop)
echo "Stopping $NAME PPTP Connection..."
stop_pptp
;;
restart)
echo "Restarting $NAME PPTP Connection..."
stop_pptp
start_pptp
;;
status)
ifconfig
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
;;
esacHere's my /etc/ppp/options file:#
# Identify this connection
#
ipparam Compaq
#
# Lock the port
#
lock
#
# We don't need the tunnel server to authenticate itself
#
noauth
+chap
+chapms
+chapms-v2
multilink
mrru 1614
#
# Turn off transmission protocols we know won't be used
#
nobsdcomp
nodeflate
#
# We want MPPE
#
mppe-128
mppe-stateless
#
# We want a sane mtu/mru
#
mtu 1000
mru 1000
#
# Time this thing out of it goes poof
#
lcp-echo-failure 10
lcp-echo-interval 10My /etc/ppp/ip-up.local file sets up the routes that I need to route
Compaq traffic through the PPTP tunnel:#/bin/sh
case $6 in
Compaq)
route add -net 16.0.0.0 netmask 255.0.0.0 gw $5 $1
route add -net 130.252.0.0 netmask 255.255.0.0 gw $5 $1
route add -net 131.124.0.0 netmask 255.255.0.0 gw $5 $1
...
;;
esacFinally, I run the following script every five minutes under crond
to restart the tunnel if it fails:#!/bin/sh
restart_pptp() {
/sbin/service pptp stop
sleep 10
if /sbin/service pptp start; then
/usr/bin/logger "PPTP Restarted"
fi
}
if [ -n "`ps ax | grep /usr/sbin/pptp | grep -v grep`" ]; then
exit 0
fi
echo "Attempting to restart PPTP"
restart_pptp > /dev/null 2>&1 &Here's
a script and corresponding ip-up.local from Jerry Vonau
jvonau@home.com that controls two PPTP connections.PPTP Client running on your Firewall with PPTP Server in an ADSL
ModemSome ADSL systems in Europe (most notably in Austria and the
Netherlands) feature a PPTP server builtinto an ADSL Modem.
In this setup, an Ethernet interface is dedicated to supporting the PPTP
tunnel between the firewall and the Modem while the actual
Internet access is through PPTP (interface ppp0). If you have this type of
setup, you need to modify the sample configuration that you downloaded as
described in this section. These changes are in
addition to those described in the QuickStart
Guides.Lets assume the following:ADSL Modem connected through eth0Modem IP address = 192.168.1.1eth0 IP address = 192.168.1.2The changes you need to make are as follows:Add this entry to /etc/shorewall/zones:#ZONE TYPE
modem ipv4That entry defines a new zone called modem which
will contain only your ADSL modem.Add the following entry to /etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
modem eth0 192.168.1.255 dhcpYou will of course modify the net entry in
/etc/shorewall/interfaces to specify ppp0 as the
interface as described in the QuickStart Guide corresponding to your
setup.Add the following to /etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY ZONE
pptpclient modem 192.168.1.1That entry allows a PPTP tunnel to be established between your
Shorewall system and the PPTP server in the modem.
shorewall-docs-xml-5.0.4/Manpages.xml 0000644 0000000 0000000 00000016765 12647470621 016247 0 ustar root root
Shorewall 5.0 ManpagesTomEastep2007-2015Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.These manpages are for Shorewall 5.0 and later only. They describe
features and options not available on earlier releases. The manpages for
Shorewall 4.4-4.6 are available
here.Section 5 — Files and Concepts
accounting - Define
IP accounting rules.actions -
Declare user-defined actions.arprules
- (Added in Shorewall 4.5.12) Define arpfilter rules.blrules -
shorewall Blacklist file.conntrack - Specify
helpers for connections or exempt certain traffic from netfilter
connection tracking.ecn -
Disabling Explicit Congestion Notificationexclusion - Excluding
hosts from a network or zonehosts -
Define multiple zones accessed through a single interfaceinterfaces - Define
the interfaces on the system and optionally associate them with
zones.ipsets -
Describes how to specify set names in Shorewall configuration
files.maclist -
Define MAC verification.mangle -
Supersedes tcrules and describes packet/connection marking.masq -
Define Masquerade/SNATmodules -
Specify which kernel modules to load.nat - Define
one-to-one NAT.nesting -
How to define nested zones.netmap -
How to map addresses from one net to another.params -
Assign values to shell variables used in other files.policy -
Define high-level policies for connections between zones.providers - Define
routing tables, usually for multiple Internet links.proxyarp
- Define Proxy ARP.rtrules -
Define routing rules.routes -
(Added in Shorewall 4.4.15) Add additional routes to provider routing
tables.rules -
Specify exceptions to policies, including DNAT and REDIRECT.secmarks
- Attach an SELinux context to a packet.tcclasses - Define htb
classes for traffic shaping.tcdevices - Specify
speed of devices for traffic shaping.tcfilters - Classify
traffic for shaping; often used with an IFB to shape ingress
traffic.tcinterfaces -
Specify devices for simplified traffic shaping.tcpri -
Classify traffic for simplified traffic shaping.tunnels -
Define VPN connections with endpoints on the firewall.shorewall.conf - Specify
values for global Shorewall options.shorewall-lite.conf -
Specify values for global Shorewall Lite options.vardir -
Redefine the directory where Shorewall keeps its state
information.vardir-lite -
Redefine the directory where Shorewall Lite keeps its state
information.zones -
Declare Shorewall zones.
Section 8 — Administrative Commands
shorewall -
/sbin/shorewall command syntax and semantics.shorewall-init - Companion
package that allows for automatic start/stop of other Shorewall
products based on network events.shorewall-lite -
/sbin/shorewall-lite command syntax and semantics.
shorewall-docs-xml-5.0.4/VPN.xml 0000644 0000000 0000000 00000013613 12647470621 015144 0 ustar root root
VPN PassthroughTomEastep200220042005Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Virtual Private Networking (VPN)It is often the case that a system behind the firewall needs to be
able to access a remote network through Virtual Private Networking (VPN).
The two most common means for doing this are IPSEC and PPTP. The basic
setup is shown in the following diagram:A system with an RFC 1918 address needs to access a remote network
through a remote gateway. For this example, we will assume that the local
system has IP address 192.168.1.12 and that the remote gateway has IP
address 192.0.2.224.If PPTP is being used and you need to have two or more local systems
connected to the same remote server at the same time, then you should be
sure that the PPTP helpers modules are loaded (ip_conntrack_pptp and
ip_nat_pptp or nf_conntrack_pptp and nf_nat_pptp). Using the default
modules file, Shorewall (Lite) will attempt to load these modules when
Shorewall (Lite) is started.If IPSEC is being used, you should configure IPSEC to use
NAT Traversal -- Under NAT traversal the IPSEC
packets (protocol 50 or 51) are encapsulated in UDP packets (normally with
destination port 4500). Additionally, keep-alive
messages are sent frequently so that NATing gateways between
the end-points will retain their connection-tracking entries. This is the
way that I connect to the HP Intranet and it works flawlessly without
anything in Shorewall other than my ACCEPT loc->net policy. NAT
traversal is available as a patch for Windows 2K and is a standard feature
of Windows XP -- simply select "L2TP IPSec VPN" from the "Type of VPN"
pulldown.Alternatively, if you have an IPSEC gateway behind your firewall
then you can try the following: only one system may connect to the remote
gateway and there are firewall configuration requirements as
follows:
The above may or may not work — your mileage may vary. NAT Traversal
is definitely a better solution. To use NAT traversal:
/etc/shorewall/rules with NAT TraversalACTIONSOURCEDESTINATIONPROTOCOLPORTCLIENT PORTORIGINAL DESTDNATnet:192.0.2.224loc:192.168.1.12udp4500DNATnet:192.0.2.224loc:192.168.1.12udp500
If you want to be able to give access to all of your local systems
to the remote network, you should consider running a VPN client on your
firewall. As starting points, see The /etc/shorewall/tunnels
manpage.
shorewall-docs-xml-5.0.4/two-interface.xml 0000644 0000000 0000000 00000170664 12647470621 017262 0 ustar root root
Basic Two-Interface FirewallTomEastep2002-2009Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.This article applies to Shorewall 4.4 and
later. If you are running a version of Shorewall earlier than Shorewall
4.4.0 then please see the documentation for that
release.IntroductionSetting up a Linux system as a firewall for a small network is a
fairly straight-forward task if you understand the basics and follow the
documentation.This guide doesn't attempt to acquaint you with all of the features
of Shorewall. It rather focuses on what is required to configure Shorewall
in its most common configuration:Linux system used as a firewall/router for a small local
network.Single public IP address. If
you have more than one public IP address, this is not the guide you
want -- see the Shorewall Setup
Guide instead.Internet connection through cable modem, DSL, ISDN, Frame Relay,
dial-up ...Here is a schematic of a typical installation: Common two interface firewall configurationIf you edit your configuration files on a
Windows system, you must save them as
Unix files if your editor supports that option
or you must run them through dos2unix before trying
to use them. Similarly, if you copy a configuration file from your
Windows hard drive to a floppy disk, you must
run dos2unix against the copy before using it with
Shorewall. Windows
Version of dos2unixLinux
Version of dos2unixSystem RequirementsShorewall requires that you have the
iproute/iproute2 package installed
(on RedHat, the package is called
iproute). You can tell if this package is installed
by the presence of an ip program on your firewall
system. As root, you can use
the which command to check for this program:
[root@gateway root]# which ip
/sbin/ip
[root@gateway root]# I recommend that you first read through
the guide to familiarize yourself with what's involved then go back
through it again making your configuration changes.ConventionsPoints at which configuration changes are recommended are flagged
with .Configuration notes that are unique to Debian and it's derivatives
are marked with .PPTP/ADSLIf you have an ADSL Modem and you use
PPTP to communicate with a server in that modem, you
must make the changes recommended here in addition to those detailed below.
ADSL with PPTP is most commonly
found in Europe, notably in Austria.Shorewall ConceptsThe configuration files for Shorewall are contained in the directory
/etc/shorewall -- for simple
setups, you will only need to deal with a few of these as described in
this guide.After you have installed
Shorewall, locate the two-interfaces samples:If you installed using an RPM, the samples will be in the
Samples/two-interfaces/ subdirectory of the Shorewall
documentation directory. If you don't know where the Shorewall
documentation directory is, you can find the samples using this
command:~# rpm -ql shorewall | fgrep two-interfaces
/usr/share/doc/packages/shorewall/Samples/two-interfaces
/usr/share/doc/packages/shorewall/Samples/two-interfaces/interfaces
/usr/share/doc/packages/shorewall/Samples/two-interfaces/masq
/usr/share/doc/packages/shorewall/Samples/two-interfaces/policy
/usr/share/doc/packages/shorewall/Samples/two-interfaces/rules
/usr/share/doc/packages/shorewall/Samples/two-interfaces/zones
~#If you installed using the tarball, the samples are in the
Samples/two-interfaces directory in the tarball.If you installed using a Shorewall 3.x .deb, the samples are
in /usr/share/doc/shorewall/examples/two-interfaces. You must
install the shorewall-doc package.If you installed using a
Shorewall 4.x .deb, the samples are in /usr/share/doc/shorewall-common/examples/two-interfaces.
You do not need the shorewall-doc package to have access to the
samples.Note to Debian and Ubuntu
UsersIf you install using the .deb, you will find that your
/etc/shorewall directory
is practially empty. This is intentional. The released
configuration file skeletons may be found on your system in the
directory /usr/share/doc/shorewall/default-config.
Simply copy the files you need from that directory to /etc/shorewall and modify the
copies.As each file is introduced, I suggest that you look at the actual
file on your system and that you look at the man page for that
file. For example, to look at the man page for the
/etc/shorewall/zones file, type man
shorewall-zones at a shell prompt.Note: Beginning with Shorewall 4.4.20.1, there are versions of the
sample files that are annotated with the corresponding manpage contents.
These files have names ending in '.annotated'. You might choose to look at
those files instead.Shorewall views the network where it is running as being composed of
a set of zones. In the two-interface sample configuration, the following
zone names are used:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall
net ipv4
loc ipv4Zones are defined in the /etc/shorewall/zones
file.Note that Shorewall recognizes the firewall system as its own zone -
when the /etc/shorewall/zones file is processed, the name of the firewall
zone is stored in the shell variable $FW which may be used to refer to the
firewall zone throughout the Shorewall configuration.Rules about what traffic to allow and what traffic to deny are
expressed in terms of zones. You express your default policy for connections from one zone
to another zone in the /etc/shorewall/policy
file.You define exceptions to those default policies in the /etc/shorewall/rules
file. For each connection request entering the firewall, the
request is first checked against the /etc/shorewall/rules
file. If no rule in that file matches the connection request then the
first policy in /etc/shorewall/policy
that matches the request is applied. If there is a common action defined for
the policy in /etc/shorewall/actions or
/usr/share/shorewall/actions.std then that action is
performed before the action is applied. The purpose of the common action
is two-fold:It silently drops or rejects harmless common traffic that would
otherwise clutter up your log — Broadcasts for example.If ensures that traffic critical to correct operation is allowed
through the firewall — ICMP fragmentation-needed
for example.The /etc/shorewall/policy
file included with the two-interface sample has the following policies:
#SOURCE DEST POLICY LOG LEVEL LIMIT:BURST
loc net ACCEPT
net all DROP info
all all REJECT infoIn the two-interface
sample, the line below is included but commented out. If you want your
firewall system to have full access to servers on the Internet, uncomment
that line. #SOURCE DEST POLICY LOG LEVEL LIMIT:BURST
$FW net ACCEPT The above policy will:
Allow all connection requests from your local network to the
InternetDrop (ignore) all connection requests from the Internet to
your firewall or local networkOptionally accept all connection requests from the firewall to
the Internet (if you uncomment the additional policy)reject all other connection requests. The word info in the LOG LEVEL
column for the DROP and REJECT policies indicates that packets dropped or
rejected under those policies should be logged at that level.It is important to note that Shorewall policies (and rules) refer to
connections and not packet flow. With the
policies defined in the /etc/shorewall/policy file shown above,
connections are allowed from the loc zone to the
net zone even though connections are not allowed from
the loc zone to the firewall itself.Some people want to consider their firewall to be part of their
local network from a security perspective. If you want to do this, add
these two policies:#SOURCE DEST POLICY LOG LEVEL LIMIT:BURST
loc $FW ACCEPT
$FW loc ACCEPTAt this point, edit your /etc/shorewall/policy
and make any changes that you wish.Network InterfacesThe firewall has two network interfaces. Where Internet connectivity
is through a cable or DSL Modem, the
External Interface will be the Ethernet adapter that
is connected to that Modem (e.g., eth0) unless you connect via
Point-to-Point Protocol over Ethernet
(PPPoE) or Point-to-Point Tunneling
Protocol (PPTP) in which case the External
Interface will be a ppp interface (e.g., ppp0). If you connect via a regular modem,
your External Interface will also be ppp0. If you connect via
ISDN, your external interface will be ippp0.Be sure you know which interface is your external interface. Many
hours have been spent floundering by users who have configured the wrong
interface. If you are unsure, then as root type ip route
ls at the command line. The device listed in the last
(default) route should be your external interface.Example:root@lists:~# ip route ls
192.168.1.1 dev eth0 scope link
192.168.2.2 dev tun0 proto kernel scope link src 192.168.2.1
192.168.3.0/24 dev br0 proto kernel scope link src 192.168.3.254
10.13.10.0/24 dev tun1 scope link
192.168.2.0/24 via 192.168.2.2 dev tun0
192.168.1.0/24 dev br0 proto kernel scope link src 192.168.1.254
206.124.146.0/24 dev eth0 proto kernel scope link src 206.124.146.176
10.10.10.0/24 dev tun1 scope link
default via 206.124.146.254 dev eth0
root@lists:~# In that example, eth0 is
the external interface.If your external interface is ppp0 or ippp0 then you will want to set
CLAMPMSS=yes in /etc/shorewall/shorewall.conf.Your Internal Interface will be an Ethernet
adapter (eth1 or eth0) and will be connected to a hub or
switch. Your other computers will be connected to the same hub/switch
(note: If you have only a single internal system, you can connect the
firewall directly to the computer using a cross-over cable). Do not connect the internal and external
interface to the same hub or switch except for testing.You
can test using this kind of configuration if you specify the arp_filter option or the arp_ignore option in /etc/shorewall/interfaces
for all interfaces connected to the common hub/switch. Using such a setup with a production firewall is strongly
recommended against.Do not configure a default route on your
internal interface. Your firewall should have exactly one
default route via your ISP's Router.The Shorewall two-interface sample configuration assumes that the
external interface is eth0 and the
internal interface is eth1. If
your configuration is different, you will have to modify the sample
/etc/shorewall/interfaces
file accordingly. While you are there, you may wish to review the list of
options that are specified for the interfaces. Some hints:If your external interface is ppp0 or ippp0, you can replace the
detect in the second column with a -
(minus the quotes).If your external interface is ppp0 or ippp0 or if you have a static
IP address, you can remove dhcp
from the option list.If your internal interface is a bridge create using the
brctl utility then you must
add the routeback option to the option
list.IP AddressesBefore going further, we should say a few words about Internet
Protocol (IP) addresses. Normally, your
ISP will assign you a single Public IP address. This
address may be assigned via the Dynamic Host Configuration Protocol
(DHCP) or as part of establishing your connection when
you dial in (standard modem) or establish your PPP
connection. In rare cases, your ISP may assign you a
static IP address; that means that you configure your
firewall's external interface to use that address permanently. However
your external address is assigned, it will be shared by all of your
systems when you access the Internet. You will have to assign your own
addresses in your internal network (the Internal Interface on your
firewall plus your other computers). RFC
1918 reserves several Private
IP address ranges for this purpose: 10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255You will want to assign your
addresses from the same sub-network (subnet). For our purposes, we can
consider a subnet to consists of a range of addresses x.y.z.0 -
x.y.z.255. Such a subnet will have a Subnet Mask of 255.255.255.0. The address
x.y.z.0 is reserved as the Subnet
Address and x.y.z.255 is reserved as the
Subnet Broadcast Address. In Shorewall, a subnet is
described using Classless
InterDomain Routing (CIDR) notation with consists of the subnet
address followed by /24. The 24 refers
to the number of consecutive leading 1 bits from the left
of the subnet mask. Range:10.10.10.0 -
10.10.10.255Subnet
Address:10.10.10.0Broadcast
Address:10.10.10.255CIDR
Notation:10.10.10.0/24 It is conventional to assign the internal interface
either the first usable address in the subnet (10.10.10.1 in the above example) or the
last usable address (10.10.10.254).One of the purposes of subnetting is to allow all computers in the
subnet to understand which other computers can be communicated with
directly. To communicate with systems outside of the subnetwork, systems
send packets through a gateway (router).Your local computers (computer 1 and computer 2 in the above
diagram) should be configured with their default gateway to be the
IP address of the firewall's internal interface.The foregoing short discussion barely scratches the surface
regarding subnetting and routing. If you are interested in learning more
about IP addressing and routing, I highly recommend
IP Fundamentals: What Everyone Needs to Know about Addressing &
Routing, Thomas A. Maufer, Prentice-Hall, 1999, ISBN 0-13-975483-0
(link).The remainder of this guide will assume that you have
configured your network as shown here: The default gateway for computer's 1 & 2 would be
10.10.10.254. Your ISP might assign your external interface
an RFC 1918 address. If that address
is in the 10.10.10.0/24
subnet then you will need to select a DIFFERENT
RFC 1918 subnet for your local network.IP Masquerading (SNAT)The addresses reserved by RFC 1918 are sometimes referred to as
non-routable because the Internet backbone routers
don't forward packets which have an RFC-1918 destination address. When one
of your local systems (let's assume computer 1 in the above diagram) sends a connection request to an
Internet host, the firewall must perform Network Address
Translation (NAT). The firewall rewrites the
source address in the packet to be the address of the firewall's external
interface; in other words, the firewall makes it appear to the destination
Internet host as if the firewall itself is initiating the connection. This
is necessary so that the destination host will be able to route return
packets back to the firewall (remember that packets whose destination
address is reserved by RFC 1918 can't be routed across the Internet so the
remote host can't address its response to computer 1). When the firewall
receives a return packet, it rewrites the destination address back to
10.10.10.1 and forwards the
packet on to computer 1.On Linux systems, the above process is often referred to as
IP Masquerading but you will also see the term
Source Network Address Translation
(SNAT) used. Shorewall follows the convention used with
Netfilter: Masquerade describes the case where you
let your firewall system automatically detect the external interface
address.SNAT refers to the
case when you explicitly specify the source address that you want
outbound packets from your local network to use. In Shorewall, both Masquerading and
SNAT are configured with entries
in the /etc/shorewall/masq
file. You will normally use Masquerading if your external
IP is dynamic and SNAT if the
IP is static.If your external firewall interface is eth0, you do not need to modify the file
provided with the sample. Otherwise, edit
/etc/shorewall/masq and
change the first column to the name of your external interface.If your external IP is static, you can enter it
in the third column in the /etc/shorewall/masq
entry if you like although your firewall will work fine if you leave that
column empty (Masquerade). Entering your static IP in
column 3 (SNAT) makes the processing of outgoing packets a little more
efficient.If you are using the Debian package, please
check your shorewall.conf file to ensure that the
following is set correctly; if it is not, change it
appropriately:IP_FORWARDING=OnLoggingShorewall does not maintain a log itself but rather relies on your
system's logging configuration.
The following commands rely
on knowing where Netfilter messages are logged:shorewall show log (Displays the last 20
netfilter log messages)shorewall logwatch (Polls the log at a
settable intervalshorewall dump (Produces an extensive report
for inclusion in Shorewall problem reports)It is important that these commands work properly because when you
encounter connection problems when Shorewall is running, the first thing
that you should do is to look at the Netfilter log; with the help of
Shorewall FAQ 17, you can usually
resolve the problem quickly.The Netfilter log location is distribution-dependent:Debian and its derivatives log Netfilter messages to
/var/log/kern.log.Recent SuSE/OpenSuSE releases come
preconfigured with syslog-ng and log netfilter messages to
/var/log/firewall.For other distributions, Netfilter messages are most commonly
logged to /var/log/messages.If you are running a distribution that logs netfilter messages to a
log other than /var/log/messages, then modify the
LOGFILE setting in /etc/shorewall/shorewall.conf to
specify the name of your log.The LOGFILE setting does not control where the Netfilter log is
maintained -- it simply tells the /sbin/shorewall
utility where to find the log.Kernel Module LoadingBeginning in Shorewall 4.4.7,
/etc/shorewall/shorewall.conf contains a
LOAD_HELPERS_ONLY option which is set to in the
samples. This causes Shorewall to attempt to load the modules listed in
/usr/share/shorewall/helpers. In addition, it sets
sip_direct_media=0 when loading the
nf_conntrack_sip module. That setting is somewhat less secure than
sip_direct_media=1, but it generally
makes VOIP through the firewall work much better.The modules in /usr/share/shorewall/helpers are
those that are not autoloaded. If your kernel does not support module
autoloading and you want Shorewall to attempt to load all netfilter
modules that it might require, then set LOAD_HELPERS_ONLY=No. That will
cause Shorewall to try to load the modules listed in
/usr/share/shorewall/modules. That file does not set
sip_direct_media=0.If you need to modify either
/usr/share/shorewall/helpers or
/usr/share/shorewall/modules then copy the file to
/etc/shorewall and modify the copy.Modify the setting of LOAD_HELPER_ONLY as necessary.Port Forwarding (DNAT)One of your goals may be to run one or more servers on your local
computers. Because these computers have RFC-1918 addresses, it is not
possible for clients on the Internet to connect directly to them. It is
rather necessary for those clients to address their connection requests to
the firewall who rewrites the destination address to the address of your
server and forwards the packet to that server. When your server responds,
the firewall automatically performs SNAT to rewrite the source address in the
response.The above process is called Port Forwarding or
Destination Network Address Translation
(DNAT). You configure port forwarding using
DNAT rules in the /etc/shorewall/rules
file.For forwarding connections from the net zone to
a server in the loc zone, the general form of a
simple port forwarding rule in /etc/shorewall/rules is:
#ACTION SOURCE DEST PROTO DEST PORT(S)
DNAT net loc:<server local ip address>[:<server port>] <protocol><port>If you want to forward traffic from the
loc zone to a server in the
loc zone, see Shorewall
FAQ 2.Be sure to add your rules after the line that reads SECTION NEW.The server must have a static IP address. If you assign IP
addresses to your local system using DHCP, you need to configure your
DHCP server to always assign the same IP address to systems that are
the target of a DNAT rule.Shorewall has macros for
many popular applications. Look at the output of shorewall show
macros to see what is available in your release. Macros simplify
creating DNAT rules by supplying the protocol and port(s) as shown in the
following examples.Web ServerYou run a Web Server on computer 2 in the above diagram and you want to forward
incoming TCP port 80 to that system:
#ACTION SOURCE DEST PROTO DEST PORT(S)
Web(DNAT) net loc:10.10.10.2FTP ServerYou run an FTP Server on computer 1 so you want to forward incoming
TCP port 21 to that system: #ACTION SOURCE DEST PROTO DEST PORT(S)
FTP(DNAT) net loc:10.10.10.1 For
FTP, you will also need to have
FTP connection tracking and NAT
support in your kernel. For vendor-supplied kernels, this means that
the ip_conntrack_ftp and
ip_nat_ftp modules
(nf_conntrack_ftp and
nf_nat_ftp in later 2.6 kernels) must be loaded.
Shorewall will automatically load these modules if they are available
and located in the standard place under /lib/modules/<kernel
version>/kernel/net/ipv4/netfilter. See the Shorewall FTP documentation for more
information. A couple of important points to keep in mind: The Shorewall-provided macros assume that the service is using
its standard port and will not work with a service listening on a
non-standard port.You must test the above rule from a client outside of your
local network (i.e., don't test from a browser running on computers
1 or 2 or on the firewall). If you want to be able to access your
web server and/or FTP server from inside your
firewall using the IP address of your external
interface, see Shorewall FAQ
#2.Many ISPs block incoming connection
requests to port 80. If you have problems connecting to your web
server, try the following rule and try connecting to port
5000.#ACTION SOURCE DEST PROTO DEST PORT(S)
DNAT net loc:10.10.10.2:80 tcp 5000At this point, modify /etc/shorewall/rules to
add any DNAT rules that you require.When testing DNAT rules like those shown above, you must test from
a client OUTSIDE YOUR FIREWALL (in the 'net' zone). You cannot test
these rules from inside the firewall!For DNAT troubleshooting tips, see FAQs
1a and 1b.For information about DNAT when there are multiple external IP
addresses, see the Shorewall Aliased Interface
documentation and the Shorewall Setup Guide.Domain Name Server (DNS)Normally, when you connect to your ISP, as part of getting an IP
address your firewall's Domain Name Service
(DNS) resolver will be automatically configured (e.g.,
the /etc/resolv.conf file
will be written). Alternatively, your ISP may have given you the
IP address of a pair of DNS name
servers for you to manually configure as your primary and secondary name
servers. Regardless of how DNS gets configured on your
firewall, it is your responsibility to configure the resolver in your
internal systems. You can take one of two approaches: You can configure your internal systems to use your ISP's name
servers. If your ISP gave you the addresses of their servers or if
those addresses are available on their web site, you can configure
your internal systems to use those addresses. If that information
isn't available, look in /etc/resolv.conf on your firewall system --
the name servers are given in "nameserver" records in that
file. You can configure a
Caching Name Server on your firewall.
Red Hat has an RPM for a
caching name server (the RPM also requires the
bindRPM) and for Bering users,
there is dnscache.lrp. If you take this approach,
you configure your internal systems to use the firewall itself as
their primary (and only) name server. You use the internal
IP address of the firewall (10.10.10.254 in the example above)
for the name server address. To allow your local systems to talk to
your caching name server, you must open port 53 (both
UDP and TCP) from the local
network to the firewall; you do that by adding the following rules
in /etc/shorewall/rules.
#ACTION SOURCE DEST PROTO DEST PORT(S)
DNS(ACCEPT)loc $FWOther ConnectionsThe two-interface sample includes the following rules:
#ACTION SOURCE DEST PROTO DEST PORT(S)
DNS(ACCEPT) $FW netThis rule allows
DNS access from your firewall and may be removed if you
uncommented the line in /etc/shorewall/policy
allowing all connections from the firewall to the Internet.In the rule shown above, DNS(ACCEPT)is an example of
a macro invocation. Shorewall includes a number of
macros (command shorewall show macros)
and you can add your own.You don't have to use defined macros when coding a rule in
/etc/shorewall/rules; Shorewall will start slightly
faster if you code your rules directly rather than using macros. The the
rule shown above could also have been coded as follows:#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT $FW net udp 53
ACCEPT $FW net tcp 53In cases where Shorewall doesn't include a defined macro to meet
your needs, you can either define the macro yourself or you can simply
code the appropriate rules directly.The sample also includes: #ACTION SOURCE DEST PROTO DEST PORT(S)
SSH(ACCEPT) loc $FW That rule allows you to run an
SSH server on your firewall and connect to that server
from your local systems.If you wish to enable other connections from your firewall to other
systems, the general format using a macro is: #ACTION SOURCE DEST PROTO DEST PORT(S)
<macro>(ACCEPT) $FW <destination zone>The
general format when not using defined macros is:#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT $FW <destination zone> <protocol> <port>Web Server on FirewallYou want to run a Web Server on your firewall system:
#ACTION SOURCE DEST PROTO DEST PORT(S)
Web(ACCEPT) net $FW
Web(ACCEPT) loc $FW Those two rules would of
course be in addition to the rules listed above under You can configure a Caching Name Server on your
firewall. If you don't know what port and protocol a particular
application uses, look here. I don't recommend enabling telnet to/from the
Internet because it uses clear text (even for login!). If you want
shell access to your firewall from the Internet, use
SSH:#ACTION SOURCE DEST PROTO DEST PORT(S)
SSH(ACCEPT) net $FWBering users will want to add the following two rules to be
compatible with Jacques's Shorewall configuration.#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT loc $FW udp 53 #Allow DNS Cache to work
ACCEPT loc $FW tcp 80 #Allow Weblet to workNow edit your /etc/shorewall/rules
file to add or delete other connections as required.Some Things to Keep in MindYou cannot test your firewall from the
inside. Just because you send requests to your firewall
external IP address does not mean that the request will be associated
with the external interface or the net zone. Any
traffic that you generate from the local network will be associated
with your local interface and will be treated as loc->fw
traffic.IP addresses are properties of systems,
not of interfaces. It is a mistake to believe that your
firewall is able to forward packets just because you can ping the IP
address of all of the firewall's interfaces from the local network.
The only conclusion you can draw from such pinging success is that the
link between the local system and the firewall works and that you
probably have the local system's default gateway set correctly.All IP addresses configured on firewall
interfaces are in the $FW (fw) zone. If 192.168.1.254 is
the IP address of your internal interface then you can write
$FW:192.168.1.254 in a
rule but you may not write loc:192.168.1.254. Similarly, it is
nonsensical to add 192.168.1.254 to the loc zone using an entry in
/etc/shorewall/hosts.Reply packets do NOT automatically follow
the reverse path of the one taken by the original request.
All packets are routed according to the routing table of the host at
each step of the way. This issue commonly comes up when people install
a Shorewall firewall parallel to an existing gateway and try to use
DNAT through Shorewall without changing the default gateway of the
system receiving the forwarded requests. Requests come in through the
Shorewall firewall where the destination IP address gets rewritten but
replies go out unmodified through the old gateway.Shorewall itself has no notion of inside
or outside. These concepts are embodied in how Shorewall is
configured.Starting and Stopping Your FirewallThe installation procedure
configures your system to start Shorewall at system boot but startup is
disabled so that your system won't try to start Shorewall before
configuration is complete. Once you have completed configuration of your
firewall, you must edit /etc/shorewall/shorewall.conf and set
STARTUP_ENABLED=Yes.Users of the .deb package must edit /etc/default/shorewall
and set startup=1. While you are editing shorewall.conf,
it is a good idea to check the value of the SUBSYSLOCK option. You can
find a description of this option by typing 'man shorewall.conf' at a
shell prompt and searching for SUBSYSLOCK.The firewall is started using the shorewall
start command and stopped using
shorewall stop. When the firewall is
stopped, routing is enabled on those hosts that have an entry in /etc/shorewall/routestopped
(Shorewall 4.5.7 and earlier) or in/etc/shorewall/stoppedrules.
A running firewall may be restarted using the shorewall
restart command. If you want to totally remove any trace
of Shorewall from your Netfilter configuration, use
shorewall clear.The two-interface sample assumes that you want to enable routing
to/from eth1 (the local network)
when Shorewall is stopped. If your local network isn't connected to
eth1 or if you wish to enable
access to/from other hosts, change /etc/shorewall/routestopped
accordingly. If you are connected to your firewall from the Internet, do not
issue a shorewall stop command
unless you have either:Used ADMINISABSENTMINDED=Yes in
/etc/shorewall/shorewall.conf; oradded an entry for the IP address that
you are connected from to /etc/shorewall/routestopped.Also, I don't recommend using shorewall
restart; it is better to create an alternate
configuration and test it using the shorewall
try command.The firewall will start after your network interfaces have been
brought up. This leaves a small window between the time that the network
interfaces are working and when the firewall is controlling connections
through those interfaces. If this is a concern, you can close that window
by installing the Shorewall Init
Package.If it Doesn't WorkRe-check each of the items flagged with a red arrow
above.Check your log.Check the Troubleshooting
Guide.Check the FAQ.Disabling your existing FirewallBefore starting Shorewall for the first time, it's a good idea to
stop your existing firewall. On older Redhat/CentOS/Fedora:service iptables stopOn recent Fedora systems that run systemd, the command is:systemctl stop iptables.serviceIf you are running SuSE, use Yast or Yast2 to stop
SuSEFirewall.On other systems that use a classic SysV init system:/etc/init.d/iptables stopOnce you have Shorewall running to your satisfaction, you should
totally disable your existing firewall. On older
Redhat/CentOS/Fedora:chkconfig --del iptablesOn Debian systems:update-rc.d iptables disableOn recent Fedora system running systemd:systemctl disable iptables.serviceAt this point, disable your existing firewall service.Additional Recommended ReadingI highly recommend that you review the Common Configuration File Features
page -- it contains helpful tips about Shorewall features than
make administering your firewall easier. Also, Operating Shorewall and
Shorewall Lite contains a lot of useful operational hints.Adding a Wireless Segment to your Two-Interface FirewallOnce you have the two-interface setup working, the next logical step
is to add a Wireless Network. The first step involves adding an additional
network card to your firewall, either a Wireless card or an Ethernet card
that is connected to a Wireless Access Point.When you add a network card, it won't necessarily be detected as
the next highest Ethernet interface. For example, if you have two
Ethernet cards in your system (eth0 and eth1) and you add a third card that uses
the same driver as one of the other two, that third card won't
necessarily be detected as eth2; it could rather be detected as
eth0 or eth1! You can either live with that or
you can shuffle the cards around in the slots until the new card is
detected as eth2.Update: Distributions are
getting better about this. SuSE now associates
a unique interface name with each MAC address. Other distributions
have add-on packages to manage the relationship between MAC addresses
and device names.Your new network will look similar to what is shown in the following
figure.The first thing to note is that the computers in your wireless
network will be in a different subnet from those on your wired local LAN.
In the above example, we have chosen to use the network 10.10.11.0/24.
Computers 3 and 4 would be configured with a default gateway IP address of
10.10.11.254.Second, we have chosen to include the wireless network as part of
the local zone. Since Shorewall allows intra-zone traffic by default,
traffic may flow freely between the local wired network and the wireless
network.There are only two changes that need to be made to the Shorewall
configuration:An entry needs to be added to
/etc/shorewall/interfaces for the wireless
network interface. If the wireless interface is wlan0, the entry might look like:#ZONE INTERFACE BROADCAST OPTIONS
loc wlan0 detect maclistAs shown in the above entry, I recommend using the maclist option for the wireless
segment. By adding entries for computers 3 and 4 in
/etc/shorewall/maclist, you help ensure that your
neighbors aren't getting a free ride on your Internet connection.
Start by omitting that option; when you have everything working, then
add the option and configure your
/etc/shorewall/maclist file.You may need to add an entry to the
/etc/shorewall/masq file to masquerade traffic
from the wireless network to the Internet. If you file looks like
this:#INTERFACE SOURCE ADDRESS PROTO PORT(S) IPSEC MARK
eth0 10.0.0.0/8,\
169.254.0.0/16,\
172.16.0.0/12,\
192.168.0.0/16
then you do not need to change
the contents.Otherwise, if your Internet interface is eth0 and your wireless interface is
wlan0, the entry would
be:#INTERFACE SOURCE ADDRESS
eth0 10.10.11.0/24One other thing to note. To get Microsoft
networking working between the wireless and wired networks, you will need
either a WINS server or a PDC. I personally use Samba configured as a WINS
server running on my firewall. Running a WINS server on your firewall
requires the rules listed in the Shorewall/Samba
documentation.
shorewall-docs-xml-5.0.4/shorewall_prerequisites.xml 0000644 0000000 0000000 00000011036 12647470621 021462 0 ustar root root
Shorewall RequirementsTomEastep2001-2006Thomas M EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.This article applies to Shorewall 4.3 and
later. If you are running a version of Shorewall earlier than Shorewall
4.3.5 then please see the documentation for that
release.Shorewall Requires:A Linux kernel that supports
Netfilter (No, it won't work on BSD or Solaris). I've tested with
2.4.2 - 2.6.16. Check here for kernel
configuration information.iptables 1.2 or later (but I recommend at least version
1.3.3)Iproute (ip and "tc" utilities). The iproute
package is included with most distributions but may not be installed
by default. The official download site is http://developer.osdl.org/dev/iproute2/download/.
Note that the Busybox versions of the iproute2 utilities
(ip and tc) do not
support all of the features required for advanced Shorewall
use.A Bourne shell or derivative such as bash or ash. This shell
must have correct support for variable expansion formats
${variable%pattern},
${variable%%pattern},
${variable#pattern} and
${variable##pattern}.Your shell must produce a sensible result when a number n (128
<= n <= 255) is left shifted by 24 bits. You can check this at a
shell prompt by:echo $((128 << 24))The result must be either 2147483648 or
-2147483648.The firewall monitoring display is greatly improved if you have
awk (gawk) installed.On the system where the Shorewall package itself is installed,
you must have Perl installed (preferably Perl 5.8.10):If you want to be able to use DNS names in your Shorewall6
configuration files, then Perl 5.10 is required together with the
Perl Socket6 module.Perl Cwd ModulePerl File::Basename ModulePerl File::Temp ModulePerl Getopt::Long ModulePerl Carp ModulePerl FindBin ModulePerl Scalar::Util Module
shorewall-docs-xml-5.0.4/VPNBasics.xml 0000644 0000000 0000000 00000035437 12647470621 016301 0 ustar root root
VPN, Netfilter and Shorewall — The BasicsTomEastep200420052006Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Gateway-to-gateway traffic vs. Host-to-host traffic.The purpose of a Virtual Private Network
(VPN) is to provide for secure communication between a set of hosts.
Communication between a pair of hosts connected by a VPN occurs in
stages:Local-host-to-local-gateway.
This communication is not encrypted; in the case where the traffic
originates on the gateway itself, the communication is local to that
system.Local-gateway-to-remote-gateway. This
communication is encrypted and can use a tunneling protocol such as
GRE, AH or ESP or a standard protocol such as UDP or TCP. Some VPNs
use multiple protocols; for example PPTP uses TCP port 1723 and GRE
while IPSEC uses UDP port 500 together with ESP or AH.Remote-gateway-to-remote-host.
This is just the unencrypted traffic described in the first item as it
is delivered to its destination.Of course, one-way communication generally isn't useful so we need
traffic in the other direction as well.Remote-host-to-remote-gateway.Remote-gateway-to-local-gateway.Local-gateway-to-local-host.Relationship to NetfilterWhen Netfilter is configured on a VPN gateway, each VPN packet goes
through Netfilter twice! Let's first consider outbound traffic:Local-host-to-local-gateway.
This traffic has a source address in the local network or on the
gateway itself. The destination IP address is that of a remote host;
either the remote gateway itself or a host behind that gateway.Local-gateway-to-remote-gateway. This
(encrypted) traffic has a source IP address on the gateway and is
addressed to the remote gateway.Incoming traffic is similar.What does this mean with Shorewall?When Shorewall is installed on a VPN gateway system, it categorizes
the VPN-related traffic slightly differently:Local-host-to-remote-host —
same as Local-host-to-local-gateway
above.Local-gateway-to-remote-gateway.Remote-gateway-to-local-gateway.Remote-host-to-local-host —
same as Local-gateway-to-local-host
above.Shorewall implements a set of features for dealing with VPN.The /etc/shorewall/tunnels file. This file
is used to define remote gateways and the type of encrypted traffic
that will be passed between the Shorewall system and those remote
gateways. In other words, the tunnels file deals with Local-gateway-to-remote-gateway and Remote-gateway-to-local-gateway traffic.The /etc/shorewall/zones file. An entry in
this file allows you to associated a name with the set of hosts behind
the remote gateway (or to the remote gateway itself if it is a
standalone system).The /etc/shorewall/interfaces and
/etc/shorewall/hosts files. These files are used
to associate a set of remote hosts with the zone name defined in
/etc/shorewall/zones.The /etc/shorewall/policy and
/etc/shorewall/rules files. These files are used
to define the connections that are permitted between the remote and
local hosts -- in other words, the Local-host-to-remote-host and Remote-host-to-local-host traffic.Defining Remote ZonesMost VPN types are implemented using a virtual network device such
as pppN (e.g., ppp0), tunN (e.g., tun0), etc. This means that in most
cases, remote zone definition is similar to zones that you have already
defined./etc/shorewall/zones:#ZONE TYPE
fw firewall
net ipv4
loc ipv4
rem ipv4/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTION
net eth0 - tcpflags,routefilter
loc eth1 -
rem ppp0 -Allowing TrafficNormally, you will just allow all traffic between your remote
client(s) and the local zone. You can do that with a couple of
policies:#SOURCE DESTINATION POLICY LEVEL BURST/LIMIT
rem loc ACCEPT
loc rem ACCEPTSimilar policies using $FW rather than 'loc' can permit traffic from
the remote clients to/from the firewall.Different Firewall Policies for Different Remote SystemsThe /etc/shorewall/hosts file comes into play when:You have a number of remote networks.The remote networks have different firewall requirements and you
want to divide them into multiple zones.There is no fixed relationship between the remote networks and
virtual network devices (for example, the VPN uses PPTP and remote
gateways connect on demand).In this case, your configuration takes the following
approach:etc/shorewall/zones:#ZONE TYPE OPTIONS
net ipv4
loc ipv4
rem1 ipv4 #Remote LAN 1
rem2 ipv4 #Remote LAN 2/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTION
net eth0 - tcpflags,routefilter
loc eth1 -
- tun+ -/etc/shorewall/hosts:#ZONE HOST(S) OPTIONS
rem1 tun+:10.0.0.0/24
rem2 tun+:10.0.1.0/24The /etc/shorewall/hosts file is also used with
kernel 2.6 native IPSEC.Eliminating the /etc/shorewall/tunnels fileThe /etc/shorewall/tunnels file provides no
functionality that could not be implemented using entries in
/etc/shorewall/rules and I have elimination of the
/etc/shorewall/tunnels file as a long-term goal. The
following sections show how entries in
/etc/shorewall/tunnels can be replaced by rules for
some common tunnel types.IPSEC/etc/shorewall/tunnels:
#TYPE ZONE GATEWAY GATEWAY ZONE
ipsec Z1 1.2.3.4 Z2
The "noah" option causes the rules for protocol 51 to be
eliminated. The "ipsecnat" causes UDP port 4500 to be accepted in both
directions. If no GATEWAY ZONE is given then the last two rules above
are omitted.PPTP/etc/shorewall/tunnels:
#TYPE ZONE GATEWAY GATEWAY ZONE
pptpserver Z1 1.2.3.4
/etc/shorewall/rules:
#ACTION SOURCE DEST PROTO DEST SOURCE
# PORT PORT(S)
ACCEPT Z1:1.2.3.4 $FW tcp 1723
ACCEPT $FW Z1:1.2.3.4 47
ACCEPT Z1:1.2.3.4 $FW 47
Tunnel type "pptpclient" simply reverses the direction of the tcp
port 1723 rule.OpenVPN/etc/shorewall/tunnels:
#TYPE ZONE GATEWAY GATEWAY ZONE
openvpn:port Z1 1.2.3.4
/etc/shorewall/rules:
#ACTION SOURCE DEST PROTO DEST SOURCE
# PORT PORT(S)
ACCEPT Z1:1.2.3.4 $FW udp port
ACCEPT $FW Z1:1.2.3.4 udp port
/etc/shorewall/tunnels:
#TYPE ZONE GATEWAY GATEWAY ZONE
openvpnclient:port Z1 1.2.3.4
/etc/shorewall/rules:
#ACTION SOURCE DEST PROTO DEST SOURCE
# PORT PORT(S)
ACCEPT Z1:1.2.3.4 $FW udp - port
ACCEPT $FW Z1:1.2.3.4 udp port
/etc/shorewall/tunnels:
#TYPE ZONE GATEWAY GATEWAY ZONE
openvpnserver:port Z1 1.2.3.4
/etc/shorewall/rules:
#ACTION SOURCE DEST PROTO DEST SOURCE
# PORT PORT(S)
ACCEPT Z1:1.2.3.4 $FW udp port
ACCEPT $FW Z1:1.2.3.4 udp - port
Links to Other VPN Articles at shorewall.netOpenVPNIPSECPPTP
shorewall-docs-xml-5.0.4/GenericTunnels.xml 0000644 0000000 0000000 00000010564 12647470621 017430 0 ustar root root
Generic TunnelsTomEastep2001200220032005Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Shorewall includes built-in support for a wide range of VPN solutions.
If you have need for a tunnel type that does not have explicit support, you
can generally describe the tunneling software using generic
tunnels.Bridging two Masqueraded NetworksSuppose that we have the following situation:We want systems in the 192.168.1.0/24 subnetwork to be able to
communicate with the systems in the 10.0.0.0/8 network. This is
accomplished through use of the /etc/shorewall/tunnels file, the
/etc/shorewall/policy file and the /etc/shorewall/tunnel script that is
included with Shorewall.Suppose that you have tunneling software that uses two different
protocols:TCP port 1071GRE (Protocol 47)The tunnel interface on system A is tun0 and the
tunnel interface on system B is also tun0.On each firewall, you will need to declare a zone to represent the
remote subnet. We'll assume that this zone is called vpn
and declare it in /etc/shorewall/zones on both systems as follows.#ZONE TYPE OPTIONS
vpn ipv4On system A, the 10.0.0.0/8 will comprise the vpn zone. In /etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
vpn tun0 10.255.255.255In /etc/shorewall/tunnels on system A, we need the following:#TYPE ZONE GATEWAY GATEWAY ZONE
generic:tcp:1071 net 134.28.54.2
generic:47 net 134.28.54.2These entries in /etc/shorewall/tunnels, opens the firewall so that
TCP port 1071 and the Generalized Routing Encapsulation Protocol (47) will
be accepted to/from the remote gateway.#ZONE INTERFACE BROADCAST OPTIONS
vpn tun0 192.168.1.255In /etc/shorewall/tunnels on system B, we have:#TYPE ZONE GATEWAY GATEWAY ZONE
generic:tcp:1071 net 206.191.148.9
generic:47 net 206.191.148.9You will need to allow traffic between the vpn zone
and the loc zone on both systems -- if you simply want to
admit all traffic in both directions, you can use the policy file:#SOURCE DEST POLICY LOG LEVEL
loc vpn ACCEPT
vpn loc ACCEPTOn both systems, restart Shorewall and start your VPN software on
each system. The systems in the two masqueraded subnetworks can now talk
to each other
shorewall-docs-xml-5.0.4/survey-200603.xml 0000644 0000000 0000000 00000050766 12647470621 016600 0 ustar root root
The Shorewall Environment Survey 2006PaulGear2006Paul D. GearPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.BackgroundIn early March 2006, i embarked on the journey of surveying
Shorewall users. Initially this sprang from my own curiosity: i thought
that some of the systems at work on which i use Shorewall may be bigger
and more complex than most others, and i wanted to find out if there are
people out there who use Shorewall like i do. As started thinking about
the questions i would ask, i realised that if i asked the right questions,
i could create a survey that might help the Shorewall project better to
understand its users.I used Zoomerang to
create the survey. It has a number of tools that make it easy to create
useful surveys. To get the most benefit out of Zoomerang, you have to
subscribe to their professional version.In the long term, it would be great to have a practical free
software alternative that could be self-hosted. A number of free content
management systems such as Drupal
have a survey module, but when i last looked at them, they were more
limited and harder to use than Zoomerang.Survey and results linksThe survey is still open as of this writing, and can be accessed
at the
Zoomerang survey page. Further participation is encouraged. The
figures quoted in this document reflect the results at the time of
writing.The public
results of the survey are available. If you complete the survey,
a link to the results is provided on the thank you page.Sample sizeAn important note about this survey is that it has a small sample
size (103 complete responses at the time of writing), so any conclusions
drawn should be considered tentative.To speculate on the overall number of users that this sample
represents, the Debian popularity
contest reports 478 installations of Shorewall, 285 of which are
in active use. Assuming that the popularity contest represents 30% of
the Debian installed base (likely ridiculously optimistic), this would
make the number of active Shorewall systems approximately:285 / 0.3 (percentage of Debian systems) / 0.26 (percentage Debian
holds of all distributions) = 3654 (rounding up the numbers to the
nearest whole, and assuming the percentages extrapolate
regularly)This means that our survey represents a maximum of 2.8% of the
installed base, likely far less.Other possible inaccuraciesAdditionally, since the survey was open to multiple responses, it
could be that some people answered the questions about themselves more
than once, despite instructions to the contrary in the introduction
page.There is an error in the released version of the survey for
question 15 (RAM size): it was a multiple choice question rather than
single choice, and thus there were more results than expected. The
number of errors doesn't seem to be significant.If you notice any errors in this analysis, or have any suggestions
about how to improve it, please contact the author at pgear@shorewall.net.Results analysisOrganisationsSmall organisations dominate the spectrum of Shorewall users. The
largest group (44%) was 1-10 users - mostly SOHO LANs based on the
comments in that section. Ninety percent (90%) of Shorewall
installations are in organisations with less than 500 users. The results
for the questions about organisational size and the number of users
serviced by Shorewall match fairly closely, which seems to indicate that
the majority of Shorewall systems are servicing the entire organisation
in question.The vast majority (84%) of Shorewall systems are administered by
only one person. One question that needs to be asked is, "Why?" Possible
reasons for this might be:Most of the organisations in which it is used are small, thus
most of them will only have one person skilled in the area of packet
filtering firewalls. This seems a likely scenario, but a cross
correlation of the results of questions 1 and 2 with question 3
indicates that the number of administrators is fairly uniform across
all sizes of organisation and user base.Shorewall works so well that people don't have to touch it
much. Obviously, this is the preferred interpretation of the
Shorewall project team. :-)Shorewall is too hard for new users to comprehend, so one
skilled person in an organisation tends to get the job maintaining
it. Equally obviously, this is a non-preferred interpretation. :-)
However, being a firewall generator, Shorewall is not likely to
attract the same sort of users as a web browser or music
player.Shorewall administrators are a closed bunch and don't like
sharing their job around. Given the nature of firewalls and packet
filtering, this doesn't seem far-fetched.There doesn't seem to be an easy answer to thus question. In
retrospect, since there were no responses indicating 10 or more
administrators, i could have made the granularity of this question
better. A question about a person's role in the organisation may also
have been helpful. Possibly we could follow up with a smaller survey,
specifically about the people and organisations who use
Shorewall.UsersUnsurprisingly, 97% of survey respondents were male. Or to put it
another way: surprisingly, there are actually 3 female Shorewall users.
:-) Being male seems to be an occupational hazard of life in the IT
industry, and even more so in the more "nerdy" specialisations like
Linux and security.The largest age group of users is 25-34 years (42% of all
respondents). There were no retirees (65 and over) or minors (under 18)
in the responses. The distribution of the remaining age groups was
fairly even.The largest group of users in terms of education was those with a
Bachelor's degree, followed by those with a high school education.
Fifty-seven percent (57%) of Shorewall users have a Bachelor's degree or
better. Many users' highest qualifications are not in an IT-related
discipline (42%). This remains fairly constant across the spectrum when
correlated with the highest level of qualifications. Those who do not
claim IT as their highest discipline come from a wide variety of other
fields, including agriculture, art, business, chemistry, education,
various forms of engineering, law, mathematics, physics, and
theology.Almost two-thirds of users (62%) use Shorewall as part of their
paid employment. Of these, 12% (7 of 58) do not use Shorewall as part of
their official duties. Cross correlation with level of education
revealed no major variance in this trend depending on level of
education.The majority of users (73%) began using the Internet in the 1990s.
A smaller majority (61%) have been using the Internet for more than 12
years (1994 or earlier). (The single response indicating use of the
Internet (then ARPANET) since the 1960s seems to be an error.)The majority of users (70%) began using Linux after it reached a
certain stage of maturity - around or after the release of kernel 2.0
(1996). However, nearly all respondents (97%) have been using Linux for
5 years or more, with almost half (47%) having 10 or more years
experience with it. It seems fair to say that as a rule, Shorewall
attracts people with plenty of experience.Around one third of users (30%) have been using Shorewall for more
than 5 years, with two-thirds (66%) having used it since the 1.x series
(2003 or earlier). It seems fair to say that Shorewall users seem to
stick with the product once they are familiar with it. On the other
hand, it seems that Shorewall is not attracting large numbers of new
users, which is a concern for the future of the project.HardwareNinety-three percent (93%) of users run Shorewall on i386 family
hardware, with a further 6% running it on x86-64/EM64T platforms. One
response was received indicating use of Shorewall on MIPS (Linksys WRT
platform). No responses were received for any other hardware platform.
While it is not surprising that Intel would be dominant, given their
market share, it seems a little skewed not to have any representatives
of other architectures.A good spread of CPU power is shown in the survey responses. The
largest group was 400-999 MHz (30%), with only 16% of responses
indicating less than 400 MHz, and the same number greater than 2500 MHz.
A number of responses in the field for additional information suggested
that the machines used were either recycled desktops, or systems that
were specifically built to do the job, and had been running in that role
for a number of years.RAM configuration seemed to mostly mirror CPU power, with a slight
bias towards higher RAM figures. The majority (52%) of systems have
between 256 and 1023 MB; only 11% of systems have less than 128 MB; 28%
have 1024 MB or more. This reflects the more server-oriented workload
that many Shorewall systems run (see the section on server roles
below).Shorewall systems on the whole tend toward smaller OS hard disks,
with 42% having disks 39 GB or smaller. The largest group by a small
margin was 80-159 GB at 23%, with 10-39 GB and 0-9 GB coming in a close
second and third at 22% and 20% respectively.NetworkThe majority of Shorewall systems (82%) use between two and four
network interfaces. The number of devices connected to systems closely
mirrors the size of the organisations in which they are used, with 95%
of systems connecting less than 500 devices, and the largest group (41%)
connecting 2-10 other devices.Ninety percent (90%) of Shorewall systems are connected to 100
Mbps or faster local networks. Most systems have a broadband Internet
connection or better, with only 7% having 512 Kbps or less, and 51%
having 10 Mbps or better. DSL is the most common form of Internet
connection, with over half the responses (51%).SoftwareThe most popular Linux distribution on which users run Shorewall
is Debian (26% of respondents), followed by a group consisting of Fedora
Core (16%), Red Hat 9 and earlier (13%) and Red Hat Enterprise and
derivatives (12%). The next group consists of SUSE (9%), Slackware (8%),
Gentoo (6%), and LEAF/Bering (5%).The message about maintaining an up-to-date Shorewall system seems
to have gotten through, with 61% of respondents running the latest
stable version (3.0), and an additional 22% running the previous stable
version (2.4). Only 14% of users are running unsupported older versions
(2.2 and previous).The most common roles played by Shorewall systems are:External firewall/router (78%)DNS name server (61%)DHCP server (59%)Internal firewall/router (56%)Time server (55%)Comments from usersFollowing is a sample of the comments we received about the survey
- they have been carefully sanitised to make us look good. ;-)More power to Shorewall!Shorewall Rocks! I'm amazed how easy it is every time I need
to do something, even if it's been 6+ months since the last change!
:)Good job and a great product.Shorewall is good, I have recommended it to several people,
mostly working in the University & academic areas.Thanks to everyone who contributes to Shorewall. That's a
*great* piece of software!Shorewall has been incredible. Tom has given so much of
himself to this project, I can only say thank you from one person, I
look up to people like him. I have used Shorewall for many systems,
I am a contractor that "set up shop" all over the world. Depending
on the available ISP services, this project has been flexible in
every situation to date. Also, depending on my needs, it has done
the same. "IP Tables made easy" is really an accurate
description.I'm quite interested in seeing what the 'cross section' of
Shorewall users are like. It's made my life a lot easier over the
years. Thank you.Lessons learned about survey techniqueTreat surveys like releasing free softwaretest on a small group before you go publicrelease early and oftenmake branches (copies) when you release alpha and beta
versionsmerge the changes from branches (lessons you learned in those
versions) into the main trunkStart small and work towards what you want to know with specific,
concrete questionsI tried to do everything in one survey, and ended up confusing
some people. For example, despite the fact that the survey's start page
clearly says "Please answer the questions for only ONE SYSTEM running
Shorewall", i received multiple comments saying that they couldn't
answer accurately because they ran more than one Shorewall
system.It would have been better to have two surveys: one about the
people who use Shorewall, and another about the systems they run it on.
Better still would be for Shorewall to automatically collect appropriate
information about systems and request permission to send it to a central
location for statistical analysis. How to do this and maintain users'
privacy and obtain their permission efficiently is not an easy problem
with a product like Shorewall, which doesn't actually stay running on
user systems, and doesn't present a user interface per se.Be prepared beforehandWithin hours of the survey's release, 50% of the results were in.
Within 3 days, it hit the Zoomerang basic survey limit of 100 responses.
I had not planned for such an enthusiastic response, and also was too
busy to download all of the results before the survey's time limit
expired. Fortunately, i was able to obtain funding to allow a Zoomerang
"pro" subscription to be purchased and thus provide advanced analysis,
and complete downloads of the results.Incrementally improve your surveysThe final version of this survey was released still with a few
bugs. The released version was just a copy of my master survey, and i
continued to maintain the master after the final survey was released
(and during this analysis), and i'm sure the next version will be even
better.Possible implications for the Shorewall projectThe users we have seem, on the whole, rather experienced, and very
loyal. However, we don't seem to be attracting new users, despite new
features such as multi-ISP support and integrated traffic shaping. The
question about a GUI comes up frequently, and one wonders whether this is
would make a significant difference in Shorewall's uptake with new
users.Shorewall seems to be predominantly used in small, i386-based
environments such as home LANs and small businesses. It seems to be
frequently combined with a number of other basic functions, such as DNS,
DHCP, NTP, VPN. Integration with (or perhaps providing a plug-in module
for) a dedicated gateway distribution such as ipcop, Smoothwall, or Clark
Connect might be a good way to serve the needs of our users.Possible implications for other free software projectsThe essence of free software is software by the people, for the
people. Knowing who the people are and what their needs are is
critical to this process.If at all possible, build statistics gathering into your
application, and find a way to encourage people to use it. This
concrete data will help confirm the results of any surveys you might
conduct.
shorewall-docs-xml-5.0.4/Internals.xml 0000644 0000000 0000000 00000102130 12647470621 016431 0 ustar root root
Shorewall InternalsTomEastep2012Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.IntroductionThis document provides an overview of Shorewall internals. It is
intended to ease the task of approaching the Shorewall code base by
providing a roadmap of what you will find there.HistoryShorewall was originally written entirely in Bourne Shell. The
chief advantage of this approach was that virtually any platform
supports the shell, including small embedded environments. The initial
release was in early 2001. This version ran iptables, ip, etc.
immediately after processing the corresponding configuration entry. If
an error was encountered, the firewall was stopped. For this reason, the
routestopped file had to be very simple and
foolproof.In Shorewall 3.2.0 (July 2006), the implementation was changed to
use the current compile-then-execute architecture. This was
accompilished by modifying the existing code rather than writing a
compiler/generator from scratch. The resulting code was fragile and hard
to maintain. 3.2.0 also marked the introduction of
Shorewall-lite.By 2007, the compiler had become unmaintainable and needed to be
rewritten. I made the decision to write the compiler in Perl and
released it as a separate Shorewall-perl packets in Shorewall 4.0.0
(July 2007). The shell-based compiler was packaged in a Shorewall-shell
package. An option (SHOREWALL_COMPILER) in shorewall.conf specified
which compiler to use. The Perl-based compiler was siginificantly
faster, and the compiled script also ran much faster thanks to its use
of iptables-restore.Shorewall6 was introduced in Shorewall 4.2.4 (December
2008).Support for the old Shell-based compiler was eliminated in
Shorewall 4.4.0 (July 2009).Shorewall 4.5.0 (February 2012) marked the introduction of the
current architecture and packaging.ArchitectureThe components of the Shorewall product suite fall into five broad
categories:Build/Install subsystemCommand Line Interface (CLI)Run-time LibrariesCompilerConfiguration files (including actions and macros)Build/Install SubsystemThe Shorewall Build/Install subsystem packages the products for
release and installs them on an end-user's or a packager's system. It
is diagrammed in the following graphic.The build environment components are not released and are
discussed in the Shorewall Build
Article.The end-user/packager environment consists of the
configure and configure.pl
programs in Shorewall-core and an install.sh
program in each product.CLIThe CLI is written entirely in Bourne Shell so as to allow it to
run on small embedded systems within the -lite products. The CLI
programs themselves are very small; then set global variables then
call into the CLI libraries. Here's an example
(/sbin/shorewall):PRODUCT=shorewall
#
# This is modified by the installer when ${SHAREDIR} != /usr/share
#
. /usr/share/shorewall/shorewallrc
g_program=$PRODUCT
g_libexec="$LIBEXECDIR"
g_sharedir="$SHAREDIR"/shorewall
g_sbindir="$SBINDIR"
g_perllib="$PERLLIBDIR"
g_confdir="$CONFDIR"/shorewall
g_readrc=1
. $g_sharedir/lib.cli
shorewall_cli $@As you can see, it sets the PRODUCT variable, loads the
shorewallrc file, sets the global variables (all of which have names
beginning with "g_", loads lib.cli, and calls
shorewall_cli passing its own arguments.There are two CLI libraries: lib.cli in
Shorewall Core and lib.cli-std in Shorewall. The
lib.cli library is always loaded by the CLI
programs; lib-cli-std is also loaded when the
product is 'shorewall' or 'shorewall6'.
lib.cli-std overloads some functions in
lib.cli and also provides logic for the
additional commands supported by the full products.The CLI libraries load two additional Shell libraries from
Shorewall.core: lib.base and
lib.common (actually,
lib.base loads lib.common).
These libraries are separete from lib.cli for
both historical and practicle reasons. lib.base
(aka functions) can be loaded by application programs, although this
was more common in the early years of Shorewall. In addition to being
loaded by the CLIs, lib.common is also copied
into the generated script by the compilers.Run-time LibrariesThare are two libraries that are copied into the generated
script by the compiler: lib.common from
Shorewall-core and lib.core from Shorewall. The
"outer block" of the generated script comes from the Shorewall file
prog.footer.CompilerWith the exception of the getparams Shell
program, the compiler is written in Perl. The compiler main program is
compiler.pl from Shorewall.conf; it's run-line arguments are described
in the Shorewall Perl
Article. It is invoked by the compiler
function in lib.cli-std.The compiler is modularized as follows:Accounting.pm (Shorewall::Accounting).
Processes the accounting file.Chains.pm (Shorewall::Chains). This is
the module that provides an interface to iptables/Netfilter for
the other modules. The optimizer is included in this
module.Config.pm (Shorewall::Config). This is
a multi-purpose module that supplies several related
services:Error and Progress message production.Pre-processor. Supplies all configuration file handling
including variable expansion, ?IF...?ELSE...?ENDIF processing,
INCLUDE directives and embedded Shell and Perl.Output script file creation with functions to write into
the script. The latter functions are no-ops when the
check command is being executed.Capability DetectionMiscellaneous utility functions.Compiler.pm (Shorewall::Compiler). The
compiler() function in this module contains the top-leve of the
compiler.IPAddrs.pm (Shorewall::IPAddrs) - IP
Address validation and manipulation (both IPv4 and IPv6). Also
interfaces to NSS for protocol/service name resolution.Misc.pm (Shorewall::Misc) - Provides
services that don't fit well into the other modules.Nat.pm (Shorewall::Nat) - Handles all
nat table rules. Processes the masq,
nat and netmap
files.Proc.pm (Shorewall::Proc) - Handles
manipulation of /proc/sys/.Providers.pm (Shorewall::Providers) -
Handles policy routing; processes the
providers file.Proxyarp.pm (Shorewall::Proxyarp) -
Processes the proxyarp file.Raw.pm (Shorewall::Raw) - Handles the
raw table; processes the conntrack (formerly
notrack) file.Rules.pm (Shorewall::Rules) - Contains
the logic for process the policy and
rules files, including
macros and
actions.Tc.pm (Shorewall::Tc) - Handles traffic
shaping.Tunnels.pm (Shorewall::Tunnels) -
Processes the tunnels file.Zones.pm (Shorewall::Zones) - Processes
the zones, interfaces
and hosts files. Provides the interface to
zones and interfaces to the other modules.Because the params file can contain arbitrary shell code, it
must be processed by a shell. The body of
getparams is as follows:# Parameters:
#
# $1 = Path name of params file
# $2 = $CONFIG_PATH
# $3 = Address family (4 or 6)
#
if [ "$3" = 6 ]; then
PRODUCT=shorewall6
else
PRODUCT=shorewall
fi
#
# This is modified by the installer when ${SHAREDIR} != /usr/share
#
. /usr/share/shorewall/shorewallrc
g_program="$PRODUCT"
g_libexec="$LIBEXECDIR"
g_sharedir="$SHAREDIR"/shorewall
g_sbindir="$SBINDIR"
g_perllib="$PERLLIBDIR"
g_confdir="$CONFDIR/$PRODUCT"
g_readrc=1
. $g_sharedir/lib.cli
CONFIG_PATH="$2"
set -a
. $1 >&2 # Avoid spurious output on STDOUT
set +a
export -pThe program establishes the environment of the Shorewall or
Shoreall6 CLI program since that is the environment in which the
params file has been traditionally processed. It
then sets the - option so that all newly-created
variables will be exported and invokes the
params file. Because the
STDOUT file is a pipe back to the compiler, no spurious output must be
sent to that file; so getparams redirect
params output to STDOUT. After the script has
executed, an export -p command is executed to send
the contents of the environ array back to the compiler.Regrettably, the various shells (and even different versions of
the same shell) produce quite different output from export
-p. The Perl function Shorewall::Config::getparams() detects
which species of shell was being used and stores the variable settings
into the %params hash. Variables that are also in %ENV are only stored
in %params if there value in the output from the
getparams script is different from that in
%ENV.Configuration FilesThe configuration files are all well-documented. About the only
thing worth noting is that some macros and actions are duplicated in
the Shorewall and Shorewall6 packages. Because the Shorewall6 default
CONFIG_PATH looks in ${SHAREDIR}/shorewall6 before looking in
${SHARDIR_/shorewall, this allows Shorewall6 to implement
IPv6-specific handling where required.The Generated ScriptThe generated script is completely self-contained so as to avoid
version dependencies between the Shorewall version used to create the
script and the version of Shorewall-common installed on the remote
firewall.The operation of the generated script is illustrated in this
diagram.The Netfilter ruleset is sometimes dependent on the environment
when the script runs. Dynamic IP addresses and gateways, for example,
must be detected when the script runs. As a consequence, it is the
generated script and not the compiler that creates the input for
iptables-restore. While that input could be passed to iptables-restore
in a pipe, it is written to
${VARDIR}/.iptables_restore-input so that it is
available for post-mortem analysis in the event that iptables-restore
fails. For the other utilities (ip, tc, ipset, etc), the script runs
them passing their input on the run-line.Compiler InternalsBecause the compiler is the most complex part of the Shorewall
product suite, I've chosen to document it first. Before diving into the
details of the individual modules, lets take a look at a few general
things.ModularizationWhile the compiler is modularized and uses encapsulation, it is
not object-oriented. This is due to the fact that much of the compiler
was written by manually translating the earlier Shell code.Module data is not completely encapsulated. Heavily used tables,
most notably the Chain Table (%chain_table) in Shorewall::Chains is
exported for read access. Updates to module data is always
encapsulated.Module InitializationWhile currently unused and untested, the Compiler modules are
designed to be able to be loaded into a parent Perl program and the
compiler executed repeatedly without unloading the modules. To
accomodate that usage scenario, variable data is not initialized at
declaration time or in an INIT block, but is rather initialized in an
initialize function. Because off of these
functions have the same name ("initialize"), they are not exported but
are rather called using a fully-qualified name (e.g.,
"Shorewall::Config::initialize").Most of the the initialization functions accept arguements. Those
most common argument is the address family (4 or 6), depending on
whether an IPv4 or IPv6 firewall is being compiled. Each of the modules
that are address-family dependent have their own $family private (my)
variable.Module DependenceHere is the module dependency tree. To simplify the diagram,
direct dependencies are not shown where there is also a transitive
dependency.Config ModuleAs mentioned above, the Config module offers several related
services. Each will be described in a separate sub-section.Pre-processorUnlike preprocessors like ccp, the Shorewall pre-processor does
it's work each time that the higher-level modules asks for the next
line of input.The major exported functions in the pre-processor are:open_file( $ )The single argument names the file to be opened and is
usually a simple filename such as
shorewall.conf. open_file calls find_file who traverses the CONFIG_PATH
looking for a file with the requested name. If the file is found
and has non-zero size, it is opened, module-global variables are
set as follows, and the fully-qualified name of the file is
returned by the function.$currentfileHandle for the file open$currentfilename (exported)The fully-qualified name of the file.$currentlinenumberSet to zero.If the file is not found or if it has zero size, false
('') is returned.push_open( $ )Sometimes, the higher-level modules need to suspend
processing of the current file and open another file. An obvious
example is when the Rules module encounters a macro invocation
and needs to process the corresponding macro file. The push_open
function is called in these cases.push_open pushes
$currentfile, $currentfilename, $currentlinenumber and $ifstack onto @includestack, copies @includestack into a local array, pushes
a reference to the local array onto @openstack, and empties @includestackAs its final step, push_open calls open_file.pop_open()The pop_open function
must be called after the file opened by push_open is processed. This is true even
in the case where push_open
returned false.pop_open pops @openstack and restores $currentfile, $currentfilename, $currentlinenumber, $ifstack and @includestack.close_file()close_file is called to
close the current file. Higher-level modules should only call
close_file to close the current
file prior to end-of-file.first_entry( $ )This function is called to specify what happens when the
first non-commentary and no-blank line is read from the open
file. The argument may be either a scalar or a function
reference. If the argument is a scalar then it is treaded as a
progress message that should be issued if the VERBOSITY setting
is >= 1. If the argument is a function reference, the
function (usually a closure) is called.first_entry may called
after a successful call to open_file. If it is not called, then the
pre-processor takes no action when the first non-blank
non-commentary line is found.first_entry returns no
significant value.read_a_line( $ )This function delivers the next logical input line to the
caller. The single argument is defined by the following
constants:use constant { PLAIN_READ => 0, # No read_a_line options
EMBEDDED_ENABLED => 1, # Look for embedded Shell and Perl
EXPAND_VARIABLES => 2, # Expand Shell variables
STRIP_COMMENTS => 4, # Remove comments
SUPPRESS_WHITESPACE => 8, # Ignore blank lines
CHECK_GUNK => 16, # Look for unprintable characters
CONFIG_CONTINUATION => 32, # Suppress leading whitespace if
# continued line ends in ',' or ':'
DO_INCLUDE => 64, # Look for INCLUDE <filename>
NORMAL_READ => -1 # All options
};The actual argument may be a bit-wise OR of any of these
constants.The function does not return the logical line; that line
is rather stored in the module-global variable $currentline (exported). The function
simply returns true if a line was read or false if end-of-file
was reached. read_a_line
automatically calls close_file
at EOF.split_line1Most of the callers of read_a_line want to treat each line as
whitespace-separated columns. The split_line and split_line1 functions return an array
containing the contents of those columns.The arguments to split_line1 are:A =>
column-number pair for each of
the columns in the file. These are used to process lines
that use the alternate input
methods and also serve to define the number of
columns in the file's records.A hash reference defining
=> number-of-columns pairs.
For example "{ COMMENT => 0, FORMAT 2 }" allows COMMENT
lines of an unlimited number of space-separated tokens and
it allows FORMAT lines with exactly two columns. The hash
reference must be the last argument passed.If there are fewer space-separated tokens on the line than
specified in the arguments, then "-" is returned for the omitted
trailing columns.split_linesplit_line simply returns
split_line1( @_, {} ).Error and Progress Message ProductionThere are several exported functions dealing with error and
warning messages:fatal_errorThe argument(s) to this function describe the error. The
generated error message is:"ERROR: @_" followed by the name of the file and the
line number where the error occurred.The mesage is written to the STARTUP_LOG, if any.The function does not return but rather passes the message
to die or to confess, depending on whether the "-T"
option was specified.warning_messageThe warning_message is very similar to fatal_error but
avoids calling die or confess. It also prefixes the argument(s)
with "WARNING: " rather than "ERROR: ".It message is written to Standard Out and to the
STARTUP_LOG, if any.progress_message, progress_message2, progress_message3 and
progress_message_nocompressThese procedures conditionally write their argument(s) to
Standard Out and to the STARTUP_LOG (if any), depending on the
settings of VERBOSITY and and LOG_VERBOSITY respectively.progress_message only
write messages when the verbosity is 2. This function also
preserves leading whitespace while removing superflous
embedded whitespace from the messages.progress_message2
writes messages with the verbosity is >= 1.progress_message3
writes messages when the verbosity is >= 0.progress_message_nocompress is like
progress_message except
that it does not preserve leading whitespace nor does it
eliminate superfluous embedded whitespacve from the
messages.Script File HandlingThe functions involved in script file creation are:create_temp_script( $$ )This function creates and opens a temporary file in the
directory where the final script is to be placed; this function
is not called when the check command is being
processed. The first argument is the fully-qualified name of the
output script; the second (boolean) argument determines if the
compilation is for export. The function returns no meaningful
value but sets module-global variables as follows:$scriptHandle of the open script file.$dirThe directory in which the script was
created.$tempfileThe name of the temporary file.$fileThis fully-qualified name of the script file.finalize_script( $ )This function closes the temporary file and renames it to
the
shorewall-docs-xml-5.0.4/Audit.xml 0000644 0000000 0000000 00000025002 12647470621 015542 0 ustar root root
AUDIT Target SupportTomEastep2011Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.BackgroundIn early 2011, Thomas Graf submitted a set of patches to the
Netfilter development list that implemented an AUDIT rule target. This is
from the initial submittal:
This patch adds a new netfilter target which creates audit records
for packets traversing a certain chain. It can be used to record packets
which are rejected administraively as follows:-N AUDIT_DROP-A AUDIT_DROP -j AUDIT --type DROP-A AUDIT_DROP -j DROPA rule which would typically drop or reject a packet would then
invoke the new chain to record packets before dropping them.-j AUDIT_DROPThe module is protocol independant and works for iptables,
ip6tables and ebtables.netfilter hookpacket lengthincoming/outgoing interfaceMAC src/dst/proto for ethernet packetssrc/dst/protocol address for IPv4/IPv6src/dst port for TCP/UDP/UDPLITEicmp type/code
The audited packets are sent to a daemon (auditd) that write the
audit information to a log file.In a related post by Eric Paris, the following additional
information was posted:
AUDIT exists because a very large number of gov't customers (Not
just USA) have special requirements about how 'relevant' information is
gathered and stored. They require centralization and standardization and
require pretty formal documentation describing it's operation. The gov't
certification authority has recently added a requirement that they be
able to log 'illegal attempted network connections' via the approved
audit facility. Thus, this patch.
The AUDIT target was included in Linux kernel 2.6.39.Shorewall SupportShorewall support for the AUDIT target was added in 4.4.20.The support involves the following:A new "AUDIT Target" capability is added and is required for
auditing support. To use AUDIT support with a capabilities file, that
file must be generated using this or a later release.Use 'shorewall show capabilities' after installing this release
to see if your kernel/iptables support the AUDIT target.In /etc/shorewall/policy's POLICY column, the policy (and
default action, if any) may be followed by ':audit' to cause
application of the policy to be audited. Only ACCEPT, DROP and REJECT
policies may be audited.Example:#SOURCE DEST POLICY LOG
# LEVEL
net fw DROP:auditIt is allowed to also specify a log level on audited policies
resulting in both auditing and logging.Three new builtin targets that may be used in the rules file, in
macros and in other actions.A_ACCEPT - Audits and accepts the connection requestA_DROP - Audits and drops the connection requestA_REJECT - Audits and rejectsA log level may be supplied with these actions to provide both
auditing and logging.Example:#ACTION SOURCE DEST PROTO
A_ACCEPT:info loc net ...The BLACKLIST_DISPOSITION, MACLIST_DISPOSITION,
SMURF_DISPOSITION and TCP_FLAGS_DISPOSITION options may be set as
follows:BLACKLIST_DISPOSITIONA_DROP or A_REJECTMACLIST_DISPOSITIONA_DROP, A_REJECT unless MACLIST_TABLE=mangleSMURF_DISPOSITIONThis option was added in Shorewall 4.4.20A_DROPTCP_FLAGS_DISPOSITIONA_DROP or A_REJECTAn 'audit' option has been added to the /etc/shorewall/blacklist
file which causes the packets matching the entryto be audited. 'audit'
may not be specified together with 'accept'.The builtin actions (dropBroadcast, rejNonSyn, etc.) now support
an 'audit' parameter which causes all ACCEPT, DROP and REJECTs
performed by the action to be audited.There are audited versions of the standard Default Actions (A_Drop and
A_Reject). These actions audit everything they do which is probably
more than you want; as a consequence, you probably will want to make
your own copies of these actions and modify them to only audit the
packets that you are interested in.In Shorewall 4.4.21, the standard Default Actions were parameterized,
accepting three parameters:Pass 'audit' if you want all ACCEPTs, DROPs and REJECTs
audited. Pass '-' otherwise.The action to be applied to Auth requests; the default
depends on the first parameter:FIRST
PARAMETERDEFAULT-REJECTauditA_REJECTThe action to be applied to SMB traffic. The default depends
on the first parameter:ACTIONFIRST
PARAMETERDEFAULTReject-REJECTDrop-DROPRejectauditA_REJECTDropauditA_DROP The parameters can be passed in the POLICY column of the policy
file. SOURCE DEST POLICY
net all DROP:Drop(audit):audit #Same as DROP:A_DROP:audit
SOURCE DEST POLICY
net all DROP:Drop(-,DROP) #DROP rather than REJECT Auth
The parameters can also be specified in shorewall.conf: DROP_DEFAULT=Drop(-,DROP) #DROP Auth rather than REJECT
shorewall-docs-xml-5.0.4/blacklisting_support.xml 0000644 0000000 0000000 00000033721 12647470621 020745 0 ustar root root
Shorewall Blacklisting/Whitelisting SupportTomEastep2002-200620102011Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.This article applies to Shorewall 4.4 and
later. If you are running a version of Shorewall earlier than Shorewall
4.3.5 then please see the documentation for that
release.IntroductionShorewall supports two different types of blackliisting; rule-based,
static and dynamic. The BLACKLIST option in /etc/shorewall/shorewall.conf
controls the degree of blacklist filtering.The BLACKLIST option lists the Netfilter connection-tracking states
that blacklist rules are to be applied to (states are NEW, ESTABLISHED,
RELATED, INVALID, NOTRACK). The BLACKLIST option supersedes the
BLACKLISTNEWONLY option:BLACKLISTNEWONLY=No -- All incoming packets are checked against
the blacklist. New blacklist entries can be used to terminate existing
connections.BLACKLISTNEWONLY=Yes -- The blacklists are only consulted for
new connection requests. Blacklists may not be used to terminate
existing connections.For automatic blacklisting based on exceeding defined threshholds,
see Events.Rule-based BlacklistingBeginning with Shorewall 4.4.25, the preferred method of
blacklisting and whitelisting is to use the blrules file (shorewall-blrules (5)).
There you have access to the DROP, ACCEPT, REJECT and WHITELIST actions,
standard and custom macros as well as standard and custom actions. See
shorewall-rules (5) for
details.Example:#ACTION SOURCE DEST PROTO DEST
# PORTS(S)
SECTION BLACKLIST
WHITELIST net:70.90.191.126 all
DROP net all udp 1023:1033,1434,5948,23773
DROP all net udp 1023:1033
DROP net all tcp 57,1433,1434,2401,2745,3127,3306,3410,4899,5554,5948,6101,8081,9898,23773
DROP net:221.192.199.48 all
DROP net:61.158.162.9 all
DROP net:81.21.54.100 all tcp 25
DROP net:84.108.168.139 all
DROP net:200.55.14.18 all
Beginning with Shorewall 4.4.26, the update
command supports a option that causes your legacy
blacklisting configuration to use the blrules file.If you prefer to keep your blacklisting rules in your rules file
(shorewall-rules
(5)), you can place them in the BLACKLIST section of that file rather
than in blrules.Legacy BlacklistingPrior to 4.4.25, two forms of blacklisting were supported; static
and dynamic. The dynamic variety is still appropriate for
on-the-fly blacklisting; the static form is
deprecated.By default, only the source address is
checked against the blacklists. Blacklists only stop
blacklisted hosts from connecting to you — they do not stop you or your
users from connecting to blacklisted hosts .UPDATEBeginning with Shorewall 4.4.12, you can also blacklist by
destination address. See shorewall-blacklist
(5) and shorewall (8)
for details.Dynamic Shorewall blacklisting is not
appropriate for blacklisting 1,000s of different addresses. Static
Blacklisting can handle large blacklists but only if you use
ipsets. Without ipsets, the blacklists will take forever to
load, and will have a very negative effect on firewall
performance.Static BlacklistingShorewall static blacklisting support has the following
configuration parameters:You specify whether you want packets from blacklisted hosts
dropped or rejected using the BLACKLIST_DISPOSITION setting in
shorewall.conf(5).You specify whether you want packets from blacklisted hosts
logged and at what syslog level using the BLACKLIST_LOGLEVEL setting
in shorewall.conf(5).You list the IP addresses/subnets that you wish to blacklist
in shorewall-blacklist
(5). You may also specify PROTOCOL and Port numbers/Service names in
the blacklist file.You specify the interfaces whose incoming packets you want
checked against the blacklist using the blacklist
option in shorewall-interfaces(5)
(shorewall-zones(5) in
Shorewall 4.4.12 and later).Prior to Shorewall 4.4.20, only source-address static blacklisting
was supported.Users with a large static black list may want to set the
DELAYBLACKLISTLOAD option in shorewall.conf (added in Shorewall version
2.2.0). When DELAYBLACKLISTLOAD=Yes, Shorewall will enable new
connections before loading the blacklist rules. While this may allow
connections from blacklisted hosts to slip by during construction of the
blacklist, it can substantially reduce the time that all new connections
are disabled during "shorewall [re]start".Beginning with Shorewall 2.4.0, you can use ipsets to define your static blacklist. Here's
an example:#ADDRESS/SUBNET PROTOCOL PORT
+Blacklistports[dst]
+Blacklistnets[src,dst]
+Blacklist[src,dst]
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVEIn this example, there is a portmap ipset
Blacklistports that blacklists all traffic with
destination ports included in the ipset. There are also
Blacklistnets (type nethash)
and Blacklist (type iphash)
ipsets that allow blacklisting networks and individual IP addresses.
Note that [src,dst] is specified so that individual entries in the sets
can be bound to other portmap ipsets to allow blacklisting
(source address, destination
port) combinations. For example:ipset -N SMTP portmap --from 1 --to 31
ipset -A SMTP 25
ipset -A Blacklist 206.124.146.177
ipset -B Blacklist 206.124.146.177 -b SMTPThis will blacklist SMTP traffic from host 206.124.146.177.Static WhitelistingBeginning with Shorewall 4.4.20, you can create
whitelist entries in the blacklist file.
Connections/packets matching a whitelist entry are not matched against
the entries in the blacklist file that follow. Whitelist entries are
created using the whitelist option
(OPTIONS column). See shorewall-blacklist
(5).Dynamic BlacklistingBeginning with Shorewall 4.4.7, dynamic blacklisting is enabled by
setting DYNAMIC_BLACKLIST=Yes in shorewall.conf.
Prior to that release, the feature is always enabled.Once enabled, dynamic blacklisting doesn't use any configuration
parameters but is rather controlled using /sbin/shorewall[-lite]
commands. Note that to and from may
only be specified when running Shorewall 4.4.12 or
later.drop [to|from] <ip address list> -
causes packets from the listed IP addresses to be silently dropped
by the firewall.reject [to|from]<ip address list> -
causes packets from the listed IP addresses to be rejected by the
firewall.allow [to|from] <ip address list> -
re-enables receipt of packets from hosts previously blacklisted by a
drop or reject
command.save - save the dynamic blacklisting configuration so that it
will be automatically restored the next time that the firewall is
restarted.Update: Beginning with
Shorewall 4.4.10, the dynamic blacklist is automatically retained
over stop/start sequences and over
restart.show dynamic - displays the dynamic blacklisting
configuration.logdrop [to|from] <ip address list>
- causes packets from the listed IP addresses to be dropped and
logged by the firewall. Logging will occur at the level specified by
the BLACKLIST_LOGLEVEL setting at the last [re]start (logging will
be at the 'info' level if no BLACKLIST_LOGLEVEL was given).logreject [to|from}<ip address
list> - causes packets from the listed IP addresses to
be rejected and logged by the firewall. Logging will occur at the
level specified by the BLACKLIST_LOGLEVEL setting at the last
[re]start (logging will be at the 'info' level if no
BLACKLIST_LOGLEVEL was given).Dynamic blacklisting is not dependent on the
blacklist option in
/etc/shorewall/interfaces.Ignore packets from a pair of systemsshorewall[-lite] drop 192.0.2.124 192.0.2.125Drops packets from hosts 192.0.2.124 and 192.0.2.125Re-enable packets from a systemshorewall[-lite] allow 192.0.2.125Re-enables traffic from 192.0.2.125.Displaying the Dynamic Blacklistshorewall show dynamicDisplays the 'dynamic' chain which contains rules for the
dynamic blacklist. The source column contains
the set of blacklisted addresses.
shorewall-docs-xml-5.0.4/XenMyWay-Routed.xml 0000644 0000000 0000000 00000134331 12647470621 017463 0 ustar root root
Strong Firewall in a Routed Xen Dom0TomEastep20062007Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.This article applies to Shorewall 4.0 and later. If you are running
a version of Shorewall earlier than Shorewall 4.0.0 then please see the
documentation for that release.Before XenPrior to adopting Xen, I had a home office crowded with 5 systems,
three monitors a scanner and a printer. The systems were:FirewallPublic Server in a DMZ (mail)Private Server (wookie)My personal Linux Desktop (ursa)My work system (docked laptop running Windows XP).The result was a very crowded and noisy room.After XenXen has allowed me to reduce the noise and clutter considerably. I
now have three systems with two monitors. I've also replaced the
individual printer and scanner with a Multifunction
FAX/Scanner/Printer.The systems now include:Combination Firewall/Public Server/Private Server/Wireless
Gateway using Xen (created by building out my Linux desktop system --
Now replaced by a Hewlett-Packard Pavilion a1510y).My work system.My Linux desktop (wookie, which is actually the old public
server box)The Linux systems run either OpenSuSE 10.3 or
Ubuntu "Gutsy Gibbon".Here is a high-level diagram of our network.As shown in this diagram, the Xen system has three physical network
interfaces. These are:eth0 -- connected to our
DSL "Modem".eth1 -- connected to the
switch in my office.eth2 -- connected to a
Wireless Access Point (WAP) that interfaces to our wireless
network.There are three Xen domains.Dom0 (DNS name gateway.shorewall.net) is used as our main
firewall and wireless gateway as well as a local file server. It hosts
Squid running as a
transparent HTTP proxy and a DHCP server that manages IP address
assignment for both the LAN and the Wireless network.A DomU (Domain name lists, DNS
name lists.shorewall.net) that is
used as a public Web/FTP/Mail/DNS server.A DomU (Domain name test, DNS
name test.shorewall.net) that I use
for Shorewall testing.Shorewall runs in Dom0.As the developer of Shorewall, I have enough experience to be very
comfortable with Linux networking and Shorewall/iptables. I arrived at
this configuration after a fair amount of trial and error
experimentation (see Xen and the art of
Consolidation). If you are a Linux networking novice, I
recommend that you do not attempt a configuration like this one for your
first Shorewall installation. You are very likely to frustrate both
yourself and the Shorewall support team. Rather I suggest that you start
with something simple like a standalone
installation in a DomU; once you are comfortable with that then
you will be ready to try something more substantial.As Paul Gear says: Shorewall might make iptables easy,
but it doesn't make understanding fundamental networking principles,
traffic shaping, or multi-ISP routing any easier.The same goes for Xen networking.Domain ConfigurationBelow are the relevant configuration files for the two domains. I
use a partition on my hard drives for the DomU storage device.There is not much documentation about how to configure Xen for
routed operation. I've tried to mark the relevant parts with bold font.The files from /etc/xen/auto shown below correspond to
my configuration under Xen 3.0. I'm now running Xen 3.1 which does
not use configuration files for the domains but rather keeps the
configuration in a database managed by xend. See below.
/boot/grub/menu.lst — here is the entry
that boots Xen in Dom0.
/etc/modprobe.conf.local (This may need to
go in /etc/modprobe.conf or
/etc/modprobe.d/options on your system)
options netloop nloopbacks=0 #Stop netloop from creating 8 useless vifs
/etc/xen/auto/01-lists — configuration file
for the lists domain. Placed in /etc/xen/auto/ so it is started
automatically by Xen's xendomains service.
disk = [ 'phy:/dev/sda9,hda,w', 'phy:/dev/hda,hdb,r' ]
memory = 512
vcpus = 1
builder = 'linux'
name = 'server'
vif = [ 'mac=00:16:3e:b1:d7:90, ip=206.124.146.177, vifname=eth3' ]
localtime = 0
on_poweroff = 'destroy'
on_reboot = 'restart'
on_crash = 'restart'
extra = ' TERM=xterm'
bootloader = '/usr/lib/xen/boot/domUloader.py'
bootentry = 'hda2:/boot/vmlinuz-xen,/boot/initrd-xen'Note that the vifname is set to 'eth3' for the virtual
interface to this DomU. This will cause the Dom0 interface to the
server to have a fixed name (eth3) which makes it a lot easier to
deal with in Shorewall and elsewhere.Specifying an IP address (ip=206.124.146.177) causes the
vif-route script to create a host route to that IP address on
eth3.
gateway:~ # ip route ls dev eth3
206.124.146.177 scope link src 206.124.146.176
gateway:~ #
Note that the source for the route is 206.124.146.176. That is
the primary IP address of Dom0's eth0. Xen configures eth3 to have that same IP
address.
/etc/xen/auto/02-test — configuration file
for the test domain.
…
# It is possible to use the network-bridge script in more complicated
# scenarios, such as having two outgoing interfaces, with two bridges, and
# two fake interfaces per guest domain. To do things like this, write
# yourself a wrapper script, and call network-bridge from it, as appropriate.
#
#(network-script network-bridge)
…
# If you are using only one bridge, the vif-bridge script will discover that,
# so there is no need to specify it explicitly.
#
#(vif-script vif-bridge)
## Use the following if network traffic is routed, as an alternative to the
# settings for bridged networking given above.
(network-script network-route)
(vif-script vif-route)As of this writing, the vif-route script does not set up
Proxy ARP correctly. So the domU can communicate with the dom0
but not with hosts beyond the dom0.If you configure Shorewall as described below, Shorewall
will correct the Proxy ARP configuration so that it will
work.
Instructions for editing entries in the Xen 3.1 xend
database may be found at http://www.novell.com/documentation/vmserver/config_options/index.html?page=/documentation/vmserver/config_options/data/b8uh3zr.html,
The following are excerpts from the XML representations of the two user
domains (produced by "xm list -l …").lists domain:
With the three Xen domains up and running, the system looks as
shown in the following diagram.The zones correspond to the Shorewall zones in the Dom0
configuration.Readers who are paying attention will notice that eth4 has the
same public IP address (206.124.146.176) as eth0 (and eth3), yet the
test system connected to that interface
has an RFC 1918 address (192.168.1.7). That configuration is established
by Xen which clones the primary IP address of eth0 on all of the routed
virtual interfaces that it creates. test is configured with its default route via
192.168.1.254 which is the IP address of the firewall's br0. That works
because of the way that the Linux network stack treats local IPv4
addresses; by default, it will respond to ARP "who-has" broadcasts for
any local address and not just for the addresses on the interface that
received the broadcast (but of course the MAC address returned in the
"here-is" response is that of the interface that received the
broadcast). So when test broadcasts
"who-has 192.168.1.254", the firewall responds with "here-is
192.168.1.254 00:16:3e:83:ad:28" (00:16:3e:83:ad:28 is the MAC of
virtual interface eth4).Under some circumstances, UDP and/or TCP communication from a
DomU won't work for no obvious reason. That happened with the
lists domain in my setup. Looking at
the IP traffic with tcpdump -nvvi eth1 in Dom0
showed that UDP packets from the lists DomU had incorrect checksums. That
problem was corrected by arranging for the following command to be
executed in the lists and test domains when the eth0 device was brought up:ethtool -K eth0 tx offUnder OpenSuSE 10.2, I placed the
following in
/etc/sysconfig/network/ifcfg-eth-id-00:16:3e:b1:d7:90
(the config file for eth0):ETHTOOL_OPTIONS='-K iface tx off'Under other distributions, the technique will vary. For example,
under Debian or Ubuntu,
you can just add a 'post-up' entry to
/etc/network/interfaces as shown here: iface eth0 inet static
address 206.124.146.177
netmask 255.255.255.0
post-up ethtool -K eth0 tx offUpdate. Under OpenSuSE 10.2, communication from a domU works
okay without running ethtool but traffic shaping
in dom0 doesn't work! So it's a good idea to run it just to
be safe.Dom0 Shorewall ConfigurationIn Dom0, I run a conventional three-interface firewall with Proxy
ARP DMZ -- it is very similar to the firewall described in the Shorewall Setup Guide with the
exception that I've added a fourth interface for our wireless network.
The firewall runs a routed OpenVPN
server to provide road warrior access for our three laptops and
a bridged OpenVPN server for the wireless network in our home. Here is
the firewall's view of the network:The three laptops can be directly attached to the LAN as shown
above or they can be attached wirelessly -- their IP addresses are the
same in either case; when they are directly attached, the IP address is
assigned by the DHCP server running in Dom0 and when they are attached
wirelessly, the IP address is assigned by OpenVPN.The Shorewall configuration files are shown below. All routing and
secondary IP addresses are handled in the OpenSuSE network
configuration.
/etc/shorewall/shorewall.confSTARTUP_ENABLED=Yes
VERBOSITY=0
SHOREWALL_COMPILER=perl
LOGFILE=/var/log/firewall
LOGFORMAT="Shorewall:%s:%s:"
LOGTAGONLY=No
LOGRATE=
LOGBURST=
LOGALLNEW=
BLACKLIST_LOGLEVEL=
MACLIST_LOG_LEVEL=$LOG
TCP_FLAGS_LOG_LEVEL=$LOG
SMURF_LOG_LEVEL=$LOG
LOG_MARTIANS=No
IPTABLES=
SHOREWALL_SHELL=/bin/ash
SUBSYSLOCK=/var/lock/subsys/shorewall
MODULESDIR=
CONFIG_PATH=/etc/shorewall:/usr/share/shorewall
RESTOREFILE=
IPSECFILE=zones
LOCKFILE=
DROP_DEFAULT="Drop"
REJECT_DEFAULT="Reject"
ACCEPT_DEFAULT="none"
QUEUE_DEFAULT="none"
IP_FORWARDING=Yes
ADD_IP_ALIASES=No
ADD_SNAT_ALIASES=No
RETAIN_ALIASES=No
TC_ENABLED=internal
TC_EXPERT=No
CLEAR_TC=Yes
MARK_IN_FORWARD_CHAIN=Yes
CLAMPMSS=Yes
ROUTE_FILTER=No
DETECT_DNAT_IPADDRS=Yes
MUTEX_TIMEOUT=60
ADMINISABSENTMINDED=Yes
BLACKLISTNEWONLY=Yes
DELAYBLACKLISTLOAD=No
MODULE_SUFFIX=
DISABLE_IPV6=Yes
BRIDGING=No
DYNAMIC_ZONES=No
PKTTYPE=No
MACLIST_TABLE=mangle
MACLIST_TTL=60
SAVE_IPSETS=No
MAPOLDACTIONS=No
FASTACCEPT=Yes
IMPLICIT_CONTINUE=Yes
HIGH_ROUTE_MARKS=Yes
USE_ACTIONS=Yes
OPTIMIZE=1
EXPORTPARAMS=No
EXPAND_POLICIES=Yes
KEEP_RT_TABLES=No
DELETE_THEN_ADD=No
BLACKLIST_DISPOSITION=DROP
MACLIST_DISPOSITION=DROP
TCP_FLAGS_DISPOSITION=DROP/etc/shorewall/zones:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall #The firewall itself.
net ipv4 #Internet
loc ipv4 #Local wired Zone
dmz ipv4 #DMZ
vpn ipv4 #Open VPN clients
wifi ipv4 #Local Wireless Zone
#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE
/etc/shorewall/policy:#SOURCE DEST POLICY LOG LIMIT:BURST
# LEVEL
$FW $FW ACCEPT
$FW net ACCEPT
loc net ACCEPT
$FW vpn ACCEPT
vpn net ACCEPT
vpn loc ACCEPT
loc vpn ACCEPT
$FW loc ACCEPT
loc $FW ACCEPT
wifi all REJECT $LOG
net $FW DROP $LOG 1/sec:2
net loc DROP $LOG 2/sec:4
net dmz DROP $LOG 8/sec:30
net vpn DROP $LOG
all all REJECT $LOG
#LAST LINE -- DO NOT REMOVENote that the firewall<->local network interface
is wide open so from a security point of view, the firewall system is
part of the local zone./etc/shorewall/params (edited):MIRRORS=<comma-separated list of Shorewall mirrors>
NTPSERVERS=<comma-separated list of NTP servers I sync with>
POPSERVERS=<comma-separated list of server IP addresses>
LOG=info
INT_IF=br0
DMZ_IF=eth3
EXT_IF=eth0
WIFI_IF=eth2
TEST_IF=eth4
OMAK=<IP address at our second home>
#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE/etc/shorewall/init:echo 1 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_be_liberal/etc/shorewall/interfaces (don't specify
the BROADCAST addresses if you are using Shorewall-perl):#ZONE INTERFACE BROADCAST OPTIONS
net ${EXT_IF} detect dhcp,logmartians=1,blacklist
dmz $DMZ_IF detect logmartians=1
loc $INT_IF detect dhcp,logmartians=1,routeback,bridge
loc $TEST_IF detect optional
loc $TEST1_IF detect optional
wifi $WIFI_IF detect dhcp,maclist,mss=1400
vpn tun+ -
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/nat:#EXTERNAL INTERFACE INTERNAL ALL LOCAL
# INTERFACES
COMMENT One-to-one NAT
206.124.146.178 $EXT_IF:0 192.168.1.3 No No
206.124.146.180 $EXT_IF:2 192.168.1.6 No No
#LAST LINE -- ADD YOUR ENTRIES ABOVE THIS LINE -- DO NOT REMOVE/etc/shorewall/masq (Note the cute trick here and in
the following proxyarp file that allows me to
access the DSL "Modem" using its default IP address
(192.168.1.1)). The leading "+" is required to place the
rule before the SNAT rules generated by entries in
/etc/shorewall/nat above.#INTERFACE SOURCE ADDRESS PROTO PORT(S) IPSEC
COMMENT Handle DSL 'Modem'
+$EXT_IF:192.168.1.1 0.0.0.0/0 192.168.1.254
COMMENT Masquerade VPN clients and Wifi
$EXT_IF 192.168.2.0/24
$EXT_IF 192.168.3.0/24
$EXT_IF:192.168.98.1 192.168.99.1 192.168.1.99
$EXT_IF:192.168.99.1 192.168.98.1 192.168.1.98
COMMENT Masquerade Local Network
$EXT_IF 192.168.1.0/24 206.124.146.179
#LAST LINE -- ADD YOUR ENTRIES ABOVE THIS LINE -- DO NOT REMOVE/etc/shorewall/proxyarp:#ADDRESS INTERFACE EXTERNAL HAVEROUTE PERSISTENT
192.168.1.1 $EXT_IF $INT_IF yes
206.124.146.177 $DMZ_IF $EXT_IF yes
192.168.1.7 $TEST_IF $INT_IF yes
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY
# ZONE
openvpnserver:udp net 0.0.0.0/0 #Routed server for RoadWarrior access
openvpnserver:udp wifi 192.168.3.0/24 #Home wireless network server
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/blacklist:#ADDRESS/SUBNET PROTOCOL PORT
- udp 1024:1033,1434
- tcp 57,1433,1434,2401,2745,3127,3306,3410,4899,5554,6101,8081,9898
#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE/etc/shorewall/actions:#ACTION
Mirrors # Accept traffic from Shorewall Mirrors
#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE/etc/shorewall/action.Mirrors:#TARGET SOURCE DEST PROTO DEST SOURCE ORIGINAL RATE
# PORT PORT(S) DEST LIMIT
ACCEPT $MIRRORS
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/rules:SECTION NEW
###############################################################################################################################################################################
#ACTION SOURCE DEST PROTO DEST SOURCE ORIGINAL RATE USER/
# PORT PORT(S) DEST LIMIT GROUP
###############################################################################################################################################################################
REJECT:$LOG loc net tcp 25
REJECT:$LOG loc net udp 1025:1031
#
# Stop NETBIOS crap
#
REJECT loc net tcp 137,445
REJECT loc net udp 137:139
#
# Stop my idiotic work laptop from sending to the net with an HP source/dest IP address
#
DROP loc:!192.168.0.0/22 net
###############################################################################################################################################################################
# Local Network to Firewall
#
REDIRECT- loc 3128 tcp 80 - !192.168.1.1,192.168.0.7,206.124.146.177,155.98.64.80
###############################################################################################################################################################################
# Road Warriors to Firewall
#
ACCEPT vpn fw tcp ssh,time,631,8080
ACCEPT vpn fw udp 161,ntp,631
Ping(ACCEPT) vpn fw
###############################################################################################################################################################################
# Road Warriors to DMZ
#
ACCEPT vpn dmz udp domain
ACCEPT vpn dmz tcp www,smtp,smtps,domain,ssh,imap,https,imaps,ftp,10023,pop3 -
Ping(ACCEPT) vpn dmz
###############################################################################################################################################################################
# Local network to DMZ
#
ACCEPT loc dmz udp domain
ACCEPT loc dmz tcp ssh,smtps,www,ftp,imaps,domain,https -
ACCEPT loc dmz tcp smtp
Trcrt(ACCEPT) loc dmz
###############################################################################################################################################################################
# Internet to ALL -- drop NewNotSyn packets
#
dropNotSyn net fw tcp
#dropNotSyn net loc tcp
dropNotSyn net dmz tcp
###############################################################################################################################################################################
# Internet to DMZ
#
ACCEPT net dmz udp domain
LOG:$LOG net:64.126.128.0/18 dmz tcp smtp
ACCEPT net dmz tcp smtps,www,ftp,imaps,domain,https -
ACCEPT net dmz tcp smtp - 206.124.146.177,206.124.146.178
ACCEPT net dmz udp 33434:33454
Mirrors net dmz tcp rsync
Limit:$LOG:SSHA,3,60\
net dmz tcp 22
Trcrt(ACCEPT) net dmz
##############################################################################################################################################################################
#
# Net to Local
#
# When I'm "on the road", the following two rules allow me VPN access back home using PPTP.
#
DNAT net loc:192.168.1.4 tcp 1729
DNAT net loc:192.168.1.4 gre
#
# Roadwarrior access to Ursa
#
ACCEPT net:$OMAK loc tcp 22
Limit:$LOG:SSHA,3,60\
net loc tcp 22
#
# ICQ
#
ACCEPT net loc:192.168.1.3 tcp 113,4000:4100
#
# Bittorrent
#
ACCEPT net loc:192.168.1.3 tcp 6881:6889,6969
ACCEPT net loc:192.168.1.3 udp 6881:6889,6969
#
# Real Audio
#
ACCEPT net loc:192.168.1.3 udp 6970:7170
#
# Overnet
#
#ACCEPT net loc:192.168.1.3 tcp 4662
#ACCEPT net loc:192.168.1.3 udp 12112
#
# OpenVPN
#
ACCEPT net loc:192.168.1.3 udp 1194
ACCEPT net loc:192.168.1.6 udp 1194
# Skype
#
ACCEPT net loc:192.168.1.6 tcp 1194
#
# Traceroute
#
Trcrt(ACCEPT) net loc:192.168.1.3
#
# Silently Handle common probes
#
REJECT net loc tcp www,ftp,https
DROP net loc icmp 8
###############################################################################################################################################################################
# DMZ to Internet
#
ACCEPT dmz net udp domain,ntp
ACCEPT dmz net tcp echo,ftp,ssh,smtp,whois,domain,www,81,https,cvspserver,2702,2703,8080
ACCEPT dmz net:$POPSERVERS tcp pop3
Ping(ACCEPT) dmz net
#
# Some FTP clients seem prone to sending the PORT command split over two packets. This prevents the FTP connection tracking
# code from processing the command and setting up the proper expectation. The following rule allows active FTP to work in these cases
# but logs the connection so I can keep an eye on this potential security hole.
#
ACCEPT:$LOG dmz net tcp 1024: 20
###############################################################################################################################################################################
# Local to DMZ
#
ACCEPT loc dmz udp domain,xdmcp
ACCEPT loc dmz tcp www,smtp,smtps,domain,ssh,imap,rsync,https,imaps,ftp,10023,pop3,3128
Trcrt(ACCEPT) loc dmz
###############################################################################################################################################################################
# DMZ to Local
#
ACCEPT dmz loc:192.168.1.5 udp 123
ACCEPT dmz loc:192.168.1.5 tcp 21
Ping(ACCEPT) dmz loc
###############################################################################################################################################################################
# DMZ to Firewall -- ntp & snmp, Silently reject Auth
#
#ACCEPT net loc:192.168.1.3 udp 12112
#
# OpenVPN
#
ACCEPT net loc:192.168.1.3 udp 1194
ACCEPT net loc:192.168.1.6 udp 1194
# Skype
#
ACCEPT net loc:192.168.1.6 tcp 1194
#
# Traceroute
#
Trcrt(ACCEPT) net loc:192.168.1.3
#
# Silently Handle common probes
#
REJECT net loc tcp www,ftp,https
DROP net loc icmp 8
###############################################################################################################################################################################
# DMZ to Internet
#
ACCEPT dmz net udp domain,ntp
ACCEPT dmz net tcp echo,ftp,ssh,smtp,whois,domain,www,81,https,cvspserver,2702,2703,8080
ACCEPT dmz net:$POPSERVERS tcp pop3
Ping(ACCEPT) dmz net
#
# Some FTP clients seem prone to sending the PORT command split over two packets. This prevents the FTP connection tracking
# code from processing the command and setting up the proper expectation. The following rule allows active FTP to work in these cases
# but logs the connection so I can keep an eye on this potential security hole.
#
ACCEPT:$LOG dmz net tcp 1024: 20
###############################################################################################################################################################################
# Local to DMZ
#
ACCEPT loc dmz udp domain,xdmcp
ACCEPT loc dmz tcp www,smtp,smtps,domain,ssh,imap,rsync,https,imaps,ftp,10023,pop3,3128
Trcrt(ACCEPT) loc dmz
###############################################################################################################################################################################
# DMZ to Local
#
ACCEPT dmz loc:192.168.1.5 udp 123
ACCEPT dmz loc:192.168.1.5 tcp 21
Ping(ACCEPT) dmz loc
###############################################################################################################################################################################
# DMZ to Firewall -- ntp & snmp, Silently reject Auth
#
ACCEPT loc dmz udp domain,xdmcp
ACCEPT loc dmz tcp www,smtp,smtps,domain,ssh,imap,rsync,https,imaps,ftp,10023,pop3,3128
Trcrt(ACCEPT) loc dmz
###############################################################################################################################################################################
# DMZ to Local
#
ACCEPT dmz loc:192.168.1.5 udp 123
ACCEPT dmz loc:192.168.1.5 tcp 21
Ping(ACCEPT) dmz loc
###############################################################################################################################################################################
# DMZ to Firewall -- ntp & snmp, Silently reject Auth
#
ACCEPT dmz fw tcp 161,ssh
ACCEPT dmz fw udp 161,ntp
REJECT dmz fw tcp auth
Ping(ACCEPT) dmz fw
###############################################################################################################################################################################
# Internet to Firewall
#
REJECT net fw tcp www,ftp,https
DROP net fw icmp 8
ACCEPT net fw udp 33434:33454
ACCEPT net:$OMAK fw udp ntp
ACCEPT net fw tcp auth
ACCEPT net:$OMAK fw tcp 22
Limit:$LOG:SSHA,3,60\
net fw tcp 22
Trcrt(ACCEPT) net fw
#
# Bittorrent
#
ACCEPT net fw tcp 6881:6889,6969
ACCEPT net fw udp 6881:6889,6969
###############################################################################################################################################################################
# Firewall to DMZ
#
ACCEPT fw dmz tcp domain,www,ftp,ssh,smtp,https,993,465
ACCEPT fw dmz udp domain
REJECT fw dmz udp 137:139
Ping(ACCEPT) fw dmz
##############################################################################################################################################################################
# Avoid logging Freenode.net probes
#
DROP net:82.96.96.3 all
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/tcdevices#INTERFACE IN-BANDWITH OUT-BANDWIDTH
$EXT_IF 1300kbit 384kbit
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE
/etc/shorewall/tcclasses#INTERFACE MARK RATE CEIL PRIORITY OPTIONS
$EXT_IF 10 5*full/10 full 1 tcp-ack,tos-minimize-delay
$EXT_IF 20 3*full/10 9*full/10 2 default
$EXT_IF 30 2*full/10 6*full/10 3
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE/etc/shorewall/tcrules#MARK SOURCE DEST PROTO PORT(S) CLIENT USER TEST
# PORT(S)
1:110 192.168.0.0/22 $EXT_IF #Our internal nets get priority
#over the server
1:130 206.124.146.177 $EXT_IF tcp - 873 #Throttle rsync traffic to the
#Shorewall Mirrors.
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVE
The tap0 device used by
the bridged OpenVPN server is created and bridged to eth1 using a SUSE-specific SysV init
script:
#!/bin/sh
#
# The Shoreline Firewall (Shorewall) Packet Filtering Firewall - V3.0
#
# This program is under GPL [http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt]
#
# (c) 1999,2000,2001,2002,2003,2004,2005 - Tom Eastep (teastep@shorewall.net)
#
# On most distributions, this file should be called /etc/init.d/shorewall.
#
# Complete documentation is available at http://shorewall.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of Version 2 of the GNU General Public License
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# If an error occurs while starting or restarting the firewall, the
# firewall is automatically stopped.
#
# Commands are:
#
# bridge start Starts the bridge
# bridge restart Restarts the bridge
# bridge reload Restarts the bridge
# bridge stop Stops the bridge
# bridge status Displays bridge status
#
# chkconfig: 2345 4 99
# description: Packet filtering firewall
### BEGIN INIT INFO
# Provides: bridge
# Required-Start: boot.udev
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 1 6
# Description: starts and stops the bridge
### END INIT INFO
################################################################################
# Interfaces to be bridged -- may be listed by device name or by MAC
#
INTERFACES="eth1"
#
# Tap Devices
#
TAPS="tap0"
################################################################################
# Give Usage Information #
################################################################################
usage() {
echo "Usage: $0 start|stop|reload|restart|status"
exit 1
}
#################################################################################
# Find the interface with the passed MAC address
#################################################################################
find_interface_by_mac() {
local mac
mac=$1
local first
local second
local rest
local dev
/sbin/ip link ls | while read first second rest; do
case $first in
*:)
dev=$second
;;
*)
if [ "$second" = $mac ]; then
echo ${dev%:}
return
fi
esac
done
}
################################################################################
# Convert MAC addresses to interface names
################################################################################
get_interfaces() {
local interfaces
interfaces=
local interface
for interface in $INTERFACES; do
case $interface in
*:*:*)
interface=$(find_interface_by_mac $interface)
[ -n "$interface" ] || echo "WARNING: Can't find an interface with MAC address $mac"
;;
esac
interfaces="$interfaces $interface"
done
INTERFACES="$interfaces"
}
################################################################################
# Start the Bridge
################################################################################
do_start()
{
local interface
get_interfaces
for interface in $TAPS; do
/usr/sbin/openvpn --mktun --dev $interface
done
/sbin/brctl addbr br0
for interface in $INTERFACES $TAPS; do
/sbin/ip link set $interface up
/sbin/brctl addif br0 $interface
done
}
################################################################################
# Stop the Bridge
################################################################################
do_stop()
{
local interface
get_interfaces
for interface in $INTERFACES $TAPS; do
/sbin/brctl delif br0 $interface
/sbin/ip link set $interface down
done
/sbin/ip link set br0 down
/sbin/brctl delbr br0
for interface in $TAPS; do
/usr/sbin/openvpn --rmtun --dev $interface
done
}
################################################################################
# E X E C U T I O N B E G I N S H E R E #
################################################################################
command="$1"
case "$command" in
start)
do_start
;;
stop)
do_stop
;;
restart|reload)
do_stop
do_start
;;
status)
/sbin/brctl show
;;
*)
usage
;;
esac
shorewall-docs-xml-5.0.4/three-interface_ru.xml 0000644 0000000 0000000 00000210423 12647470621 020252 0 ustar root root
Файервол с тремя интерфейсамиTomEastep2002-2005Thomas M. EastepPermission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Эта статья применима для Shorewall версии 3.0
и выше. Если Вы работаете с более ранней версией Shorewall чем Shorewall
3.0.0, тогда смотрите документацию для этого выпуска.ВведениеУстановка Linux системы как файервола для небольшой сети довольно
простая задача, если Вы понимаете основы и следуете документации.Это руководство не пытается ознакомить Вас со всеми особенностями
Shorewall. Оно больше сфокусировано на том, что требуется для настройки
Shorewall в наиболее типичных конфигурациях:Linux система, используемая как файервол/маршрутизатор для
небольшой локальной сети.Один внешний (публичный) IP-адрес.Если Вы имеете более одного публичного
IP-адреса, это руководство не то, что Вам нужно.
Смотрите вместо этого Руководство по установке
Shorewall.DeMilitarized Zone (DMZ)
подсоединена к отдельному интерфейсу Ethernet. Цель
DMZ - изолировать те Ваши локальные серверы,
которые открыты для Интернет так, что если один из этих серверов
скомпрометирован, остается еще файервол между взломанным сервером и
Вашими локальными системами.Интернет-соединение посредством кабельного модема,
DSL, ISDN, Frame Relay,
коммутирумой линии ...Вот схема типичной установки:schematic of a typical installationСистемные требованияShorewall требует, чтобы у Вас был установлен пакет
iproute/iproute2 (на
RedHat, этот пакет называется
iproute). Вы можете определить установлен ли этот пакет по
наличию программы ip на Вашем файерволе. Как root, Вы
можете использовать команду which для проверки
наличия этой программы:[root@gateway root]# which ip
/sbin/ip
[root@gateway root]#Перед тем как начатьЯ рекомендую Вам прочитать все руководство для первоначального
ознакомления, а лишь затем пройти его снова, внося изменения в Вашу
конфигурацию.Если Вы редактируете Ваши файлы конфигурации на
Windows системе, Вы должны сохранить их как
Unix файлы в том случае, если Ваш редактор
поддерживает эту возможность, иначе Вы должны пропустить их через
программу dos2unix перед тем как использовать их.
Аналогично, если Вы копируете конфигурационный файл с Вашего жесткого
диска с Windows на дискету, Вы должны воспользоваться
dos2unix для копии перед ее использованием с
Shorewall. Windows
версия dos2unixLinux
версия dos2unixConventionsМеста, в которых рекомендуется вносить изменения, отмечены как
.Замечания по настройке уникальные для проекта LEAF/Bering,
отмечены как .PPTP/ADSLЕсли У Вас есть ADSL модем и Вы используете
PPTP для взаимодействия с сервером на этом модеме, Вы
должны сделать изменения рекоммендуемые здесьв дополнение к тем, что описаны в последующих
шагах. ADSL с
PPTP наиболее распространен в Европе, особенно в
Австрии.Концепции ShorewallКонфигурационные файлы Shorewall находятся в директории /etc/shorewall -- в случае простой установки
Вам необходимо иметь дело только с немногими из них, как описано в этом
руководстве.Замечание для пользователей
DebianЕсли Вы при установке пользовались .deb, Вы обнаружите, что
директория /etc/shorewall
пуста. Это сделано специально. Поставляемые шаблоны файлов
конфигурации Вы найдете на вашей системе в директории /usr/share/doc/shorewall-common/default-config.
Просто скопируйте нужные Вам файлы из этой директории в /etc/shorewall и отредактируйте
копии.Заметьте, что Вы должны скопировать /usr/share/doc/shorewall-common/default-config/shorewall.conf
и /usr/share/doc/shorewall-common/default-config/modules
в /etc/shorewall даже если Вы
не будете изменять эти файлы.После того как Вы установили
Shorewall, Вы можете найти примеры файлов настроек в следующих
местах:Если Вы при установке использовали RPM,
примеры будут находится в поддиректории Samples/three-interface директории с
документацией Shorewall. Если Вы не знаете где расположена директория
с документацией Shorewall, Вы можете найти примеры используя
команду:~# rpm -ql shorewall | fgrep three-interfaces
/usr/share/doc/packages/shorewall/Samples/three-interfaces
/usr/share/doc/packages/shorewall/Samples/three-interfaces/interfaces
/usr/share/doc/packages/shorewall/Samples/three-interfaces/masq
/usr/share/doc/packages/shorewall/Samples/three-interfaces/policy
/usr/share/doc/packages/shorewall/Samples/three-interfaces/routestopped
/usr/share/doc/packages/shorewall/Samples/three-interfaces/rules
/usr/share/doc/packages/shorewall/Samples/three-interfaces/zones
~#Если Вы установили Shorewall из tarball'а, примеры находятся в
директории Samples/three-interface внутри
tarball'а.Если же Вы пользовались пакетом .deb, примеры находятся в
директории/usr/share/doc/shorewall-common/examples/three-interface.По мере того как мы будем знакомится с каждым файлом, я надеюсь, что
Вы просмотрите реальный файл на вашей системе -- каждый файл содержит
детальное описание конфигурационных инструкций и значений по
умолчанию.Shorewall видит сеть, в которой он работает, как состоящую из набора
зон(zones). В примере конфигурации с тремя
интерфейсами, определены следующие зоны:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall
net ipv4
loc ipv4
dmz ipv4Зоны Shorewall описаны в файле /etc/shorewall/zones.Заметьте, что Shorewall рассматривает систему файервола как свою
собственную зону. При обработке файла
/etc/shorewall/zones имя зоны файервола
(fw в примере выше) храниться в переменной shell
$FW, которая может использоваться во всей
конфигурации Shorewall для ссылки на сам файервол.Правила о том какой трафик разрешен, а какой запрещен выражаются в
терминах зон.Вы отражаете Вашу политику по умолчанию для соединений из одной
зоны в другую в файле/etc/shorewall/policy.Вы определяете исключения из политики по умолчанию в файле
/etc/shorewall/rules.Для каждого запроса на соединение входящего в файервол, запрос
сначала проверяется на соответствие файлу
/etc/shorewall/rules. Если в этом файле не найдено
правил соответствующих запросу на соединение, то применяется первая
политика из файла /etc/shorewall/policy, которая
соответсвует запросу. Если есть общее действие (common
action) определенное для политики в файле
/etc/shorewall/actions или
/usr/share/shorewall/actions.std, тогда это действие
выполняется перед тем как .Файл /etc/shorewall/policy, входящий в пример с
тремя интерфейсами, имеет следующие политики:#SOURCE DEST POLICY LOG LEVEL LIMIT:BURST
loc net ACCEPT
net all DROP info
all all REJECT infoВ примере с тремя интерфейсами строка показанная внизу
закомментирована. Если Вы хотите, чтобы Ваш файервол имел полный доступ к
серверам Интернет, раскомментируйте эту строчку. #SOURCE DEST POLICY LOG LEVEL LIMIT:BURST
$FW net ACCEPTПолитики приведенные выше
будут:разрешать все запросы на соединение из Вашей локальной сети в
Интернет;отбрасывать (игнорировать) все запросы на соединение из Интернет
к Вашему файерволу или локальной сети;Опционально разрешать все запросы на соединение с файервола в
Интернет (если Вы раскомментировали дополнительную политику);отвергать все другие запросы на соединение (Shorewall требует
наличия такой политики, применимой для всех остальных
запросов).Важно отметить, что политики Shorewall (и правила) ссылаются на
соединения, а не на поток пакетов. С
политикой определенной в файле
/etc/shorewall/policy, показанной выше, разрешены соединения из
зоны loc в зону net, хотя на сам файервол
соединения из зоны loc не разрешены.В данный момент Вы можете отредактировать ваш файл
/etc/shorewall/policy и внести изменения, какие Вы
считаете необходимыми.Сетевые интерфейсыDMZФайервол имеет три сетевых интерфейса. Если соединение с Интернет
осуществляется при помощи кабельного или DSL
Модема, Внешним интерфейсом будет тот
ethernet-адаптер (например, eth0),
который подсоединен к этому Модему, если же Вы соединены посредством протокола
Point-to-Point Protocol over Ethernet
(PPPoE) или Point-to-Point Tunneling
Protocol (PPTP), то в этом случае
Внешним интерфейсом будет PPP
интерфейс (например, ppp0). Если
Вы подсоединены через обычный модем, Вашим Внешним
интерфейсом будет также ppp0. Если Вы соединяетесь используя
ISDN, Внешним интерфейсом будет
ippp0.Если Ваш внешний интерфейс - это ppp0 или ippp0, тогда Вы можете захотеть установить
переменную CLAMPMSS=yes в /etc/shorewall/shorewall.conf.Ваш Внешний интерфейс будет ethernet-адаптер
(eth0, eth1 or eth2) и будет соединен с
хабом или коммутатором. Другие
Ваши компьютеры будут соединены с тем же хабом/коммутатором (заметьте:
если Вы имеете только одну внутреннюю систему, Вы можете соединить
файервол с этим компьютером напрямую, используя кроссоверный (cross-over)
кабель.Ваш DMZ-bynthatqc будет ethernet-адаптер
(eth0, eth1 or eth2) и будет соединен с хабом или
комутатором. Другие Ваши компьютеры из DMZ будут
соединены с тем же хабом/коммутатором (заметьте: если Вы имеете только
одну систему в DMZ, Вы можете соединить файервол с этим
компьютером напрямую, используя кроссоверный (cross-over) кабель.НЕ подсоединяйте внутренний и внешний
интерфейсы к одному т тому же хабу или коммутатору исключая время
тестирование.Вы можете провести тестирование используя данную
конфигурацию, если Вы указали параметр ARP_FILTER в
/etc/shorewall/interfaces
для всех интерфейсов подсоединенных к общему хабу/коммутатору. Использовать такие установки на рабочем файерволе строго не
рекоммендуется.Пример конфигурации Shorewall с тремя интерфейсами подразумевает,
что внешний интерфейс - это eth0,
внутренний - eth1, а
DMZ - eth2.
Если Ваша конфигурация отличается, Вы должны будете изменить пример файл
/etc/shorewall/interfaces
соответственно. Пока Вы здесь, Вы возможно захотите просмотреть список
опций, специфичных для интерфейса. Вот несколько подсказок:Если Ваш внешний интерфейс ppp0 или ippp0, Вы можете заменить
detect(обнаружить) во втором столбце на
-(знак минус в ковычках).Если Ваш внешний интерфейс ppp0 или ippp0 или Вы имеете статический
IP-адрес, Вы можете удалить dhcp из
списка опций.IP-адресаПеред тем как идти дальше, мы должны сказать несколько слов о
Internet Protocol (IP)-адресах.
Обычно, Ваш Интернет-провайдер(Internet Service
Provider - ISP) назначает Вам один
IP-адрес. Этот адрес может быть назначен статически,
при помощи Протокола Динамического Конфигурирования Хостов
(Dynamic Host Configuration Protocol -
DHCP), в процессе установки Вами коммутированного
соединения (обычный модем), или при установке Вами другого типа
PPP (PPPoA, PPPoE
и т.д.) соединения. В последнем случае Ваш ISP может
назначит Вам статический IP-адрес; что означает, что Вы
настраиваете внешний интерфейс Вашего файервола на использование этого
адреса постоянно. Как бы ни был назначен Вам внешний адрес, он будет
разделяться между всеми Вашими системами при доступе в Интернет. Вы должны
будете назначить свои собственные адреса в Вашей внутренней сети
(внутренний и DMZ интерфейсы на Вашем файерволе, плюс
другие Ваши компьютеры). RFC-1918 резервирует несколько
Частных (Private) IP-адресов для
этих целей:10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255Перед запуском Shorewall, Вы должны взглянуть
на IP-адрес Вашего внешнего интерфейса и если он входит в один указанных
выше пазонов, Вы должны удалить опцию norfc1918 из строки
для внешнего интерфейса в файле /etc/shorewall/interfaces.Вы можете захотеть назначить Ваши локальные адреса из одной подсети
(subnet), а адреса DMZ из другой подсети . Для наших
целей мы можем рассматривать подсеть состоящую из диапазона адресов
x.y.z.0 - x.y.z.255. Такая подсеть будет иметь
Маску Подсети (Subnet Mask) -
255.255.255.0. Адрес
x.y.z.0 зарезервирован как Адрес Подсети
(Subnet Address), а x.y.z.255 как
Широковещательный Адрес Подсети (Subnet Broadcast
Address). В Shorewall подсеть описывается с использованием
нотации Бесклассовой
Междоменной Маршрутизации (Classless InterDomain Routing -
CIDR notation) с адресом посети оканчивающимся
/24. 24 указывает число непрерывных
ведущих бит установленных в 1 слева в маске подсети.
Example sub-networkДиапазон:10.10.10.0 -
10.10.10.255Адрес подсети:10.10.10.0Широковещательный адрес:10.10.10.255Нотация CIDR::10.10.10.0/24
Удобно назначать внутреннему интерфейсу либо первый используемый
адрес подсети (10.10.10.1 в
примере выше), либо последний используемый адрес (10.10.10.254).Одна из целей разбиения на подсети - это позволить всем компьютерам
в подсети понимать с какими другими компьютерами можно взаимодействовать
напрямую. При взаимодействии с системами находящимися вне подсети, системы
посылают пакеты через шлюз (маршрутизатор) (gateway
(router)).Ваши локальные компьютеры (локальные компьютеры 1 & 2 на
диаграмме выше) должны быть сконфигурированы так, чтобы
IP-адресом их маршрутизатора по умолчанию был
IP-адрес внутреннего интерфейса файервола и Ваши
компьютеры DMZ (DMZ компьютеры 1
& 2) должны иметь IP-адрес маршрутизатора по
умолчанию установленным в IP-адрес
DMZ- интерфейса файервола.Короткая предшествующая дискуссия лишь поверхностно затронула
вопросы связанные с подсетями и маршрутизацией. Если Вы заинтересованы
узнать больше об IP-адресации и маршрутизации, я очень
рекомендую Основы IP: Что нужно знать каждому об адресации и
маршрутизации (IP Fundamentals: What Everyone Needs to Know
about Addressing & Routing), Thomas A. Maufer, Prentice-Hall,
1999, ISBN 0-13-975483-0 (link).Оставшаяся часть руководства расчитана на то, что Вы имеете сеть,
сконфигурированную так, как показано здесь:DMZ
Маршрутизатором по умолчанию для DMZ должен быть10.10.11.254, а для локальных
компьютеров 1 и 2 должен быть 10.10.10.254.Ваш ISP может назначить Вашему внешнему
интерфейсу адрес из RFC-1918. Если этот адрес
из подсети 10.10.10.0/24, тогда Вы должны будете выделить ДРУГУЮ подсеть
RFC-1918 для вашей локальной подсети и если это
10.10.11.0/24, то Вы
должны будете выделить ДРУГУЮ подсеть RFC-1918
для Вашей DMZ.
IP-маскарадинг (SNAT)Адреса зарезервированные RFC-1918 иногда называют
немаршрутизируемыми потому, что магистральные маршрутизаторы Интернет не
переправляют пакеты, которые имеют адрес назначения из
RFC-1918. Когда одна из Ваших локальных систем
(допустим computer 1) посылает запрос на соединение хосту в Интернете,
файервол должен выполнить Трансляцию Сетевого Адреса (Network
Address Translation - NAT). Файервол
перезаписывает адрес источника в пакете адресом внешнего интерфейса
файервола; другими словами, файервол делает так, чтобы это выглядело как
файервол сам инициируетсоединение. Это необходимо так как хост назначения
должен быть способен направить пакеты назад файерволу через маршрутизаторы
(вспомним, что пакеты с адресом назначения зарезервированным
RFC-1918 не могут быть маршрутизированы через Интернет
и следовательно удаленный хост не сможет адресовать ответ на computer 1).
Когда файервол принимает ответный пакет, он перезаписывает адрес
назначения обратно в 10.10.10.1
и переправляет пакет на computer 1.На Linux системах, описанный выше процесс называют
IP-маскарадингом (IP
Masquerading), но Вы будете также встречать термин
Преобразование Сетевого Адреса Источника (Source Network Address
Translation - SNAT). Shorewall следует
соглашению используемому Netfilter: Masquerade описывает случай, когда Вы
позволяете своему файерволу автоматически определять адрес внешнего
интерфейса.SNAT используют в случае, когда Вы
определенно указываете адрес источника, который Вы хотите
использовать для покидающих Вашу локальную сеть пакетов. В Shorewall оба режима Маскарадинг
(Masquerading) и SNAT конфигурируются
записями в файле /etc/shorewall/masq. Вы
будете обычно использовать Маскарадинг, если Ваш внешний
IP-адрес - динамический и SNAT, если
внешний IP-адрес - статический.Если Ваш внешний интерфейс файервола - eth0, Ваш локальный интерфейс - eth1 и Ваш DMZ-нитерфейс
- eth2, Вам не нужно изменять файл
из примера. В противном случае, отредактируйте /etc/shorewall/masq так,
чтобы он соответствовал Вашей конфигурации.А если, несмотря и вопреки всем советам, Вы используете это
руководство и хотите применить NAT один-к-одному или
прокси-ARP для Вашей DMZ, удалите
запись для eth2 из файла
/etc/shorewall/masq.Если Ваш внешний IP-адрес - статический, Вы
можете ввести его в третьем столбце записи файла /etc/shorewall/masq если
Вам нравиться, хотя Ваш файервол будет прекрасно работать, даже если Вы
оставите этот столбец пустым. Вводя Ваш статический
IP-адрес в третьем столбце, Вы делаете обработку
исходящих пакетов немного более эффективной.Если Вы используете пакет Debian, проверьте
пожалуйста Ваш файл shorewall.conf, чтобы убедиться,
что следующее установлено правильно; если нет, измените это
соответственно:IP_FORWARDING=OnПеренаправление портов (DNAT)Одной из Ваших целей может быть запуск одного или более серверов на
Ваших DMZ компьютерах. Так как эти компьютеры имеют
адреса из RFC-1918, то клиентам из Интернет невозможно
соединиться напрямую с ними. Это более невозможно для тех клиентов, кто
адресует свои запросы для соединения на файервол, который переписывает
адрес назначения на адрес Вашего сервера и переправляет пакет на этот
сервер. Когда Ваш сервер отвечает, файервол автоматически выполняет
SNAT для перезаписи адреса источника в ответе.Описанный выше процесс называется Перенапрвление Портов
(Port Forwarding) или Преобразование Сетевого Адреса
Назначения (Destination Network Address Translation -
DNAT). Вы настраиваете перенаправление портов при
помощи правил DNAT в файле /etc/shorewall/rules.Основная форма примерного правила перенаправления портов в /etc/shorewall/rules
такая: #ACTION SOURCE DEST PROTO DEST PORT(S)
DNAT net dmz:<server local IP address>[:<server port>] <protocol><port>Если
Вы не указали <server port>
(порт сервера), его значение будет таким же как и у
<port>.Вы запускаете Web-сервер на DMZ-компьютере 2 и хотите
перенаправить приходящие на порт 80 TCP-запросы на эту систему#ACTION SOURCE DEST PROTO DEST PORT(S)
Web/DNAT net dmz:10.10.11.2
Web/ACCEPT loc dmz:10.10.11.2Первая запись перенаправляет порт 80 из Интернет.Вторая запись разрешает соединения из локальной сети.Нужно иметь в виду несколько важных
моментов:Когда Вы соединяетесь с Вашим сервером с Ваших локальных
систем, Вы должны внутренний IP-адрес сервера
(10.10.11.2).Многие ISP блокируют входящие запросы для
соединения на порт 80. Если у Вас есть проблемы при соединении с
Вашим Web-сервером, попробуйте следующее правило и попытайтесь
соединиться с портом 5000 (например, подключитесь к
http://w.x.y.z:5000, где
w.x.y.z - Ваш внешний
IP).#ACTION SOURCE DEST PROTO DEST PORT(S) SOURCE
# PORT(S)
DNAT net dmz:10.10.11.2:80 tcp 80 5000Если Вы хотите иметь доступ к Вашим серверам из локальной
сети используя Ваш внешний адрес, тогда, если Вы имеете
статический внешний IP-адрес, Вы можете
заменить правило loc->dmz выше
на:#ACTION SOURCE DEST PROTO DEST PORT(S) SOURCE ORIGINAL
# PORT(S) DEST
DNAT loc dmz:10.10.11.2 tcp 80 - <external IP>Если
же у Вас динамический внешний IP-адрес, то Вы
должны убедиться, что Ваш внешний интерфейс включен перед тем как
запускать Shorewall и Вам нужно выполнить следующие операции
(подразумевая, что Ваш внешний интерфейс - eth0):Включить следующую строку в файл /etc/shorewall/params:ETH0_IP=$(find_interface_address
eth0)Создать Ваше правило
loc->dmz: #ACTION SOURCE DEST PROTO DEST PORT(S) SOURCE ORIGINAL
# PORT(S) DEST
DNAT loc dmz:10.10.11.2 tcp 80 - $ETH0_IPЕсли Вам нужен доступ к серверу из DMZ,
используйте для доступа Ваш внешний IP-адрес,
смотрите FAQ 2a.В этом месте измените добавьте правила DNAT и
ACCEPT для Ваших серверов.Когда тестируете правила DNAT похожие на те,
что приведены выше, Вы должны тестировать с клиента ИЗВНЕ ВАШЕГО
ФАЙЕРВОЛА (в зоне net). Вы не можете протестировать эти
правила изнутри файервола!Советы по разрешению проблем с DNAT, смотрите в
FAQs 1a и 1b.Сервер Доменных Имен (Domain Name Server - DNS)Normally, when you connect to your ISP, as part of getting an IP
address your firewall's Domain Name Service (DNS)
resolver will be automatically configured (e.g., the
/etc/resolv.conf file will be written).
Alternatively, your ISP may have given you the IP address of a pair of DNS
name servers for you to manually configure as your primary and secondary
name servers. It is your responsibility to configure the resolver in your
internal systems. You can take one of two approaches: You can configure your internal systems to use your
ISP's name servers. If your
ISP gave you the addresses of their servers or if
those addresses are available on their web site, you can configure
your internal systems to use those addresses. If that information
isn't available, look in /etc/resolv.conf
on your firewall system -- the name servers are given in
nameserver records in that file.Вы можете настроить Кэширующий Сервер Имен (Caching
Name Server) на Вашем файерволе или в Вашей
DMZ. Red Hat имеет
RPM для кэширующего сервера имен (которому также
необходим пакет bind-RPM), а
для пользователей Bering существует dnscache.lrp.
Если Вы пойдете этим путем, Вы настраиваете Ваши внутренние системы
на использование самого файервола как первичного (и только) сервера
имен. Вы используете внутренний IP-адрес
файервола (10.10.10.254 в
примере выше) для адреса сервера имен, если Вы запускаете сервер
имен на Вашем файерволе. Чтобы позволить Вашим локальным системам
общаться с Вашим кэширующим сервером имен, Вы должны открыть доступ
к порту 53 (оба UDP и TCP) на
файерволе из внутренней сети. Вы можете сделать это, добавив
следующее правило в файл /etc/shorewall/rules. Если Вы запускаете сервер имен
на файерволе: #ACTION SOURCE DEST PROTO DEST PORT(S)
DNS/ACCEPT loc $FW
DNS/ACCEPT dmz $FW Запуск сервера имен на
DMZ-компьютере 1: #ACTION SOURCE DEST PROTO DEST PORT(S)
DNS/ACCEPT loc dmz:10.10.11.1
DNS/ACCEPT $FW dmz:10.10.11.1 В правилах, показанных выше, DNS/ACCEPT - это пример
предопределенного макроса (defined macro). Shorewall
включает множество предопределенных макросов и Вы
можете добавить Ваши собственные. Для просмотра списка макросов,
включенных в Вашу версию Shorewall, запустите команду ls
/usr/share/shorewall/macro.*.Вы не обязаны использовать предопределенные макросы при написании
правил в файле /etc/shorewall/rules. Первый пример
выше (сервер имен на файерволе) может быть также записан как:#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT loc $FW tcp 53
ACCEPT loc $FW udp 53
ACCEPT dmz $FW tcp 53
ACCEPT dmz $FW udp 53 В случаях когда Shorewall не имеет предопределенных макросов,
отвечающих Вашим потребностям, Вы можете либо определить свой собственный
макрос, либо просто записать соответствующие правила напрямую. Эта страница может помочь Вам в случае, если Вы
не знаете используемые протокол и порт.Другие соединенияПример с тремя интерфейсами включает следующие
правила:#ACTION SOURCE DEST PROTO DEST PORT(S)
DNS/ACCEPT $FW net Это правило разрешает доступ
к DNS с Вашего файервола и может быть удалено, если Вы
раскомментировали строку в /etc/shorewall/policy,
разрешающую все соединения с файервола в Интернет.Пример также включает:#ACTION SOURCE DEST PROTO DEST PORT(S)
SSH/ACCEPT loc $FW
SSH/ACCEPT loc dmz Это правило разрешает Вам
запускать SSH-сервер на Вашем файерволе и на кождой из
Ваших DMZ-систем и соединяться с ним с Ваших локальных
систем.Если Вы хотите разрешить другие соединения с Вашего файервола к
другим системам, основной формат использования макроса
такой:#ACTION SOURCE DEST PROTO DEST PORT(S)
<macro>/ACCEPT <source zone> <destination zone>Основной формат при отсутствии предопределенных макросами действий
такой:#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT <source zone> <destination zone> <protocol> <port> Вы хотите запустить общедоступный DNS-сервер на Вашем
файерволеИспользуя предопределенный макрос:#ACTION SOURCE DEST PROTO DEST PORT(S)
DNS/ACCEPT net $FWНе используя предопределенный макрос:#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT net $FW tcp 53
ACCEPT net $FW udp 53 Эти два правила, конечно, должны быть добавлены к тем правилам,
которые указаны выше в абзаце "если Вы запускаете сервер имен на Вашем
файерволе"если Вы запускаете сервер
имен на Вашем файерволе.Если Вы не знаете какой порт и протокол использует конкретное
приложение, смотрите здесь.Я не рекоммендую разрешать telnet в/из Интернет
потому, что он использует открытый текст (даже для передачи имени и
пароля!). Если Вы хотите иметь доступ к командному интерпретатору Вашего
файервола из Интернет, используйте
SSH:#ACTION SOURCE DEST PROTO DEST PORT(S)
SSH/ACCEPT net $FWПользователи дистрибутива Bering захотят добавить следующие два
правила для совместимости с конфигурацией Shorewall от Jacques.
#ACTION SOURCE DEST PROTO DEST PORT(S)
ACCEPT loc $FW udp 53
ACCEPT net $FW tcp 80 Запись 1 разрешает использование кэширующего
DNS.Запись 2 разрешает работу weblet.Now modify /etc/shorewall/rules to add or
remove other connections as required.Что нужно помнитьВы не можете Ваш файервол
изнутри. Только потому, что Вы посылаете запросы на внешний
IP-адрес Вашего файервола не означает, что запросы
будут ассоциированы с внешним интерфейсом или зоной
net. Любой трафик, создаваемый из локальной сети будет
ассоциироваться с Вашим локальным интерфейсом и будет воспринят как
трафик loc->fw.IP-адреса - это свойства систем, а не
интерфейсов. Ошибочно верить, что Ваш файервол способен
переправит пакеты только потому, что Вы можете пропинговать
IP-адрес всех интерфейсов файервола из локальной
сети. Единственное заключение, которое Вы можете вынести из такого
успешного пингования - это наличие рабочей связи между локальной
системой и файерволом и то, что Вы, возможно, правильно указали
маршрутизатор по умолчанию на локальной системе.Все IP-адреса, настроенные на интерфейсах
файервола, принадлежат зоне $FW (fw). Если
192.168.1.254 - это IP-адрес Вашего внутреннего
интерфейса, то Вы можете написать $FW:192.168.1.254 в правиле, но Вы не
можете написать loc:192.168.1.254. Также не играет роли
добавление адреса 192.168.1.254 в зону loc при помощи
записи в файле /etc/shorewall/hosts.Ответные пакеты НЕ следуют автоматически
обратно тем маршрутом, который использовал исходный запрос.
Все пакеты маршрутизируются согласно таблице маршрутизации каждого
хоста на всем пути. Этот вопрос обычно встает когда людч устанавливают
файервол Shorewall параллельно с имеющимся шлюзом и пытаются
использовать DNAT сквозь Shorewall без изменения
шлюза по умолчанию системы, принимающей переправленные запросы.
Запросы проходят сквозь файервол Shorewall, где изменяется
IP-адрес назначения, но ответы уходят неизмененными
через старый шлюз.Shorewall сам не имеет представления о
внутренней и внешней стороне. Воплощение этих концепций
зависит от того, как настроен Shorewall.Запуск и останов Вашего файерволаПроцедура установки настраивает
Вашу систему для запуска Shorewall при загрузке системе, но запуск
остается отключен, так что система не будет пытаться запустить Shorewall
до полного завершения конфигурирования. Как только Вы полностью завершите
конфигурирование Вашего файервола, Вы можете включить запуск Shorewall,
отредактировав файл /etc/shorewall/shorewall.conf и
установив параметр STARTUP_ENABLED=Yes.Пользователи пакета .deb должны отредактировать файл
/etc/default/shorewall и установить параметр
STARTUP=1.Вы должны разрешить запуск путем редактирования файла
/etc/shorewall/shorewall.conf и установки
параметра STARTUP_ENABLED=Yes.Файервол запускается при помощи команды
shorewall start и останавливается при
помощи shorewall stop. Когда файервол
остановливается, маршрутизация разрешается на те хосты, которые указаны в
/etc/shorewall/routestopped.
Запущенный файервол может быть перезапущен при помощи команды
shorewall restart. Если Вы хотите
полностью удалить изменения сделанные Shorewall из конфигурации Вашего
Netfilter, используйте команду shorewall
clear.Пример с двумя интерфейсами предполагает, что Вы хотите разрешить
маршрутизацию к/из eth1 (локальная
сеть) и eth2
(DMZ) когда Shorewall остановлен. Если эти два
интерфейса не соединены с Вашей локальной сетью и DMZ
или если Вы хотите разрешить другой набор хостов, измените файл
/etc/shorewall/routestopped соответственно.Если Вы подсоединены к Вашему файерволу из Интернет, не
используйте команду shorewall stop
если Вы не добавили запись для IP-адреса, с
которого Вы подсоединены, в /etc/shorewall/routestopped.
Также, я не рекоммендую использовать shorewall
restart; лучше создать альтернативную
конфигурацию и протестировать ее при помощи команды
shorewall
try.Дополнительно рекоммендуемая литератураЯ особо рекоммендую просмотреть Вам страницу Общих Особенностей Файлов
Конфигурации -- она содержит полезные советы об особенностях
Shorewall, делающую администрирование Вашего файервола проще.
shorewall-docs-xml-5.0.4/shorewall_setup_guide_fr.xml 0000644 0000000 0000000 00000341423 12647470621 021570 0 ustar root root
Guide de configuration ShorewallVersion Franaise de Shorewall Setup
GuideTomEastepFabienDemassieuxTraduction Franaise initialeGuyMarcenacAdaptation franaise version 3.02002-2006Thomas M. EastepFabien DemassieuxGuy MarcenacPermission est accorde de copier, distribuer et/ou modifier ce
document selon les termes de la Licence de Documentation Libre GNU (GNU
Free Documentation License), version 1.2 ou toute version ultrieure
publie par la Free Software Foundation ; sans section Invariables, sans
premire de Couverture, et sans texte de quatrime de couverture. Une
copie de la prsente Licence est incluse dans la section intitule. Une
traduction franaise de la licence se trouve dans la section
Licence de
Documentation Libre GNU. Ce paragraphe est une
traduction franaise pour aider votre comprhension. Seul le texte
original en anglais prsent ci-dessous fixe les conditions
d'utilisation de cette documentation.Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version
1.2 or any later version published by the Free Software Foundation; with
no Invariant Sections, with no Front-Cover, and with no Back-Cover
Texts. A copy of the license is included in the section entitled
GNU Free Documentation
License.Notes du traducteur : Le
traduction initiale a t ralise par Fabien Demassieux. J'ai assur la
rvision pour l'adapter la version 3 de Shorewall. Si vous trouvez des
erreurs ou des amliorations y apporter vous pouvez me contacter.Cet article s'applique Shorewall 3.0 et
ses versions ultrieures. Si vous utilisez une version plus ancienne de
Shorewall, rfrez-vous la documentation s'appliquant votre
version.IntroductionCe guide est destin aux utilisateurs qui configurent Shorewall dans
un environnement o un ensemble d'adresses IP publiques doit tre pris en
compte ainsi qu' ceux qui souhaitent en savoir plus propos de Shorewall
que ce que contiennent le guides pour une utilisation avec une adresse IP unique. Le champs
d'application tant trs large, ce guide vous donnera des indications
gnrales suivre et vous indiquera d'autres ressources si
ncessaire.Shorewall a besoin que le paquetage
iproute/iproute2
soit install (avec la distribution RedHat, le
paquetage s'appelle iproute). Vous
pouvez contrler que le paquetage est install en vrifiant la prsence
du programme ip sur votre
firewall. En tant que root,
vous pouvez utiliser la commande which pour
cela:[root@gateway root]# which ip
/sbin/ip
[root@gateway root]#Je vous recommande de commencer par une lecture complte du guide
afin de vous familiariser avec les concepts mis en oeuvre, puis de
recommencer la lecture et seulement alors d'appliquer vos modifications
de configuration.Les points o des modifications s'imposent sont indiqus par
.Si vous ditez vos fichiers de configuration sur un systme
Windows, vous devez les enregistrer comme des
fichiers Unix si votre diteur supporte cette
option sinon vous devez les convertir avec dos2unix
avant d'essayer de les utiliser. De la mme manire, si vous copiez un
fichier de configuration depuis votre disque dur
Windows vers une disquette, vous devez lancer
dos2unix sur la copie avant de l'utiliser avec
Shorewall.Version
Windows de dos2unixVersion Linux de
dos2unixLes Concepts de ShorewallLes fichiers de configuration pour Shorewall sont situs dans le
rpertoire /etc/shorewall -- pour de simples paramtrages, vous n'aurez
faire qu'avec quelques-uns d'entre eux comme dcrit dans ce guide. Des
squelettes de fichiers sont crs durant la
procdure d'installation de Shorewall.Note aux utilisateurs de
DebianSi vous vous servez du .deb pour installer, vous vous rendrez
compte que votre rpertoire /etc/shorewall est vide. Ceci est voulu.
Les squelettes des fichiers de configuration se trouvent sur votre
systme dans le rpertoire /usr/share/doc/shorewall/default-config.
Copiez simplement les fichiers dont vous avez besoin depuis ce
rpertoire dans /etc/shorewall,
puis modifiez ces copies.Remarquez que vous devez copier
/usr/share/doc/shorewall/default-config/shorewall.conf et
/usr/share/doc/shorewall/default-config/modules
dans /etc/shorewall mme si
vous ne modifiez pas ces fichiers.Au fur et mesure de la prsentation de chaque fichier, je vous
suggre de jeter un oeil ceux physiquement prsents sur votre systme --
chacun des fichiers contient des instructions de configuration dtailles
et des entres par dfaut.Shorewall voit le rseau o il fonctionne, comme tant compos d'un
ensemble de zones. Dans ce guide nous utiliserons les zones
suivantes:fwLe firewall lui-mme.netL'internet public.locUn rseau local priv utilisant des adresses IP
prives.dmzUne zone dmilitarise (DMZ) contenant les
serveurs publiquement accessibles.Les Zones sont dfinies dans le fichier /etc/shorewall/zones.Le fichier /etc/shorewall/zones fourni avec
la distribution est vide. Vous pouvez crer l'ensemble de zones standard
dcrites au-dessus en copiant puis en collant ce qui suit dans le
fichier:#ZONE TYPE OPTIONS
fw firewall
net ipv4
loc ipv4
dmz ipv4Remarquez que Shorewall reconnat aussi le systme firewall comme sa
propre zone - l'exemple ci-dessus suit la convention qui veut que la zone
firewall soit nomme fw. Le nom de la
zone firewall (fw dans l'exemple plus
haut) est stock dans la variable d'environnement $FW
lorsque le fichier /etc/shorewall/zones est trait. A
l'exception du nom attribu la zone firewall, Shorewall n'attache aucune
signification aux noms de zone. Le zones sont entirement ce que VOUS en
faites. Ceci signifie que vous ne devriez pas attendre de Shorewall qu'il
fasse quoi que ce soit de spcial car il s'agit de la zone
internet ou car ceci est la
DMZ.ditez le fichier /etc/shorewall/zones et
faites-y les changements ncessaires.Les rgles qui concernent le trafic autoriser ou refuser sous
exprimes en termes de Zones.Vous exprimez les politiques par dfaut entre une zone et une
autre zone dans le fichier /etc/shorewall/policy.Vous dfinissez les exceptions ces politiques par dfaut dans
le fichier /etc/shorewall/rules.Shorewall est construit sur les mcanismes de Netfilter, service de filtrage du
noyau (kernel). Netfilter fournit une fonction
de suivi de connexion qui permet une analyse d'tat des paquets
(stateful inspection). Cette proprit permet aux rgles du firewall
d'tre dfinies en termes de connexions plutt qu'en termes de paquets.
Avec Shorewall, vous:Identifiez la zone source (client).Identifiez la zone destination (serveur).Si la politique depuis la zone du client vers la zone du serveur
est ce que vous souhaitez pour cette paire client/serveur, vous n'avez
rien de plus faire.Si la politique n'est pas ce que vous souhaitez, alors vous
devez ajouter une rgle. Cette rgle est exprime en termes de zone
client et de zone serveur.Autoriser les connexions d'un certain type
depuis la zone A vers le firewall et depuis firewall vers la zone B
NE SIGNIFIE PAS que ces connections sont autoriss
de la zone A la zone B (autrement dit, les
connexions impliquant la zone firewall ne sont pas transitives).Pour chaque connexion demandant entrer dans le firewall, la
requte est en premier lieu vrifie par rapport au fichier
/etc/shorewall/rules. Si aucune rgle dans ce fichier
ne correspond la demande de connexion alors la premire politique dans
le fichier /etc/shorewall/policy qui y correspond
sera applique. S'il y a une action par dfaut dfinie
pour cette politique dans /etc/shorewall/actions ou
dans /usr/share/shorewall/actions.std cette action
commune sera excute avant que l'action spcifie dans
/etc/shorewall/rules ne soit applique.Avant Shorewall 2.2.0, le fichier
/etc/shorewall/policy avait les politiques
suivantes:#SOURCE ZONE DESTINATION ZONE POLICY LOG LIMIT:BURST
# LEVEL
fw net ACCEPT
net all DROP info
all all REJECT infoLe fichier de politiques distribu actuellement est vide. Vous
pouvez y copier et coller les entres prsentes ci-dessus comme point
de dpart, puis l'adapter vos propres politiques.Les politiques prcdentes vont:Autoriser (ACCEPT) toutes les connexions de votre rseau local
vers internetIgnorer (DROP) toutes les tentatives de connexions d'internet
vers le firewall ou vers votre rseau local et enregistrer dans vos
journaux (log) un message au niveau info (vous trouverez ici la description des
niveaux de journalisation).Rejeter (REJECT) toutes les autres demandes de connexion et
gnrer un message de niveau info dans votre journal. Quant la requte
est rejete et que le protocole est TCP, le firewall retourne un
paquet RST. Pour tous les autres protocoles, quand une requte est
rejete, le firewall renvoie un paquet ICMP port-unreachable.Maintenant, ditez votre /etc/shorewall/policy
et apportez-y tous les changements que vous souhaitez.Interfaces RseauDans la suite du guide, nous nous rfrerons au schma ci-dessous.
Bien qu'il puisse ne pas correspondre votre propre rseau, il peut tre
utilis pour illustrer les aspects importants de la configuration de
Shorewall.Sur ce schma:La zone DMZ est compose des systmes DMZ 1
et DMZ 2. On utilise une DMZ pour isoler ses
serveurs accessibles depuis internet de ses systmes locaux. Ainsi si
un des serveurs de la DMZ est compromis, vous avez
encore un firewall entre le systme compromis et vos systmes
locaux.La zone local est compose des systmes Local 1,
Local 2 et Local 3.Tous les systmes l'extrieur du firewall, y compris ceux de
votre FAI, sont dans la zone internet.La faon la plus simple pour dfinir les zones est d'associer le nom
de la zone (dfinie prcdemment dans
/etc/shorewall/zones) une interface rseau. Ceci
est fait dans le fichier /etc/shorewall/interfaces.Le firewall illustr ci-dessus trois interfaces rseau. Lorsque la
connexion internet passe par un modem cble
ou ADSL
l'Interface
Externe sera l'adaptateur ethernet qui est connect
ce Modem (par exemple eth0). Par contre, si vous vous connectez
avec PPPoE (Point-to-Point Protocol over Ethernet) ou
avec PPTP (Point-to-Point Tunneling
Protocol), l'interface externe sera une interface ppp (par exemple
ppp0). Si vous vous connectez
avec un simple modem RTC, votre
interface externe sera aussi ppp0. Si vous vous connectez en
utilisant l'ISDN, votre interface
externe sera ippp0.Si votre interface vers l'extrieur est
ppp0 ou ippp0 alors vous mettrez CLAMPMSS=yes dans
le fichier
/etc/shorewall/shorewall.conf.Votre Interface locale sera un adaptateur
ethernet (eth0, eth1
or eth2) et sera connecte un hub
ou un switch. Vos ordinateurs locaux seront connects ce mme hub ou
switch (note : si vous n'avez qu'un seul ordinateur en local, vous pouvez
le connecter directement au firewall par un cble crois).Votre interface DMZ sera
aussi un adaptateur ethernet (eth0, eth1
or eth2) et sera connect un hub
ou un switch. Vos ordinateurs appartenant la DMZ seront connects ce
mme hub ou switch (note : si vous n'avez qu'un seul ordinateur dans la
DMZ, vous pouvez le connecter directement au firewall
par un cble crois).Ne connectez pas les interfaces interne et
externe sur le mme hub ou le mme switch, sauf des fins de
test. Vous pouvez tester en utilisant ce type de
configuration si vous spcifiez l'option arp_filter ou l'option arp_ignore dans le fichier /etc/shorewall/interfaces, et
ce pour toutes les interfaces connectes au hub/switch
commun. Il est trs fortement dconseill
d'utiliser une telle configuration avec un firewall en
production.Dans la suite, nous supposerons que:L'interface externe est eth0.L'interface locale est eth1.L'interface DMZ est eth2.La configuration par dfaut de Shorewall ne dfinit le contenu
d'aucune zone. Pour dfinir la configuration prsente plus haut, le
fichier /etc/shorewall/interfaces doit
contenir:#ZONE INTERFACE BROADCAST OPTIONS
net eth0 detect rfc1918
loc eth1 detect
dmz eth2 detectRemarquez que la zone $FW n'a aucune entre dans le fichier
/etc/shorewall/interfaces.ditez le fichier /etc/shorewall/interfaces.
Dfinissez les interfaces du rseau de votre firewall et associez chacune
d'entre elles une zone. Si vous avez une zone qui est connecte par plus
d'une interface, incluez simplement une entre pour chaque interface et
rptez le nom de zone autant de fois que ncessaire.Interfaces Multiples associes une Zone#ZONE INTERFACE BROADCAST OPTIONS
net eth0 detect rfc1918
loc eth1 detect
loc eth2 detectVous pouvez dfinir des zones plus compliques en utilisant le
fichier/etc/shorewall/hosts mais
dans la plus part des cas, cela ne sera pas ncessaire. Vous trouverez des
exemples dans Shorewall_and_Aliased_Interfaces.html
et Multiple_Zones.html.Adressage, Sous-rseaux et RoutageNormalement, votre FAI vous attribue un ensemble
d'adresses IP publiques. Vous utiliserez une de ces adresses pour
configurer l'interface externe de votre firewall. Vous dciderez ensuite
comment utiliser le reste de vos adresses. Avant d'aborder ce point, il
nous faut rappeler le contexte.Si vous tes dj familier de l'adressage IP et du routage, vous
pouvez directement aller la prochaine section.La prsentation qui suit ne fait que d'effleurer les questions de
l'adressage et du routage. Si vous vous voulez en apprendre plus sur
l'adressage IP et le routage, je vous recommande
IP Fundamentals: What Everyone Needs to Know about Addressing &
Routing, Thomas A. Maufer, Prentice-Hall, 1999, ISBN 0-13-975483-0
(lien).Adressage IPLes adresses IP version 4 (IPv4) sont codes sur 32 bits. La
notation w.x.y.z fait rfrence une adresse dont l'octet de poids fort
a pour valeur w, le suivant a pour valeur
x, etc. Si nous prenons l'adresse 192.0.2.14 et que nous
l'exprimons en hexadcimal, nous obtenonsC0.00.02.0Eet si nous la
regardons comme un entier de 32 bits nous avonsC000020ESous-rseauxVous entendrez encore aujourd'hui les termes de Rseau de
classe A, Rseau de classe B et Rseau de
classe C. Au dbut de l'existence de l'IP, les rseaux ne
pouvaient avoir que trois tailles (il y avait aussi les rseaux de
classe D mais il taient utiliss diffremment):Classe A - masque de sous-rseau 255.0.0.0, taille = 2 **
24Classe B - masque de sous-rseau 255.255.0.0, taille = 2 **
16Classe C - masque de sous-rseau 255.255.255.0, taille =
256La classe d'un rseau tait dtermine de faon unique par la
valeur de l'octet de poids fort de son adresse, ainsi en regardant une
adresse IP on pouvait dterminer immdiatement la valeur du masque
rseau. Le masque rseau est un nombre qui combin une adresse par un
ET logique, isole l'adresse du rseau auquel cette adresse appartient.
Le reste de l'adresse est le numro d'hte. Par
exemple, dans l'adresse de classe C 192.0.2.14, la valeur hexadcimale
de l'adresse du rseau est C00002 et le numro d'hte est 0E.Comme internet se dveloppait, il devint clair qu'un
partitionnement aussi grossier de l'espace d'adresses de 32 bits allait
tre trs limitatif (rapidement, les grandes socits et les universits
s'taient dj attribues leur propre rseau de classe A !). Aprs
quelques faux dparts, la technique courante du sous-adressage de ces
rseaux en plus petits sous-rseaux volua. On fait rfrence cette
technique sous l'appellation de Routage Inter-Domaine Sans Classe ou
Classless InterDomain Routing
(CIDR). Aujourd'hui, les systmes avec lesquels vous
travaillez sont probablement compatibles avec la notation CIDR. La
gestion des rseaux base sur les Classes est du domaine du
pass.Un sous-rseau (subnet
ou subnetwork) est un ensemble contigu d'adresses
IP tel que:Le nombre d'adresses dans le jeu est un multiple de 2.La premire adresse dans le jeu est un multiple de la taille
du jeu.La premire adresse du sous-rseau est rserve et on s'y
rfre comme tant l'adresse du
sous-rseau.La dernire adresse du sous-rseau est rserve comme
adresse de diffusion (broadcast) du
sous-rseau.Comme vous pouvez le constater par cette dfinition, dans chaque
sous-rseau de taille n il y a (n - 2) adresses utilisables (adresses
qui peuvent tre attribues un hte). La premire et la dernire
adresse du sous-rseau sont utilises respectivement pour identifier
l'adresse du sous-rseau et l'adresse de diffusion du sous-rseau. En
consquence, de petits sous-rseaux sont plus gourmands en adresses IP
que des sous-rseaux plus tendus.Comme n est une puissance de deux, nous pouvons aisment calculer
le Logarithme base 2 de n (log2). La taille et le
logarithme base 2 pour les tailles de sous-rseau les plus communes
sont donns par la table suivante:
Logarithmes base 2nlog2 n(32 - log2 n)832916428325276462612872525682451292310241022204811214096122081921319163841418327681517655361616
Vous constaterez que la table ci-dessus contient aussi une colonne
(32 - log2 n). Ce nombre est le
Masque de Sous-rseau Longueur Variable ou
Variable Length Subnet Mask
(VLSM) pour un sous-rseau de taille n. De la table
ci-dessus, nous pouvons dduire la suivante, qui est plus facile
utiliser.
VLSMTaille du
sous-rseauVLSMMasque de
sous-rseau8/29255.255.255.24816/28255.255.255.24032/27255.255.255.22464/26255.255.255.192128/25255.255.255.128256/24255.255.255.0512/23255.255.254.01024/22255.255.252.02048/21255.255.248.04096/20255.255.240.08192/19255.255.224.016384/18255.255.192.032768/17255.255.128.065536/16255.255.0.02 ** 24/8255.0.0.0
Notez que le VLSM est crit avec un slash
(/) -- vous entendrez souvent nommer un rseau de taille
64 comme tant un slash 26 et un de taille 8 comme tant
un slash 29.Le masque de sous-rseau est simplement un nombre de 32 bits avec
les premiers bits correspondant au VLSM positionns
1 et les bits suivants 0. Par exemple,
pour un sous-rseau de taille 64, le masque de sous-rseau dbute par 26
bits 1:11111111111111111111111111000000 = FFFFFFC0 = FF.FF.FF.C0 = 255.255.255.192Le
masque de sous-rseau a la proprit suivante: si vous appliquez un ET
logique entre le masque de sous-rseau et une adresse dans le
sous-rseau, le rsultat est l'adresse du sous-rseau. Tout aussi
important, si vous appliquer un ET logique entre le masque de
sous-rseau et une adresse en dehors du sous-rseau, le rsultat n'est
PAS l'adresse du sous-rseau. Comme nous le verrons aprs, cette
proprit du masque de sous-rseau est trs importante dans le
routage.Pour un sous-rseau dont l'adresse est a.b.c.d et dont le VLSM est
/v, nous notons le sous-rseau
a.b.c.d/v en utilisant
la notation CIDR.
Un exemple de sous-rseau :Sous-rseau:10.10.10.0 - 10.10.10.127Taille du
sous-rseau:128Adresse du
sous-rseau:10.10.10.0Adresse de
diffusion:10.10.10.127Notation CIDR:10.10.10.0/25
Il existe deux sous-rseaux dgnrs qui doivent tre mentionns:
le sous-rseau avec un seul membre et le sous-rseau avec 2 ** 32
membres.
/32 and /0Taille du
sous-rseauLongueur VLSMMasque de
sous-rseauNotation CIDR132255.255.255.255a.b.c.d/323200.0.0.00.0.0.0/0
Ainsi, chaque adresse a.b.c.d
peut aussi tre crite a.b.c.d/32 et
l'ensemble des adresses possibles est crit 0.0.0.0/0.Un utilisateur de Shorewall a propos cette trs utile reprsentation
graphique de ces informations.Dans la suite, nous utiliserons la notation a.b.c.d/v pour dcrire la configuration IP d'une
interface rseau (l'utilitaire ip utilise aussi cette
syntaxe). Dans cette notation l'interface est configure avec une
adresse ip a.b.c.d avec le masque de
sous-rseau qui correspond au VLSM /v.192.0.2.65/29L'interface est configure avec l'adresse IP 192.0.2.65 et le
masque de sous-rseau 255.255.255.248./sbin/shorewall propose une commande ipcalc qui
calcule automatiquement les informations d'un [sous-]rseau.Utiliser la commande
ipcalc.shorewall ipcalc 10.10.10.0/25
CIDR=10.10.10.0/25
NETMASK=255.255.255.128
NETWORK=10.10.10.0
BROADCAST=10.10.10.127Utiliser la commande
ipcalc.shorewall ipcalc 10.10.10.0 255.255.255.128
CIDR=10.10.10.0/25
NETMASK=255.255.255.128
NETWORK=10.10.10.0
BROADCAST=10.10.10.127RoutageL'un des objectifs de la gestion en sous-rseaux est qu'elle pose
les bases pour le routage. Ci-dessous se trouve la table de routage de
mon firewall:[root@gateway root]# netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flgs MSS Win irtt Iface
192.168.9.1 0.0.0.0 255.255.255.255 UH 40 0 0 texas
206.124.146.177 0.0.0.0 255.255.255.255 UH 40 0 0 eth1
206.124.146.180 0.0.0.0 255.255.255.255 UH 40 0 0 eth3
192.168.3.0 0.0.0.0 255.255.255.0 U 40 0 0 eth3
192.168.2.0 0.0.0.0 255.255.255.0 U 40 0 0 eth1
192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0 eth2
206.124.146.0 0.0.0.0 255.255.255.0 U 40 0 0 eth0
192.168.9.0 192.0.2.223 255.255.255.0 UG 40 0 0 texas
127.0.0.0 0.0.0.0 255.0.0.0 U 40 0 0 lo
0.0.0.0 206.124.146.254 0.0.0.0 UG 40 0 0 eth0
[root@gateway root]#L'interface texas est un tunnel GRE vers un
site pair Dallas, au Texas.Les trois premires routes sont des routes vers des htes
(host routes) puisqu'elles indiquent comment aller
vers un hte unique. Dans la sortie de netstat, cela
se voit trs bien au masque de sous-rseau (Genmask) 255.255.255.255,
ou bien au drapeau H dans la colonne
Flags . Les autres routes sont des routes rseau car
elles indiquent au noyau comment router des paquets un sous-rseau. La
dernire route est la route par dfaut. La
passerelle mentionne dans cette route est appele la
passerelle par dfaut (default gateway).Quant le noyau essaye d'envoyer un paquet une adresse IP
A, il commence au dbut de la table de
routage et:Il ralise un ET logique entre
A et la valeur du masque de sou-rseau pour
cette entre de la table.Ce rsultat est compar avec la valeur de la
Destination dans cette entre de la table.Si le rsultat et la valeur de la Destination
sont identiques, alors:Si la colonne Gateway n'est pas nulle, le
paquet est envoy la passerelle par l'interface nomme dans la
colonne Iface.Sinon, le paquet est directement envoy A travers l'interface nomme dans la
colonne iface.Sinon, les tapes prcdentes sont rptes sur l'entre
suivante de la table.Puisque la route par dfaut correspond toutes les adresses IP
(A ET 0.0.0.0 = 0.0.0.0), les paquets
qui ne correspondent aucune des autres entres de la table de routage
sont envoys la passerelle par dfaut qui est gnralement un routeur
de votre FAI.Prenons un exemple. Supposons que vous souhaitiez router un paquet
192.168.1.5. Cette adresse ne correspond aucune route d'hte dans la
table mais lorsque nous faisons le ET logique de cette adresse avec
255.255.255.0, le rsultat est 192.168.1.0 qui correspond cette entre
de la table:192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0 eth2Donc, pour router ce paquet 192.168.1.5, il faudra le
transmettre directement l'interface eth2.Un point important doit tre soulign -- tous les paquets sont
envoys en utilisant la table de routage et les paquets en rponse ne
sont pas un cas particulier. Il semble exister une ide fausse comme
quoi les paquets rponses seraient comme les saumons et contiendraient
une sorte de code gntique qui leur permettrait suivre la mme route
emprunte par les paquets de requte (request) l'aller. Ce n'est pas
le cas. Les rponses peuvent prendre un chemin totalement diffrent de
celui pris par les paquets de la requte client l'aller -- Ces routes
sont totalement indpendantes.Protocole de Rsolution d'Adresse (ARP)Quant on envoie des paquets sur ethernet, les adresses IP ne sont
pas utilises. L'adressage ethernet est bas sur les adresses
MAC (Media Access Control).
Chaque carte ethernet sa propre adresse MAC unique
qui est grave dans une PROM lors de sa fabrication.
Vous pouvez obtenir l'adresse MAC d'une carte
ethernet grce l'utilitaire
ip:[root@gateway root]# ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP> mtu 1500 qdisc htb qlen 100
link/ether 02:00:08:e3:fa:55 brd ff:ff:ff:ff:ff:ff
inet 206.124.146.176/24 brd 206.124.146.255 scope global eth0
inet 206.124.146.178/24 brd 206.124.146.255 scope global secondary eth0
inet 206.124.146.179/24 brd 206.124.146.255 scope global secondary eth0
[root@gateway root]#
Comme vous pouvez le constater, l'adresse MAC
est code sur 6 octets (48 bits). L'adresse MAC est
gnralement imprime sur la carte elle-mme.Comme IP utilise les adresses IP et ethernet les adresses MAC, il
faut un mcanisme pour transcrire une adresse IP en adresse MAC. C'est
ce dont est charg le protocole de rsolution d'adresse
(Address Resolution Protocol
ARP). Voici ARP en
action:[root@gateway root]# tcpdump -nei eth2 arp
tcpdump: listening on eth2
09:56:49.766757 2:0:8:e3:4c:48 0:6:25:aa:8a:f0 arp 42:
arp who-has 192.168.1.19 tell 192.168.1.254
09:56:49.769372 0:6:25:aa:8a:f0 2:0:8:e3:4c:48 arp 60:
arp reply 192.168.1.19 is-at 0:6:25:aa:8a:f0
2 packets received by filter
0 packets dropped by kernel
[root@gateway root]#Dans cet change , 192.168.1.254 (MAC 2:0:8:e3:4c:48) veut
connatre l'adresse MAC du priphrique qui a l'adresse IP 192.168.1.19.
Le systme ayant cette adresse IP rpond que l'adresse MAC du
priphrique avec l'adresse IP 192.168.1.19 est 0:6:25:aa:8a:f0.Afin de ne pas avoir changer des information
ARP chaque fois qu'un paquet doit tre envoy, le
systme maintient un cache des correspondances IP<-> MAC. Vous
pouvez voir le contenu du cache ARP sur votre systme
(y compris sur les systmes Windows) en utilisant
la commande arp[root@gateway root]# arp -na
? (206.124.146.177) at 00:A0:C9:15:39:78 [ether] on eth1
? (192.168.1.3) at 00:A0:CC:63:66:89 [ether] on eth2
? (192.168.1.5) at 00:A0:CC:DB:31:C4 [ether] on eth2
? (206.124.146.254) at 00:03:6C:8A:18:38 [ether] on eth0
? (192.168.1.19) at 00:06:25:AA:8A:F0 [ether] on eth2Les points d'interrogation au dbut des lignes sont le rsultat de
l'utilisation de l'option n qui empche le programme
arp de rsoudre le noms DNS pour
les adresses IP (la commande arpde
Windows n'accepte pas cette option) . Si je n'avais pas
utilis pas cette option, les points d'interrogation seraient remplacs
par les noms pleinement qualifis (FQDN) correspondant chaque adresse
IP. Remarquez que la dernire information dans le cache correspond
celle que nous avons vue en utilisant tcpdump
l'instant.RFC 1918Les adresses IP sont alloues par l'IANA
(Internet Assigned Number
Authority) qui dlgue les allocations sur une base gographique
aux Registres Internet Rgionaux (RIR). Par exemple,
les allocations pour les Etats-Unis et l'Afrique sub-Saharienne sont
dlgues l'ARIN (American Registry for Internet
Numbers). Ces RIRs peuvent leur tour dlguer des bureaux
nationaux. La plupart d'entre nous ne traite pas avec ces autorits mais
obtient plutt ses adresse IP de son FAI.Dans la ralit, on ne peut en gnral pas se permettre d'avoir
autant d'adresses IP publiques que l'on a de priphriques en
ncessitant une. C'est cette raison qui nous amne utiliser des
adresses IP prives. La RFC 1918 rserve plusieurs plages d'adresses
cette fin :10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255Les adresses rserves par la RFC 1918 sont parfois appeles
non-routables car les routeurs d'infrastructure internet ne feront pas
suivre (forward) les paquets qui ont une adresse de destination de la
RFC 1918. Cela est comprhensible puisque chacun peut choisir n'importe
laquelle ces adresses pour son usage priv. Mais le terme de
non-routable est quelque peu malencontreux car il peut amener conclure
de manire errone que le trafic destin une de ces adresses ne peut
tre envoy travers un routeur. Ceci est faux et les routeurs privs,
dont votre firewall Shorewall, peuvent parfaitement faire suivre du
trafic avec des adresses conformes la RFC 1918.Quant on choisit des adresses dans ces plages, il faut bien avoir
l'esprit les choses suivantes:Comme l'espace des adresses IPv4 s'puise, de plus en plus
d'organisation (y compris les FAI) commencent utiliser les
adresses RFC 1918 dans leurs infrastructures.Vous ne devez pas utiliser d'adresse IP qui soit utilise par
votre FAI ou une autre organisation avec laquelle
vous souhaitez tablir une liaison VPNC'est pourquoi c'est une bonne ide de vrifier aprs de votre FAI
s'il n'utilise pas (ou ne prvoie pas d'utiliser) des adresses prives
avant de dcider quelles adresses que vous allez utiliser.Dans ce document, les adresses IP externes
relles sont dans la plage 192.0.2.x. Les adresses du
rseau 192.0.2.0/24 sont rserves par RFC 3330 pour l'utilisation
d'adresses IP publiques dans les exemples imprims ainsi que dans les
rseaux de test. Ces adresses ne doivent pas tre confondues avec les
adresses 192.168.0.0/16, qui comme dcrit ci-dessus, sont rserves
par la RFC 1918 pour une utilisation prive.Configurer votre RseauLe choix d'une configuration pour votre rseau dpend d'abord du
nombre d'adresses IP publiques dont vous disposez et du nombre d'adresses
IP dont vous avez besoin. Quel que soit le nombre d'adresses dont vous
disposez, votre FAI peut vous servir ce jeu d'adresses
de deux manires:Routes - Le trafic vers
chacune de vos adresses publiques sera rout travers une seule
adresse de passerelle. Cela sera gnralement fait si votre FAI vous
attribue un sous-rseau complet (/29 ou plus). Dans ce cas, vous
affecterez l'adresse de cette passerelle comme tant l'adresse de
l'interface externe de votre firewall/routeur.Non routes - Votre FAI enverra
le trafic chacune de vos adresses directement.Dans les paragraphes qui suivent, nous tudierons chacun de ces cas
sparment.Avant de commencer, il y a une chose que vous devez vrifier:Si vous utilisez un paquetage Debian, vrifiez votre fichier
shorewall.conf afin de vous assurer que les
paramtres suivants sont convenablement fixs. Si ce n'est pas le cas,
appliquez les changements ncessaires:IP_FORWARDING=OnRoutSupposons que votre fournisseur d'accs vous ait assign le
sous-rseau 192.0.2.64/28 rout par 192.0.2.65. Vous avez les adresses
IP 192.0.2.64 - 192.0.2.79 et l'adresse externe de votre firewall est
192.0.2.65. Votre FAI vous a aussi dit que vous devez utiliser le masque
de sous-rseau 255.255.255.0 (ainsi, votre /28 est un sous-ensemble du
/24, plus grand). Avec autant d'adresses IP, vous pouvez scinder votre
rseau /28 en deux sous-rseaux /29 et configurer votre rseau comme
l'indique le diagramme suivant.Dans l'exemple, la zone dmilitaris DMZ est
dans le sous-rseau 192.0.2.64/29 et le rseau local est dans
192.0.2.72/29. La passerelle par dfaut pour les htes dans la
DMZ doit tre configure 192.0.2.66 et la
passerelle par dfaut pour ceux du rseau local doit tre configure
192.0.2.73.Notez que cette solution est plutt gourmande en adresses
publiques puisqu'elle utilise 192.0.2.64 et 192.0.2.72 pour les adresses
de sous-rseau, 192.0.2.71 et 192.0.2.79 pour les adresses de diffusion
(broadcast) du rseau, et 192.0.2.66 et 168.0.2.73 pour les adresses
internes sur le firewall/routeur. Elle montre nammoins comment la
gestion en sous-rseaux peut fonctionner. Et si nous avions un rseau
/24 plutt qu'un /28, l'utilisation de 6 adresses IP parmi les 256
disponibles serait largement justifie par la simplicit du
paramtrage.Le lecteur attentif aura peut-tre remarqu que l'interface
externe du firewall/Routeur est en fait incluse dans le sous-rseau
DMZ (192.0.2.64/29). On peut se demander ce qui se
passe quand l'hte DMZ 1 (192.0.2.67) essaye de communiquer avec
192.0.2.65. La table de routage sur l'hte DMZ 1 doit ressembler
cela:Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
192.0.2.64 0.0.0.0 255.255.255.248 U 40 0 0 eth0
0.0.0.0 192.0.2.66 0.0.0.0 UG 40 0 0 eth0Donc, lorsque l'hte DMZ 1 voudra communiquer avec 192.0.2.65, il
enverra une requte ARP "qui-a 192.0.2.65" alors
qu'aucune interface sur le segment ethernet DMZ n'a cette adresse IP.
Assez bizarrement, le firewall rpondra la requte avec
l'adresse MAC de sa propre interface
DMZ! DMZ 1 peut alors envoyer des
trames ethernet adresses cette adresse MAC et les
trames seront reues correctement par le firewall/routeur.L'avertissement fait plus haut qui dconseille trs fortement la
connexion de plusieurs interfaces du firewall/routeur un mme hub ou
switch est une consquence directe de ce comportement plutt inattendu
d'ARP de la part du noyau Linux. Quant une requte
ARP destine une des adresses du firewall/routeur est envoye par un
autre systme connect au mme hub ou switch, toutes les interfaces du
firewall qui y sont connectes peuvent rpondre ! C'est alors la course
savoir quelle rponse c'est-ici atteindra la premire
l'metteur de la requte.Non routSi vous tes dans la situation prcdente mais que votre trafic
n'est pas rout par votre FAI, vous pouvez configurer
votre rseau exactement comme dcrit plus haut, au prix d'une lgre
contorsion supplmentaire: spcifiez simplement l'option
proxyarp sur les trois interfaces du
firewall dans le fichier
/etc/shorewall/interfaces.La plupart d'entre nous n'ont pas le luxe d'avoir suffisamment
d'adresses publiques IP pour configurer leur rseau comme indiqu dans
l'exemple prcdent (mme si la configuration est route).Dans le reste de cette section, supposons
que notre FAI nous ait assign la plage d'adresses IP 192.0.2.176-180,
qu'il nous ait dit d'utiliser le masque de sous-rseau 255.255.255.0 et
que la passerelle par dfaut soit 192.0.2.254.De toute vidence, ce jeu d'adresses ne comprend pas de
sous-rseau et n'a pas suffisamment d'adresses pour toutes les
interfaces de notre rseau. Nous pouvons utiliser quatre techniques
diffrentes pour contourner ce problme.La traduction d'adresses source (Source Network
Address TranslationSNAT).La traduction d'adresses destination (Destination
Network Address TranslationDNAT) nomme aussi transfert ou suivi de port
(Port Forwarding).Le Proxy
ARP.La traduction d'adresses rseau (Network Address
Translation NAT) laquelle on fait
aussi rfrence sous l'appellation de un--un NAT (one-to-one
NAT).Souvent, une combinaison de ces techniques est utilise. Chacune
d'entre elles sera dtaille dans la section suivante.SNATAvec la SNAT, un segment interne du rseau
local est configur en utilisant des adresses de la RFC 1918. Quant un
hte A sur ce segment interne initie
une connexion vers un hte B sur
internet, le firewall/routeur rcrit les enttes IP de la requte
pour utiliser une de vos adresses publiques IP en tant qu'adresse
source. Quant B rpond et que la
rponse est reue par le firewall, le firewall change l'adresse
destination par celle de la RFC 1918 de A et transfre la rponse A.Supposons que vous dcidiez d'utiliser la SNAT sur votre zone
locale. Supposons galement que vous utilisiez l'adresse publique
192.0.2.176 la fois comme adresse externe du firewall et comme
adresse source des requtes internet envoyes depuis cette
zone.On a assign la zone locale le sous-rseau 192.168.201.0/29
(masque de sous-rseau 255.255.255.248).Dans ce cas, les systmes de la zone locale seraient
configurs avec 192.168.201.1 comme passerelle par dfaut (adresse
IP de l'interface local du firewall).La SNAT est configure dans Shorewall avec le fichier
/etc/shorewall/masq.#INTERFACE SUBNET ADDRESS
eth0 192.168.201.0/29 192.0.2.176Cet exemple utilise la technique normale qui assigne la mme
adresse publique IP pour l'interface externe du firewall et pour la
SNAT. Si vous souhaitez utiliser une adresse IP diffrente, vous
pouvez soit utiliser les outils de configuration rseau de votre
distribution Linux pour ajouter cette adresse IP, soit mettre la
variable ADD_SNAT_ALIASES=Yes dans
/etc/shorewall/shorewall.conf et Shorewall
ajoutera l'adresse pour vous.DNATQuand la SNAT est utilise, il est impossible pour les htes sur
internet d'initialiser une connexion avec un des systmes internes
puisque ces systmes n'ont pas d'adresses publiques IP. La DNAT
fournit une mthode pour autoriser des connexions slectionnes depuis
internet.Supposons que votre fille souhaite hberger un serveur Web sur
son systme "Local 3". Vous pourriez autoriser les connexions
d'internet son serveur en ajoutant l'entre suivante dans le fichier
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DEST SOURCE ORIGINAL
# PORT(S) PORT(S) DEST
DNAT net loc:192.168.201.4 tcp wwwSi une des amies de votre fille avec une adresse A veut accder au serveur de votre fille, elle
peut se connecter http://192.0.2.176 (l'adresse IP externe de votre
firewall). Le firewall rcrira l'adresse IP de destination
192.168.201.4 (le systme de votre fille) et lui fera suivre la
requte. Quand le serveur de votre fille rpondra, le firewall
remettra l'adresse source 192.0.2.176 et retournera la rponse
A.Cet exemple utilise l'adresse externe IP du firewall pour la
DNAT. Vous pouvez utiliser une autre de vos
adresses IP publiques. Pour cela, mettez-la dans la colonne ORIGINAL
DEST de la rgle ci-dessus. Par contre, Shorewall n'ajoutera pas
votre place cette adresse l'interface externe du firewall.Quand vous testez des rgles DNAT comme
celles prsente plus haut, vous devez le faire depuis un client A
L'EXTRIEUR DE VOTRE FIREWALL (depuis la zone net).
Vous ne pouvez pas tester ces rgles de l'intrieur !Pour quelques astuces sur la rsolution de problmes avec la
DNAT, voyez les FAQ 1a et
1b.Proxy ARPLe principe du proxy ARP est:On attribue un hte H
derrire notre firewall une de nos adresses publiques A et on lui donne le mme masque de
sous-rseau M que celui de
l'interface externe du firewall.Le firewall rpond aux requtes ARP
qui-a-l'adresseAmises par les htes
l'extrieur du firewall.Lorsque c'est l'hte H qui
met une requte qui-a-l'adressepour un hte
situ l'extrieur du firewall et
appartenant au sous-rseau dfini par A et M,
c'est le firewall qui rpondra H avec l'adresse MAC de l'interface du
firewall laquelle est raccord H.Pour une description plus complte du fonctionnement du Proxy
ARP, vous pouvez vous rfrer la Documentation du Proxy Shorewall.Supposons que nous dcidions d'utiliser le Proxy ARP sur la DMZ
de notre exemple de rseau.Ici, nous avons assign les adresses IP 192.0.2.177 au systme
DMZ 1 et 192.0.2.178 au systme DMZ 2. Remarquez que nous avons
assign une adresse RFC 1918 et un masque de sous-rseau arbitraires
l'interface DMZ de notre firewall. Cette adresse et ce masque ne sont
pas pertinents - vrifiez juste que celle-ci n'est en conflit avec
aucun autre sous-rseau dj dfini.La configuration du Proxy ARP est faite dans le fichier /etc/shorewall/proxyarp.#ADDRESS INTERFACE EXTERNAL HAVE ROUTE PERSISTANT
192.0.2.177 eth2 eth0 No
192.0.2.178 eth2 eth0 NoLa variable HAVE ROUTE tant No, Shorewall ajoutera les routes
d'hte pour 192.0.2.177 et 192.0.2.178 par eth2. Les interfaces ethernet des
machines DMZ 1 et DMZ 2 devront tre configures avec les adresses IP
donnes plus haut, mais elles devront avoir la mme passerelle par
dfaut que le firewall lui-mme (192.0.2.254 dans notre exemple).
Autrement dit, elles doivent tre configures exactement comme si
elles taient parallles au firewall plutt que derrire lui.Ne pas ajouter le(s) adresse(s) traites
par le proxy ARP (192.0.2.177 et 192.0.2.178 dans l'exemple
ci-dessus) l'interface externe du firewall (eth0 dans cet
exemple).Un mot de mise en garde. En gnral, les FAI
configurent leurs routeurs avec un timeout de cache
ARP assez lev. Si vous dplacez un systme
parallle votre firewall derrire le Proxy ARP du firewall, cela
peut mettre des HEURES avant que ce systme ne puisse communiquer avec
internet. Il y a deux choses que vous pouvez essayer de faire:(Salutations Bradey Honsinger) Une lecture de
TCP/IP Illustrated, Vol 1 de Richard Stevens rvle
qu'un paquet ARP gratuit (gratuitous) peut amener
le routeur de votre FAI rafrachir son cache (section 4.7). Un
paquet ARP gratuit est simplement une requte d'un
hte demandant l'adresse MAC associe sa propre adresse
IP.En plus de garantir que cette adresse IP n'est pas
duplique, si l'hte qui envoie la commande ARP
gratuit vient juste de changer son adresse
matrielle ..., ce paquet force tous les autres htes...qui ont
une entre dans leur cache ARP pour l'ancienne adresse matrielle
mettre leurs caches jourCe qui est exactement, bien sr, ce que vous souhaitez faire
lorsque vous basculez un hte qui tait directement expos sur
internet vers l'arrire de votre firewall Shorewall en utilisant
le proxy ARP (ou en faisant du NAT un--un pour la mme raison).
Heureusement, les versions rcentes du paquetage
iputils de Redhat
comprennent arping, dont l'option "-U" fait
cela:arping -U -I <net if> <newly proxied IP>
arping -U -I eth0 66.58.99.83 # for exampleStevens
continue en mentionnant que certains systmes ne rpondent pas
correctement la commande ARP gratuit, mais une
recherche sur google pour arping -U semble
dmontrer que cela fonctionne dans la plupart des cas.Vous pouvez appeler votre FAI et lui
demander de purger l'entre obsolte de son cache
ARP, mais la plupart ne voudront ou ne pourront
le faire.Vous pouvez vrifier si le cache ARP de votre FAI est obsolte
en utilisant ping et tcpdump.
Supposez que vous pensez que la passerelle routeur a une entre ARP
obsolte pour 192.0.2.177. Sur le firewall, lancez
tcpdump de cette faon:tcpdump -nei eth0 icmpMaintenant depuis 192.0.2.177, pingez la
passerelle de votre FAI (que nous supposons tre 192.0.2.254):ping 192.0.2.254Nous pouvons maintenant observer le rsultat de
tcpdump:13:35:12.159321 0:4:e2:20:20:33 0:0:77:95:dd:19 ip 98:
192.0.2.177 > 192.0.2.254: icmp: echo request (DF)
13:35:12.207615 0:0:77:95:dd:19 0:c0:a8:50:b2:57 ip 98:
192.0.2.254 > 192.0.2.177 : icmp: echo replyRemarquez
que l'adresse source MAC dans la requte echo est
diffrente de l'adresse MAC de destination dans la
rponse echo ! Dans ce cas, 0:4:e2:20:20:33 tait l'adresse
MAC de l'interface rseau eth0 du firewall tandis que
0:c0:a8:50:b2:57 tait l'adresse MAC de la carte
rseau de DMZ 1. En d'autre termes, le cache ARP de
la passerelle associe encore 192.0.2.177 avec la carte rseau de DMZ 1
plutt qu'avec l'interface eth0 du firewall.NAT un--unAvec le NAT un--un (one-to-one NAT), vous attribuez des
adresses RFC 1918 vos systmes puis vous tablissez une
correspondance un pour un de ces adresses avec les adresses IP
publiques. Pour les occurrences des connexions sortantes, la
traduction d'adresses sources (SNAT) sera alors
effectue. Pour les occurrences des connexions entrantes, c'est la
traduction d'adresses destination (DNAT) qui sera
ralise.Voyons avec l'exemple prcdent du serveur web de votre fille
tournant sur le systme Local 3.Souvenons-nous que dans cette configuration, le rseau local
utilise la SNAT et qu'il partage l'IP externe du
firewall (192.0.2.176) pour les connexions sortantes. On obtient ce
rsultat grce l'entre suivante dans le fichier
/etc/shorewall/masq:#INTERFACE SUBNET ADDRESS
eth0 192.168.201.0/29 192.0.2.176Supposons maintenant que vous ayez dcid d'allouer votre
fille sa propre adresse IP (192.0.2.179) pour l'ensemble des
connexions entrantes et sortantes. Vous pouvez faire cela en ajoutant
cette entre dans le fichier
/etc/shorewall/nat.#EXTERNAL INTERFACE INTERNAL ALL INTERFACES LOCAL
192.0.2.179 eth0 192.168.201.4 No NoAvec cette entre active, votre fille a sa propre adresse IP et
les deux autres systmes locaux partagent l'adresse IP du
firewall.Une fois que la relation entre 192.0.2.179 et192.168.201.4 est
tablie avec l'entre ci-dessus dans le fichier
nat, l'utilisation d'une rgle d'une rgle DNAT
pour le serveur Web de votre fille n'est plus approprie -- vous
devriez plutt utiliser une simple rgle ACCEPT:#ACTION SOURCE DEST PROTO DEST SOURCE ORIGINAL
# PORT(S) PORT(S) DEST
ACCEPT net loc:192.168.201.4 tcp wwwUn mot de mise en garde. En gnral, les FAI
configurent leurs routeurs avec un timeout de cache
ARP assez lev. Si vous dplacez un systme
parallle votre firewall derrire le Proxy ARP du firewall, cela
peut mettre des HEURES avant que ce systme ne puisse communiquer avec
internet. Il y a deux choses que vous pouvez essayer de faire:(Salutations Bradey Honsinger) Une lecture de
TCP/IP Illustrated, Vol 1 de Richard Stevens rvle
qu'un paquet ARP gratuit (gratuitous) peut amener
le routeur de votre FAI rafrachir son cache (section 4.7). Un
paquet ARP gratuit est simplement une requte d'un
hte demandant l'adresse MAC associe sa propre adresse
IP.En plus de garantir que cette adresse IP n'est pas
duplique, si l'hte qui envoie la commande ARP
gratuit vient juste de changer son adresse
matrielle ..., ce paquet force tous les autres htes...qui ont
une entre dans leur cache ARP pour l'ancienne adresse matrielle
mettre leurs caches jourCe qui est exactement, bien sr, ce que vous souhaitez faire
lorsque vous basculez un hte qui tait directement expos sur
internet vers l'arrire de votre firewall Shorewall en utilisant
le proxy ARP (ou en faisant du NAT un--un pour la mme raison).
Heureusement, les versions rcentes du paquetage
iputils de Redhat
comprennent arping, dont l'option "-U" fait
cela:arping -U -I <net if> <newly proxied IP>
arping -U -I eth0 66.58.99.83 # for exampleStevens
continue en mentionnant que certains systmes ne rpondent pas
correctement la commande ARP gratuit, mais une
recherche sur google pour arping -U semble
dmontrer que cela fonctionne dans la plupart des cas.Vous pouvez appeler votre FAI et lui
demander de purger l'entre obsolte de son cache
ARP, mais la plupart ne voudront ou ne pourront
le faire.Vous pouvez vrifier si le cache ARP de votre FAI est obsolte
en utilisant ping et tcpdump.
Supposez que vous pensez que la passerelle routeur a une entre ARP
obsolte pour 192.0.2.177. Sur le firewall, lancez
tcpdump de cette faon:tcpdump -nei eth0 icmpMaintenant depuis 192.0.2.177, pingez la
passerelle de votre FAI (que nous supposons tre 192.0.2.254):ping 192.0.2.254Nous pouvons maintenant observer le rsultat de
tcpdump:13:35:12.159321 0:4:e2:20:20:33 0:0:77:95:dd:19 ip 98:
192.0.2.177 > 192.0.2.254: icmp: echo request (DF)
13:35:12.207615 0:0:77:95:dd:19 0:c0:a8:50:b2:57 ip 98:
192.0.2.254 > 192.0.2.177 : icmp: echo replyRemarquez
que l'adresse source MAC dans la requte echo est
diffrente de l'adresse MAC de destination dans la
rponse echo ! Dans ce cas, 0:4:e2:20:20:33 tait l'adresse
MAC de l'interface rseau eth0 du firewall tandis que
0:c0:a8:50:b2:57 tait l'adresse MAC de la carte
rseau de DMZ 1. En d'autre termes, le cache ARP de
la passerelle associe encore 192.0.2.177 avec la carte rseau de DMZ 1
plutt qu'avec l'interface eth0 du firewall.RglesShorewall dispose d'un mcanisme de macros comprenant des macros pour de
nombreuses applications standard. Dans cette section nous
n'utiliserons pas de macro. mais nous dfinirons les rgles
directement.Avec les politiques dfinies plus tt dans ce document, vos
systmes locaux (Local 1-3) peuvent accder n'importe quel serveur sur
internet alors que la DMZ ne peut accder aucun
autre hte, dont le firewall. A l'exception des rgles
NAT qui entranent la traduction d'adresses et
permettent aux requtes de connexion traduites de passer travers le
firewall, la faon d'autoriser des requtes travers votre firewall est
d'utiliser des rgles ACCEPT.Puisque les colonnes SOURCE PORT et ORIG. DEST. ne sont pas
utilises dans cette section, elle ne seront pas affiches.Vous souhaiter certainement autoriser le ping
entre vos zones:#ACTION SOURCE DEST PROTO DEST
# PORT(S)
ACCEPT net dmz icmp echo-request
ACCEPT net loc icmp echo-request
ACCEPT dmz loc icmp echo-request
ACCEPT loc dmz icmp echo-requestSupposons que vous avez des serveurs mail et pop3 actifs sur le
systme DMZ 2, et un serveur Web sur le systme DMZ 1. Les rgles dont
vous avez besoin sont:#ACTION SOURCE DEST PROTO DEST COMMENTS
# PORT(S)
ACCEPT net dmz:192.0.2.178 tcp smtp #Mail from
#Internet
ACCEPT net dmz:192.0.2.178 tcp pop3 #Pop3 from
#Internet
ACCEPT loc dmz:192.0.2.178 tcp smtp #Mail from local
#Network
ACCEPT loc dmz:192.0.2.178 tcp pop3 #Pop3 from local
#Network
ACCEPT $FW dmz:192.0.2.178 tcp smtp #Mail from the
#Firewall
ACCEPT dmz:192.0.2.178 net tcp smtp #Mail to the
#Internet
ACCEPT net dmz:192.0.2.177 tcp http #WWW from
#Internet
ACCEPT net dmz:192.0.2.177 tcp https #Secure WWW
#from Internet
ACCEPT loc dmz:192.0.2.177 tcp https #Secure WWW
#from local
#NetworkSi vous utilisez un serveur DNS public sur 192.0.2.177, vous devez
ajouter les rgles suivantes:#ACTION SOURCE DEST PROTO DEST COMMENTS
# PORT(S)
ACCEPT net dmz:192.0.2.177 udp domain #UDP DNS from
#Internet
ACCEPT net dmz:192.0.2.177 tcp domain #TCP DNS from
#Internet
ACCEPT loc dmz:192.0.2.177 udp domain #UDP DNS from
#Local Network
ACCEPT loc dmz:192.0.2.177 tcp domain #TCP DNS from
#Local Network
ACCEPT $FW dmz:192.0.2.177 udp domain #UDP DNS from
#the Firewall
ACCEPT $FW dmz:192.0.2.177 tcp domain #TCP DNS from
#the Firewall
ACCEPT dmz:192.0.2.177 net udp domain #UDP DNS to
#the Internet
ACCEPT dmz:192.0.2.177 net tcp domain #TCPP DNS to
#the InternetVous souhaiterez probablement communiquer depuis votre rseau
local avec votre firewall et les systmes en DMZ --
Je recommande SSH qui, grce son utilitaire
scp peut aussi faire de la diffusion et de la mise
jour de logiciels.#ACTION SOURCE DEST PROTO DEST COMMENTS
# PORT(S)
ACCEPT loc dmz tcp ssh #SSH to the DMZ
ACCEPT net $FW tcp ssh #SSH to the
#FirewallD'autres petites chosesLa discussion prcdente reflte ma prfrence personnelle pour
l'utilisation d'un Proxy ARP associ mes serveurs en DMZ et de
SNAT/NAT pour les systmes locaux. Je prfre utiliser la NAT seulement
dans le cas ou un systme qui fait partie d'un sous-rseau RFC 1918
besoin d'avoir sa propre adresse IP publique.Si vous ne l'avez dj fait, ce serait une bonne ide de parcourir
le fichier /etc/shorewall/shorewall.conf
juste pour voir si autre chose pourrait vous intresser. Vous pouvez
aussi regarder les autres fichiers de configuration que vous n'avez pas
touchs pour avoir un aperu des autres possibilits de
Shorewall.Dans le cas ou vous auriez perdu le fil, vous trouverez ci-dessous
un jeu final des fichiers de configuration pour le rseau de notre
exemple. Seuls les fichiers de la configuration initiale qui ont t
modifis sont prsents./etc/shorewall/interfaces (Les "options" sont
trs dpendantes des sites).#ZONE INTERFACE BROADCAST OPTIONS
net eth0 detect rfc1918,routefilter
loc eth1 detect
dmz eth2 detectLa configuration dcrite ici ncessite que votre rseau soit
dmarr avant que Shorewall ne puisse se lancer. Ceci laisse un petit
intervalle de temps durant lequel vous n'avez pas la protection d'un
firewall.Si vous remplacez le detect dans les entres
ci-dessus par la valeurs des adresses de diffusion (broadcoast) relles,
vous pouvez activer Shorewall avant de monter vos interfaces
rseau.#ZONE INTERFACE BROADCAST OPTIONS
net eth0 192.0.2.255 rfc1918
loc eth1 192.168.201.7
dmz eth2 192.168.202.7/etc/shorewall/masq - Rseau Local#INTERFACE SUBNET ADDRESS
eth0 192.168.201.0/29 192.0.2.176/etc/shorewall/proxyarp - DMZ#ADDRESS EXTERNAL INTERFACE HAVE ROUTE
192.0.2.177 eth2 eth0 No
192.0.2.178 eth2 eth0 No/etc/shorewall/nat- Le systme de ma
fille#EXTERNAL INTERFACE INTERNAL ALL INTERFACES LOCAL
192.0.2.179 eth0 192.168.201.4 No No/etc/shorewall/rules#ACTION SOURCE DEST PROTO DEST COMMENTS
# PORT(S)
ACCEPT net dmz icmp echo-request
ACCEPT net loc icmp echo-request
ACCEPT dmz loc icmp echo-request
ACCEPT loc dmz icmp echo-request
ACCEPT net loc:192.168.201.4 tcp www #Daughter's
#Server
ACCEPT net dmz:192.0.2.178 tcp smtp #Mail from
#Internet
ACCEPT net dmz:192.0.2.178 tcp pop3 #Pop3 from
#Internet
ACCEPT loc dmz:192.0.2.178 tcp smtp #Mail from local
#Network
ACCEPT loc dmz:192.0.2.178 tcp pop3 #Pop3 from local
#Network
ACCEPT $FW dmz:192.0.2.178 tcp smtp #Mail from the
#Firewall
ACCEPT dmz:192.0.2.178 net tcp smtp #Mail to the
#Internet
ACCEPT net dmz:192.0.2.177 tcp http #WWW from
#Internet
ACCEPT net dmz:192.0.2.177 tcp https #Secure WWW
#from Internet
ACCEPT loc dmz:192.0.2.177 tcp https #Secure WWW
#from local
#Network
ACCEPT net dmz:192.0.2.177 udp domain #UDP DNS from
#Internet
ACCEPT net dmz:192.0.2.177 tcp domain #TCP DNS from
#Internet
ACCEPT loc dmz:192.0.2.177 udp domain #UDP DNS from
#Local Network
ACCEPT loc dmz:192.0.2.177 tcp domain #TCP DNS from
#Local Network
ACCEPT $FW dmz:192.0.2.177 udp domain #UDP DNS from
#the Firewall
ACCEPT $FW dmz:192.0.2.177 tcp domain #TCP DNS from
#the Firewall
ACCEPT dmz:192.0.2.177 net udp domain #UDP DNS to
#the Internet
ACCEPT dmz:192.0.2.177 net tcp domain #TCPP DNS to
#the Internet
ACCEPT loc dmz tcp ssh #SSH to the DMZ
ACCEPT net $FW tcp ssh #SSH to the
#FirewallDNSCompte tenu des adresses RFC 1918 et des adresses publiques
utilises dans cette configuration, la seule faon logique de faire est
d'avoir des serveurs DNS interne et externe spars.
Vous pouvez combiner les deux dans un unique serveur BIND 9 utilisant les
vues (Views). Si vous n'tes pas intress par les vues BIND 9, vous
pouvez allez la section suivante.Supposons que votre domaine est foobar.net. Vous voulez que les deux
systmes en DMZ s'appellent www.foobar.net et
mail.foobar.net, et vous voulez que les trois systmes locaux s'appellent
winken.foobar.net, blinken.foobar.net et nod.foobar.net. Vous voulez que
le firewall soit connu l'extrieur sous le nom de firewall.foobar.net,
que son interface vers le rseau local soit nomme gateway.foobar.net et
que son interface vers la DMZ soit dmz.foobar.net.
Mettons le serveur DNS sur 192.0.2.177 qui sera aussi connu sous le nom de
ns1.foobar.net.Le fichier /etc/named.conf devrait ressembler
cela:
options {
directory "/var/named";
listen-on { 127.0.0.1 ; 192.0.2.177; };
transfer-format many-answers;
max-transfer-time-in 60;
allow-transfer {
// Servers allowed to request zone tranfers
<secondary NS IP>; };
};
logging {
channel xfer-log {
file "/var/log/named/bind-xfer.log";
print-category yes;
print-severity yes;
print-time yes;
severity info;
};
category xfer-in { xfer-log; };
category xfer-out { xfer-log; };
category notify { xfer-log; };
};
#
# This is the view presented to our internal systems
#
view "internal" {
#
# These are the clients that see this view
#
match-clients { 192.168.201.0/29;
192.168.202.0/29;
127.0.0.0/8;
192.0.2.176/32;
192.0.2.178/32;
192.0.2.179/32;
192.0.2.180/32; };
#
# If this server can't complete the request, it should use
# outside servers to do so
#
recursion yes;
zone "." in {
type hint;
file "int/root.cache";
};
zone "foobar.net" in {
type master;
notify no;
allow-update { none; };
file "int/db.foobar";
};
zone "0.0.127.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "int/db.127.0.0";
};
zone "201.168.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "int/db.192.168.201";
};
zone "202.168.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "int/db.192.168.202";
};
zone "176.2.0.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "db.192.0.2.176";
};
zone "177.2.0.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "db.192.0.2.177";
};
zone "178.2.0.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "db.192.0.2.178";
};
zone "179.2.0.192.in-addr.arpa" in {
type master;
notify no;
allow-update { none; };
file "db.206.124.146.179";
};
};
#
# This is the view that we present to the outside world
#
view "external" {
match-clients { any; };
#
# If we can't answer the query, we tell the client so
#
recursion no;
zone "foobar.net" in {
type master;
notify yes;
allow-update {none; };
file "ext/db.foobar";
};
zone "176.2.0.192.in-addr.arpa" in {
type master;
notify yes;
allow-update { none; };
file "db.192.0.2.176";
};
zone "177.2.0.192.in-addr.arpa" in {
type master;
notify yes;
allow-update { none; };
file "db.192.0.2.177";
};
zone "178.2.0.192.in-addr.arpa" in {
type master;
notify yes;
allow-update { none; };
file "db.192.0.2.178";
};
zone "179.2.0.192.in-addr.arpa" in {
type master;
notify yes;
allow-update { none; };
file "db.192.0.2.179";
};
};Voici les fichiers du rpertoire /var/named (ceux qui ne sont pas prsents
font en gnral partie de votre distribution BIND).db.192.0.2.176 - Zone inverse (reverse) pour
l'interface externe du firewall; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.0.2.176/32
; Filename: db.192.0.2.176
; ############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2001102303 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
;
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
@ 604800 IN NS <name of secondary ns>.
;
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
176.2.0.192.in-addr.arpa. 86400 IN PTR firewall.foobar.net.db.192.0.2.177 - Zone inverse pour le serveur
www; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.0.2.177/32
; Filename: db.192.0.2.177
; ############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2001102303 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
;
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
@ 604800 IN NS <name of secondary ns>.
;
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
177.2.0.192.in-addr.arpa. 86400 IN PTR www.foobar.net.db.192.0.2.178 - Zone inverse du serveur
mail; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.0.2.178/32
; Filename: db.192.0.2.178
; ############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2001102303 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
;
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
@ 604800 IN NS <name of secondary ns>.
;
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
178.2.0.192.in-addr.arpa. 86400 IN PTR mail.foobar.net.db.192.0.2.179 - Zone inverse du serveur web
public de votre fille; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.0.2.179/32
; Filename: db.192.0.2.179
; ############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2001102303 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
;
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
@ 604800 IN NS <name of secondary ns>.
;
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
179.2.0.192.in-addr.arpa. 86400 IN PTR nod.foobar.net.int/db.127.0.0 - Zone inverse pour
localhost; ############################################################
; Start of Authority (Inverse Address Arpa) for 127.0.0.0/8
; Filename: db.127.0.0
; ############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2001092901 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
1 86400 IN PTR localhost.foobar.net.int/db.192.168.201 - Zone inverse pour le
rseau local. Cela ne sera visible que depuis les clients internes; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.168.201.0/29
; Filename: db.192.168.201
; ############################################################
@ 604800 IN SOA ns1.foobar.net netadmin.foobar.net. (
2002032501 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
1 86400 IN PTR gateway.foobar.net.
2 86400 IN PTR winken.foobar.net.
3 86400 IN PTR blinken.foobar.net.
4 86400 IN PTR nod.foobar.net.int/db.192.168.202 - Zone inverse de
l'interface DMZ du firewall; ############################################################
; Start of Authority (Inverse Address Arpa) for 192.168.202.0/29
; Filename: db.192.168.202
; ############################################################
@ 604800 IN SOA ns1.foobar.net netadmin.foobar.net. (
2002032501 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ) ; minimum (1 day)
; ############################################################
; Specify Name Servers for all Reverse Lookups (IN-ADDR.ARPA)
; ############################################################
@ 604800 IN NS ns1.foobar.net.
; ############################################################
; Iverse Address Arpa Records (PTR's)
; ############################################################
1 86400 IN PTR dmz.foobar.net.int/db.foobar - Forward zone pour les clients
internes.;##############################################################
; Start of Authority for foobar.net.
; Filename: db.foobar
;##############################################################
@ 604800 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2002071501 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ); minimum (1 day)
;############################################################
; foobar.net Nameserver Records (NS)
;############################################################
@ 604800 IN NS ns1.foobar.net.
;############################################################
; Foobar.net Office Records (ADDRESS)
;############################################################
localhost 86400 IN A 127.0.0.1
firewall 86400 IN A 192.0.2.176
www 86400 IN A 192.0.2.177
ns1 86400 IN A 192.0.2.177
mail 86400 IN A 192.0.2.178
gateway 86400 IN A 192.168.201.1
winken 86400 IN A 192.168.201.2
blinken 86400 IN A 192.168.201.3
nod 86400 IN A 192.168.201.4
dmz 86400 IN A 192.168.202.1ext/db.foobar - Forward zone pour les clients
externes;##############################################################
; Start of Authority for foobar.net.
; Filename: db.foobar
;##############################################################
@ 86400 IN SOA ns1.foobar.net. netadmin.foobar.net. (
2002052901 ; serial
10800 ; refresh (3 hour)
3600 ; retry (1 hour)
604800 ; expire (7 days)
86400 ); minimum (1 day)
;############################################################
; Foobar.net Nameserver Records (NS)
;############################################################
@ 86400 IN NS ns1.foobar.net.
@ 86400 IN NS <secondary NS>.
;############################################################
; Foobar.net Foobar Wa Office Records (ADDRESS)
;############################################################
localhost 86400 IN A 127.0.0.1
;
; The firewall itself
;
firewall 86400 IN A 192.0.2.176
;
; The DMZ
;
ns1 86400 IN A 192.0.2.177
www 86400 IN A 192.0.2.177
mail 86400 IN A 192.0.2.178
;
; The Local Network
;
nod 86400 IN A 192.0.2.179
;############################################################
; Current Aliases for foobar.net (CNAME)
;############################################################
;############################################################
; foobar.net MX Records (MAIL EXCHANGER)
;############################################################
foobar.net. 86400 IN A 192.0.2.177
86400 IN MX 0 mail.foobar.net.
86400 IN MX 1 <backup MX>.Quelques Points Garder en MmoireVous ne pouvez pas tester votre firewall
depuis l'intrieur de votre rseau. Envoyer des requtes
l'adresse IP externe de votre firewall ne signifie pas qu'elle seront
associes votre interface externe ou la zone net.
Tout trafic gnr par le rseau local sera associ l'interface
locale et sera trait comme du trafic du rseau local ver le firewall
(loc->fw).Les adresses IP sont des proprits des
systmes, pas des interfaces. C'est une erreur de croire
que votre firewall est capable de faire suivre
(forward) des paquets simplement parce que vous
pouvez faire un ping sur l'adresse IP de toutes les
interfaces du firewall depuis le rseau local. La seule conclusion que
vous puissiez faire dans ce cas est que le lien entre le rseau local
et le firewall fonctionne et que vous avez probablement la bonne
adresse de passerelle par dfaut sur votre systme.Toutes les adresses IP configures sur le
firewall sont dans la zone $FW (fw). Si 192.168.1.254 est
l'adresse IP de votre interface interne, alors vous pouvez crire
$FW:192.168.1.254 dans
une rgle mais vous ne devez pas crire loc:192.168.1.254. C'est aussi une
absurdit d'ajouter 192.168.1.254 la zone loc en utilisant une entre dans
/etc/shorewall/hosts.Les paquets de retour (reply) ne suivent
PAS automatiquement le chemin inverse de la requte
d'origine. Tous les paquets sont routs en se rfrant la
table de routage respective de chaque hte chaque tape du trajet.
Ce problme se produit en gnral lorsque on installe un firewall
Shorewall en parallle une passerelle existante et qu'on essaye
d'utiliser des rgles DNAT dans Shorewall sans
changer la passerelle par dfaut sur les systmes recevant les
requtes transfres (forwarded). Les requtes passent dans le
firewall Shorewall o l'adresse de destination IP est rcrite, mais
la rponse revient par l'ancienne passerelle qui, elle, ne modifiera
pas le paquet.Shorewall lui-mme n'a aucune notion du
dedans et du dehors. Ces concepts dpendent de la faon
dont Shorewall est configur.Dmarrer et Arrter Votre FirewallLa procdure d'installation
configure votre systme pour lancer Shorewall ds le boot du systme, mais
le lancement est dsactiv, de faon ce que votre systme ne tente pas
de lancer Shorewall avant que la configuration ne soit termine. Une fois
que vous en avez fini avec la configuration du firewall, vous devez diter
/etc/shorewall/shorewall.conf et y mettre STARTUP_ENABLED=Yes.Les utilisateurs des paquetages .deb doivent diter /etc/default/shorewall
et mettre startup=1.Le firewall est activ en utilisant la commande
shorewall start et arrt avec la
commande shorewall stop. Lorsque le
firewall est arrt, le routage est autoris sur les htes qui possdent
une entre dans /etc/shorewall/routestopped.
Un firewall qui tourne peut tre relanc en utilisant la commande
shorewall restart. Si vous voulez
enlever toute trace de Shorewall sur votre configuration de Netfilter,
utilisez shorewall
clearModifiez /etc/shorewall/routestopped pour
y configurer les htes auxquels vous voulez accder lorsque le firewall
est arrt. Si vous tes connect votre firewall depuis internet,
n'essayez pas d'excuter une commande shorewall
stop tant que vous n'avez pas ajout une entre dans
/etc/shorewall/routestopped
pour l'adresse IP partir de laquelle vous tes connect . De la mme
manire, je vous dconseille d'utiliser shorewall
restart; il est plus intressant de crer une configuration
alternative et de la tester en utilisant la commande
shorewall
try