shorewall-docs-xml-5.2.3/ 0000775 0000000 0000000 00000000000 13430376104 013746 5 ustar root root shorewall-docs-xml-5.2.3/FoolsFirewall.xml 0000664 0000000 0000000 00000006471 13427347317 017262 0 ustar root root
The Fool's FirewallTomEastep2009Thomas 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.DefinitionOccasionally, we hear from someone who has cabled his firewall's
external and internal firewall interfaces to the same unmanaged switch (or
mis-configured managed switch). I call this configuration The
Fool's Firewall.When the external interface supports broadcast, this configuration
has two very bad drawbacks:It is very insecureBoth the up-stream router and the local systems can send
incoming packets to the wrong interface.Security IssueBecause Fool's firewall is not physically located between the net
and the local systems, the local systems are exposed to all of the systems
in the same broadcast domain. Because the local systems (especially those
running Windows) send broadcasts, those systems can be easily detected by
using a packet sniffer. Once the systems have been spotted, it is child's
play to add an IP address in Fool's internal IP network and bypass his
"Firewall".ARP RouletteThe Linux IP stack implements the weak host model. As
a result, it exhibits some unexpected behavior with respect to ARP. It
will respond to ARP 'who-has' requests received on
any interface and not just on the interface owning
the address. So when the upstream router sends a 'who-has' request for
Fool's external IP address, the response may come from his
internal interface (and reflect the MAC address of
that interface). When that happens, packets from the net start entering
the firewall's internal interface.A similar problem can occur when a local system sends to the
"Firewall" or to the Net. The packets may arrive on the firewall through
the external interface.
shorewall-docs-xml-5.2.3/configuration_file_basics.xml 0000664 0000000 0000000 00000363616 13427347317 021713 0 ustar root root
Configuration Files Tips and HintsTomEastep2001-2019Thomas 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 5.0 and
later. If you are running a version of Shorewall earlier than Shorewall
5.0.0 then please see the documentation for that
release.If you copy or edit your configuration files on a system running
Microsoft Windows, you must run them through dos2unix
before you use them with Shorewall.IntroductionThis article offers hints about how to accomplish common tasks with
Shorewall. The Introduction to
Shorewall is required reading for being able to use this article
effectively. For information about setting up your first Shorewall-based
firewall, see the Quickstart
Guides.inFiles/etc/shorewall/shorewall.conf - used to
set global firewall parameters./etc/shorewall/params - use this file to
set shell variables that you will expand in other files. It is
always processed by /bin/sh or by the shell specified through
SHOREWALL_SHELL in
/etc/shorewall/shorewall.conf./etc/shorewall/zones - partition the
firewall's view of the world into zones./etc/shorewall/policy - establishes
firewall high-level policy./etc/shorewall/initdone - An optional
Perl script that will be invoked by the Shorewall rules compiler
when the compiler has finished it's initialization./etc/shorewall/interfaces - describes the
interfaces on the firewall system./etc/shorewall/hosts - allows defining
zones in terms of individual hosts and subnetworks./etc/shorewall/masq - directs the
firewall where to use many-to-one (dynamic) Network Address
Translation (a.k.a. Masquerading) and Source Network Address
Translation (SNAT)./etc/shorewall/mangle - supersedes
/etc/shorewall/tcrules in Shorewall 4.6.0.
Contains rules for packet marking, TTL, TPROXY, etc./etc/shorewall/rules - defines rules that
are exceptions to the overall policies established in
/etc/shorewall/policy./etc/shorewall/nat - defines one-to-one
NAT rules./etc/shorewall/proxyarp - defines use of
Proxy ARP./etc/shorewall/routestopped - defines
hosts accessible when Shorewall is stopped. Superseded in Shorewall
4.6.8 by /etc/shorewall/stoppedrules. Not
supported in Shorewall 5.0.0 and later versions./etc/shorewall/tcrules - The file has a
rather unfortunate name because it is used to define marking of
packets for later use by both traffic control/shaping and policy
routing. This file is superseded by
/etc/shorewall/mangle in Shorewall 4.6.0. Not
supported in Shorewall 5.0.0 and later releases./etc/shorewall/tos - defines rules for
setting the TOS field in packet headers. Superseded in Shorewall
4.5.1 by the TOS target in
/etc/shorewall/tcrules (which file has since
been superseded by /etc/shorewall/mangle). Not
supported in Shorewall 5.0.0 and later versions./etc/shorewall/tunnels - defines tunnels
(VPN) with end-points on the firewall system./etc/shorewall/blacklist - Deprecated in
favor of /etc/shorewall/blrules. Lists
blacklisted IP/subnet/MAC addresses. Not supported in Shorewall
5.0.0 and later releases./etc/shorewall/blrules — Added in
Shorewall 4.5.0. Define blacklisting and whitelisting./etc/shorewall/init - commands that you
wish to execute at the beginning of a shorewall
start, "shorewall reload" or shorewall
restart./etc/shorewall/start - commands that you
wish to execute near the completion of a shorewall
start, "shorewall reload" or shorewall
restart/etc/shorewall/started - commands that
you wish to execute after the completion of a shorewall
start, "shorewall reload" or shorewall
restart/etc/shorewall/stop - commands that you
wish to execute at the beginning of a shorewall
stop./etc/shorewall/stopped - commands that
you wish to execute at the completion of a shorewall
stop./etc/shorewall/ecn - disable Explicit
Congestion Notification (ECN - RFC 3168) to remote hosts or
networks./etc/shorewall/accounting - define IP
traffic accounting rules/etc/shorewall/actions and
/usr/share/shorewall/action.template allow
user-defined actions./etc/shorewall/providers - defines an
alternate routing table./etc/shorewall/rtrules - Defines routing
rules to be used in conjunction with the routing tables defined in
/etc/shorewall/providers./etc/shorewall/tcdevices,
/etc/shorewall/tcclasses,
/etc/shorewall/tcfilters - Define complex
traffic shaping./etc/shorewall/tcrules - Mark or classify
traffic for traffic shaping or multiple providers. Deprecated in
Shorewall 4.6.0 in favor of
/etc/shorewall/mangle. Not supported in
Shorewall 5.0.0 and later releases./etc/shorewall/tcinterfaces and
/etc/shorewall-tcpri - Define simple traffic
shaping./etc/shorewall/secmarks - Added in
Shorewall 4.4.13. Attach an SELinux context to selected
packets./etc/shorewall/vardir - Determines the
directory where Shorewall maintains its state./usr/share/shorewall/actions.std -
Actions defined by Shorewall./usr/share/shorewall/action.* - Details
of actions defined by Shorewall./usr/share/shorewall/macro.* - Details of
macros defined by Shorewall./usr/share/shorewall/modules — Specifies
the kernel modules to be loaded during shorewall start/restart
(removed in Shorewall 5.2.3)./usr/share/helpers — Added in Shorewall
4.4.7. Specifies the kernel modules to be loaded during shorewall
start/restart when LOAD_HELPERS_ONLY=Yes in
shorewall.conf./usr/share/arprules — Added in Shorewall
4.5.12. Allows specification of arptables rules./etc/shorewall/mangle -- Added in
Shorewall 4.6.0. Supersedes
/etc/shorewall/tcrules.If you need to change a file in
/usr/share/shorewall/, copy it to /etc/shorewall and
modify the copyMan PagesMan pages are provided in section 5 for each of the Shorewall
configuration files. The name of the page is formed by prefixing the file
name with "shorewall-".Example — To view the manual page for
/etc/shorewall/interfaces:man shorewall-interfacesThe /etc/shorewall/shorewall.conf file is an exception -- the man
page for that file is 'shorewall.conf':man shorewall.confCommentsYou may place comments in configuration files by making the first
non-whitespace character a pound sign (#). You may also
place comments at the end of any line, again by delimiting the comment
from the rest of the line with a pound sign.Comments in a Configuration File# This is a comment
ACCEPT net $FW tcp www #This is an end-of-line commentIf a comment ends with a backslash ("\"), the next line will also
be treated as a comment. See Line
Continuation below.NamesWhen you define an object in Shorewall (Zone, Logical Interface, ipsets, Actions, etc., you give it a name. Shorewall
names start with a letter and consist of letters, digits or underscores
("_"). Except for Zone names, Shorewall does not impose a limit on name
length.When an ipset is referenced, the name must be preceded by a plus
sign ("+").The last character of an interface may also be a plus sign to
indicate a wildcard name.Physical interface names match names shown by 'ip link ls'; if the
name includes an at sign ("@"), do not include that character or any
character that follows. For example, "sit1@NONE" is referred to as simply
'sit1".Zone and Chain NamesFor a pair of zones, Shorewall creates two Netfilter chains; one for
connections in each direction. The names of these chains are formed by
separating the names of the two zones by either "2" or "-".Example: Traffic from zone A to zone B would go through chain A2B
(think "A to B") or "A-B".In Shorewall 4.6, the default separator is "-" but you can override
that by setting ZONE_SEPARATOR="2" in shorewall.conf (5).Prior to Shorewall 4.6, the default separator was "2".Zones themselves have names that begin with a letter and are
composed of letters, numerals, and "_". The maximum length of a name is
dependent on the setting of LOGFORMAT in shorewall.conf (5). See shorewall-zones (5) for
details.CapabilitiesShorewall probes your system to determine the features that it
supports. The result of this probing is a set of
capabilities. This probing is normally done each
time that the compiler is run but can also be done by executing the
shorewall show capabilities command. Regardless of
whether the compiler or the command does the probing, this probing may
produce error messages in your system log. These log messages are to be
expected and do not represent a problem; they merely indicate that
capabilities that are being probed are not supported on your
system.Probing may be suppressed by using a capabilities
file. A capabilities file may be generated using this
command:shorewall show -f capabilities > /etc/shorewall/capabilitiesIf you use a capabilities file, be sure to regenerate it after you
have performed a Shorewall upgrade to ensure that all current
capabilities have been recorded in your file."Blank" ColumnsIf you don't want to supply a value in a column but want to supply a
value in a following column, simply enter '-' to make the column appear
empty.Example:#INTERFACE BROADCAST OPTIONS
br0 - routebackLine ContinuationYou may continue lines in the configuration files using the usual
backslash (\) followed immediately by a new line character
(Enter key).ACCEPT net $FW tcp \↵
smtp,www,pop3,imap #Services running on the firewallIn certain cases, leading white space is ignored in continuation
lines:The continued line ends with a colon (":")The continued line ends with a comma (",")What follows does NOT apply to shorewall-params(5) and
shorewall.conf(5).Example (/etc/shorewall/rules):#ACTION SOURCE DEST PROTO DPORT
ACCEPT net:\
206.124.146.177,\
206.124.146.178,\
206.124.146.180\
dmz tcp 873The leading white space on the first through third continuation
lines is ignored so the SOURCE column effectively contains
"net:206.124.146.177,206.124.147.178,206.124.146.180". Because the third
continuation line does not end with a comma or colon, the leading white
space in the last line is not ignored.A trailing backslash is not ignored in a comment. So the continued
rule above can be commented out with a single '#' as follows:#ACTION SOURCE DEST PROTO DPORT
#ACCEPT net:\
206.124.146.177,\
206.124.146.178,\
206.124.146.180\
dmz tcp 873Alternate Specification of Column Values - Shorewall 4.4.24 and
LaterSome of the configuration files now have a large number of columns.
That makes it awkward to specify a value for one of the right-most columns
as you must have the correct number of intervening '-' columns.This problem is addressed by allowing column values to be specified
as column-name/value
pairs.There is considerable flexibility in how you specify the
pairs:At any point, you can enter a left curly bracket ('{') followed
by one or more specifications of the following forms:column-name=valuecolumn-name=>valuecolumn-name:valueThe pairs must be followed by a right curly bracket
("}").The value may optionally be enclosed in double quotes.The pairs must be separated by white space, but you can add a
comma adjacent to the values for
readability as in:{ proto=>udp, port=1024
}You can also separate the pairs from columns by using a
semicolon:; proto:udp,
port:1024This form is incompatible with INLINE_MATCHES=Yes. See the
INLINE_MATCHES option in shorewall.conf(5).In Shorewall 5.0.3, the sample configuration files and the man pages
were updated to use the same column names in both the column headings and
in the alternate specification format. The following table shows the
column names for each of the table-oriented configuration files.Column names are case-insensitive.FileColumn namesaccountingaction,chain, source, dest, proto, dport, sport, user,
mark, ipsec, headersconntrackaction,source,dest,proto,dport,sport,user,switchblacklistnetworks,proto,port,optionsblrulesaction,source,dest,proto,dport,sport,origdest,rate,user,mark,connlimit,time,headers,switch,helperecninterface,hosts. Beginning with Shorewall 4.5.4, 'host' is
a synonym for 'hosts'.hostszone,hosts,options. Beginning with Shorewall 4.5.4, 'host'
is a synonym for 'hosts'.interfaceszone,interface,broadcast,optionsmaclistdisposition,interface,mac,addressesmangleaction,source,dest,proto,dport,sport,user,test,length,tos,connbytes,helper,headersmasqinterface,source,address,proto,port,ipsec,mark,user,switchnatexternal,interface,internal,allints,localnetmaptype,net1,interface,net2,net3,proto,dport,sportnotracksource,dest,proto,dport,sport,userpolicysource,dest,policy,loglevel,limit,connlimitproviderstable,number,mark,duplicate,interface,gateway,options,copyproxyarp and proxyndpaddress,interface,external,haveroute,persistentrtrulessource,dest,provider,priorityroutesprovider,dest,gateway,deviceroutestoppedinterface,hosts,options,proto,dport,sportrulesaction,source,dest,proto,dport,sport,origdest,rate,user,mark,connlimit,time,headers,switch,helpersecmarkssecmark,chain,source,dest,proto,dport,sport,user,marktcclassesinterface,mark,rate,ceil,prio,optionstcdevicesinterface,in_bandwidth,out_bandwidth,options,redirecttcfiltersclass,source,dest,proto,dport,sport,tos,lengthtcinterfacesinterface,type,in_bandwidth,out_bandwidthtcpriband,proto,port,address,interface,helpertcrulesmark,source,dest,proto,dport,sport,user,test,length,tos,connbytes,helper,headers.
Beginning with Shorewall 4.5.3, 'action' is a synonym for
'mark'.tossource,dest,proto,dport,sport,tos,marktunnelstype,zone,gateway,gateway_zone. Beginning with Shorewall
4.5.3, 'gateways' is a synonym for 'gateway'. Beginning with
Shorewall 4.5.4, 'gateway_zones' is a synonym for
'gateway_zone'.zoneszone,type,options,in_options,out_optionsExample (rules file):#ACTION SOURCE DEST PROTO DPORT
DNAT net loc:10.0.0.1 tcp 80 ; mark="88"Here's the same line in several equivalent formats:{ action=>DNAT, source=>net, dest=>loc:10.0.0.1, proto=>tcp, dport=>80, mark=>88 }
; action:"DNAT" source:"net" dest:"loc:10.0.0.1" proto:"tcp" dport:"80" mark:"88"
DNAT { source=net dest=loc:10.0.0.1 proto=tcp dport=80 mark=88 }Beginning with Shorewall 5.0.11, ip[6]table comments can be attached
to individual rules using the keyword.Example from the rules file: ACCEPT net $FW { proto=tcp, dport=22, comment="Accept \"SSH\"" }As shown in that example, when the comment contains whitespace, it
must be enclosed in double quotes and any embedded double quotes must be
escaped using a backslash ("\").Using Netfilter Features not Directly Supported by
ShorewallShorewall doesn't contain built-in support for all ip[6]tables
targets and matches. Nevertheless, you can still use the unsupported
ip[6]tables features through several Shorewall facilities.INLINEINLINE, added in Shorewall 4. is available in the mangle, snat
(masq) and rules files and allows you to specify ip[6]table text
following two semicolons to the right of the column-oriented
specifications.INLINE takes one optional parameter which, if present, must be
a valid entry for the first column of the file. If the parameter is
omitted, then you can specify the target of the rule in the
text.Examples from the rules file:#ACTION SOURCE DEST
?COMMENT Drop DNS Amplification Attack Packets
INLINE(DROP):info net $FW udp 53 ;; -m u32 --u32 "0>>22&0x3C\@8&0xffff=0x0100 && 0>>22&0x3C\@12&0xffff0000=0x00010000"
?COMMENT
?COMMENT Rule generated by the IfEvent action
INLINE net $FW ;; -m recent --rcheck 10 --hitcount 5 --name SSH -s 1.2.3.4 -j MARK --or-mark 0x4000
?COMMENTIPTABLES and IP6TABLESThese are very similar to INLINE. The difference is that the
parameter to IPTABLES and IP6TABLES is the ip[6]tables target of the
Rule rather than a Shorewall-defined action or target.Example from the mangle file:IPTABLES(MARK --set-mark 0x4):P eth0 1.2.3.4Inline MatchesIn Shorewall 4.6.0 and later, setting INLINE_MATCHES=Yes in
shorewall[6].conf allows you to include ip[6]tables matches
following a semicolon on any rule in the mangle, masq and rules
files. Note that this is incompatible with the Alternate Input form
that uses a semicolon to delimit column-oriented specifications from
column=value specifications. In Shorewall 5.0.0 and later, inline
matches are allowed in mangle, masq and rules following two adjacent
semicolons (";;"). If alternate input is present, the adjacent
semicolons should follow that input. In Shorewall 5.2.2, this
support was extended to the conntrack file.INLINE_MATCHES=Yes is deprecated and is not supported in
Shorewall 5.2 and beyond. Use two adjacent semicolons to introduce
inline matches.Example from the masq file that spits outgoing SNAT between
two public IP addressesCOMB_IF !70.90.191.120/29 70.90.191.121 ;; -m statistic --mode random --probability 0.50
COMB_IF !70.90.191.120/29 70.90.191.123If the first character of the inline matches is a plus sign
("+"), then the matches are processed before the column-oriented
input in the rule. That is required when specifying additional TCP
protocol parameters.Example from action.TCPFlags:DROP - - ;;+ -p 6 --tcp-flags ALL FIN,URG,PSHAddressesIn both Shorewall and Shorewall6, there are two basic types of
addresses:Host AddressThis address type refer to a single host.In IPv4, the format is i.j.k.l where
i through l are decimal
numbers between 1 and 255.In IPv6, the format is a:b:c:d:e:f:g:h
where a through h consist
of 1 to 4 hexidecimal digits (leading zeros may be omitted). a
single series of 0 addresses may be omitted. For example
2001:227:e857:1:0:0:0:0:1 may be written 2001:227:e857:1::1.Network AddressA network address refers to 1 or more hosts and consists of a
host address followed by a slash ("/") and a Variable
Length Subnet Mask (VLSM). This is known as
Classless Internet Domain Routing (CIDR)
notation.The VLSM is a decimal number. For IPv4, it is in the range 0
through 32. For IPv6, the range is 0 through 128. The number
represents the number of leading bits in the address that represent
the network address; the remainder of the bits are a host address
and are generally given as zero.Examples:IPv4: 192.168.1.0/24IPv6: 2001:227:e857:1:0:0:0:0:1/64In the Shorewall documentation and manpages, we have tried to make
it clear which type of address is accepted in each specific case.Because Shorewall uses a colon (":") as a separator in many
contexts, IPv6 addresses are best written using the standard convention in
which the address itself is enclosed in square brackets:[2001:227:e857:1::1][2001:227:e857:1:0:0:0:0:1]/64For more information about addressing, see the Setup Guide.Specifying SOURCE and DESTEntries in Shorewall configuration files often deal with the source
(SOURCE) and destination (DEST) of connections and Shorewall implements a
uniform way for specifying them.A SOURCE or DEST consists of one to three parts separated by colons
(":"):ZONE — The name of a zone declared in
/etc/shorewall/zones or
/etc/shorewall6/zones. This part is only
available in the rules file
(/etc/shorewall/rules,
/etc/shorewall/blrules,
/etc/shorewall6/rules and
/etc/shorewall6/blrules).INTERFACE — The name of an interface that matches an entry in
/etc/shorewall/interfaces
(/etc/shorewall6/interfaces).ADDRESS LIST — A list of one or more addresses (host or network)
or address ranges, separated by commas. In an IPv6 configuration, this
list must be included in square or angled brackets ("[...]" or
"<...>"). The list may have exclusion.Examples.All hosts in the net zone —
netSubnet 192.168.1.0/29 in the loc zone — loc:192.168.1.0/29All hosts in the net zone connecting through ppp0 — net:ppp0All hosts interfaced by eth3 — eth3Subnet 10.0.1.0/24 interfacing through eth2 — eth2:10.0.1.0/24Host 2002:ce7c:92b4:1:a00:27ff:feb1:46a9 in the loc zone — loc:[2002:ce7c:92b4:1:a00:27ff:feb1:46a9]The primary IP address of eth0 in the $FW zone - $FW:ð0 (see Run-time Address Variables below)All hosts in Vatican City - net:^VA (Shorwall 4.5.4 and later - See this article).INCLUDE DirectiveAny configuration file may contain INCLUDE directives. An INCLUDE
directive consists of the word INCLUDE followed by a path name and causes
the contents of the named file to be logically included into the file
containing the INCLUDE. Relative path names given in an INCLUDE directive
are resolved using the current CONFIG_PATH setting (see shorewall.conf(5)).INCLUDE's may be nested to a level of 3 -- further nested INCLUDE
directives are ignored with a warning message.Beginning with Shorewall 4.4.17, the INCLUDE directive may also
appear in the following extension scripts:clearfindgwinitisusablerefreshrefreshedrestorerestoredstartstartedstopstoppedtcclearWhen used in these scripts, the INCLUDEd files are copied into the
compiled firewall script.Prior to Shorewall 4.4.17, if you are using Shorewall Lite , it is not advisable
to use INCLUDE in the params file in an export
directory if you set EXPORTPARAMS=Yes in shorewall.conf (5). If you do
that, you must ensure that the included file is also present on the
firewall system's /etc/shorewall-lite/ directory.If you only need the params file at compile
time, you can set EXPORTPARAMS=No in
shorewall.conf. That prevents the
params file from being copied into the compiled
script. With EXPORTPARAMS=No, it is perfectly okay to use INCLUDE in the
params file. Note that with Shorewall 4.4.17 and
later:The variables set at compile time are available at run-time
even with EXPORTPARAMS=No.The INCLUDE directive in the params file
is processed at compile time and the INCLUDEd file is copied into
the compiled script.Use of INCLUDE shorewall/params.mgmt:
MGMT_SERVERS=1.1.1.1,2.2.2.2,3.3.3.3
TIME_SERVERS=4.4.4.4
BACKUP_SERVERS=5.5.5.5
----- end params.mgmt -----
shorewall/params:
# Shorewall 1.3 /etc/shorewall/params
[..]
#######################################
INCLUDE params.mgmt
# params unique to this host here
----- end params -----
shorewall/rules.mgmt:
ACCEPT net:$MGMT_SERVERS $FW tcp 22
ACCEPT $FW net:$TIME_SERVERS udp 123
ACCEPT $FW net:$BACKUP_SERVERS tcp 22
----- end rules.mgmt -----
shorewall/rules:
# Shorewall version 1.3 - Rules File
[..]
#######################################
INCLUDE rules.mgmt
# rules unique to this host here
----- end rules -----You may include multiple files in one command using an embedded shell command.Example (include all of the files ending in ".rules" in a
directory:):gateway:/etc/shorewall # ls rules.d
ALL.rules DNAT.rules FW.rules NET.rules REDIRECT.rules VPN.rules
gateway:/etc/shorewall # /etc/shorewall/rules:?SECTION NEW
SHELL cat /etc/shorewall/rules.d/*.rulesIf you are the sort to put such an entry in your rules file even
though /etc/shorewall/rules.d might not exist or might be empty, then
you probably want:?SECTION NEW
SHELL cat /etc/shorewall/rules.d/*.rules 2> /dev/null || trueBeginning with Shorewall 4.5.2, in files other than
/etc/shorewall/params and
/etc/shorewall/conf, INCLUDE may be immediately
preceded with '?' to signal that the line is a compiler directive and
not configuration data.Example:?INCLUDE common.rules?FORMAT DirectiveA number of configuration files support multiple formats. Prior to
Shorewall 4.5.11, the format was specified by a line having 'FORMAT' as
the first token. This requires each of the file processors to handle
FORMAT separately.In Shorewall 4.5.11, the ?FORMAT directive was created to centralize
processing of FORMAT directives. The old entries, while still supported in
Shorewall 4.5-4.6, are now deprecated. They are no longer supported in
Shorewall 5.0 and later versions.The ?FORMAT directive is as follows:?FORMAT formatWhere format is an integer. In all cases, the default format
is 1. The following table shows the files that have different
formats and the supported formats for each.FILEFORMATSaction files (action.*)1 and 2conntrack1, 2 and 3interfaces1 and 2macro files (macro.*)1 and 2tcrules1 and 2?COMMENT DirectiveA number of files allow attaching comments to generated Netfilter
rules:accountingaction.* filesblrulesconntrackmacro.* filessnatnatrulessecmarkstcrulestunnelsPrior to Shorewall 4.5.11, comments were specified by a line having
COMMENT as the first token. The remainder of the line is treated as a
comment to be attached to rules.In Shorewall 4.5.11, the ?COMMENT directive was created to
centralize processing of COMMENT directives. The old entries, while still
supported in Shorewall 4.5 and 4.6, are now deprecated. They are no longer
supported in Shorewall 5.0 and later versions.Use of this directive requires Comment support in your kernel and
iptables - see the output of shorewall show
capabilities.The ?COMMENT directive is as follows:?COMMENT [ comment ]If comment is present, it will
appear enclosed in /*....*/ in the output of the shorewall
show and shorewall dump commands. If no
comment is present, the rules generated
by following entries will not have comments attached.Example (/etc/shorewall/rules):?COMMENT Stop NETBIOS noise
REJECT loc net tcp 137,445
REJECT loc net udp 137:139
?COMMENT 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
?COMMENTHere's the corresponding output from
/sbin/shorewall-lite:gateway:~ # shorewall-lite show loc-net
Shorewall Lite 4.3.3 Chains loc2net at gateway - Mon Oct 16 15:04:52 PDT 2008
Counters reset Mon Oct 16 14:52:17 PDT 2006
Chain loc-net (1 references)
pkts bytes target prot opt in out source destination
0 0 LOG tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25 LOG flags 0 level 6 prefix `FW:loc2net:REJECT:'
0 0 reject tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25
0 0 LOG udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:1025:1031 LOG flags 0 level 6 prefix `FW:loc2net:REJECT:'
0 0 reject udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:1025:1031
0 0 reject tcp -- * * 0.0.0.0/0 0.0.0.0/0 multiport dports 137,445 /* Stop NETBIOS noise */
0 0 reject udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:137:139 /* Stop NETBIOS noise */
0 0 DROP all -- * * !192.168.0.0/22 0.0.0.0/0 /* Stop my idiotic work laptop from sending to the net with an HP source/dest IP address */
5 316 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0
gateway:~ #
?COMMENT lines in macro files work somewhat differently from other
files. ?COMMENT lines in macros are ignored if COMMENT support is not
available or if there was a COMMENT in use when the top-level macro was
invoked. This allows the following:/usr/share/shorewall/macro.SSH:#ACTION SOURCE DEST PROTO DPORT SPORT RATE USER
?COMMENT SSH
PARAM - - tcp 22 /etc/shorewall/rules:?COMMENT Allow SSH from home
SSH(ACCEPT) net:$MYIP $FW
?COMMENTThe comment line in macro.SSH will not override the
?COMMENT line in the rules file and the generated rule will show /* Allow SSH from home */ when displayed through
the Shorewall show and dump commands.Beginning with Shorewall 5.0.11, the alternate
input format allows attaching comments to individual rules in the
files listed above.CONFIG_PATHThe CONFIG_PATH option in shorewall.conf determines where the
compiler searches for configuration files. The default setting is
CONFIG_PATH=/etc/shorewall:/usr/share/shorewall which means that the
compiler first looks in /etc/shorewall and if it doesn't find the file, it
then looks in /usr/share/shorewall.You can change this setting to have the compiler look in different
places. For example, if you want to put your own versions of standard
macros in /etc/shorewall/Macros, then you could set
CONFIG_PATH=/etc/shorewall:/etc/shorewall/Macros:/usr/share/shorewall and
the compiler will use your versions rather than the standard ones.Using Shell VariablesYou may use the /etc/shorewall/params file to
set shell variables that you can then use in the other configuration
files.It is suggested that variable names begin with an upper case letter
to distinguish them from variables used internally within the Shorewall
programsThe following variable names must be avoided. Those in bold font must be avoided in all Shorewall
versions; those in regular font must be avoided in versions prior to
4.4.8.Any option from shorewall.conf
(5)COMMANDCONFDIRDEBUGECHO_EECHO_NEXPORTFASTFILEMODEHOSTNAMEIPT_OPTIONSNOROUTESPREVIEWPRODUCTPROFILEPURGERECOVERINGRESTOREPATHRING_BELLSHAREDIRAny name beginning with SHOREWALL_ or
SW_STOPPINGTESTTIMESTAMPUSE_VERBOSITYVARDIRVARLIBVERBOSEVERBOSE_OFFSETVERSIONExample:
/etc/shorewall/params
NET_IF=eth0
NET_BCAST=130.252.100.255
NET_OPTIONS=routefilter,routefilter
/etc/shorewall/interfaces record:
net $NET_IF $NET_BCAST $NET_OPTIONS
The result will be the same as if the record had been written
net eth0 130.252.100.255 routefilter,routefilter
Variables may be used anywhere in the other configuration
files.If you use "$FW" on the right side of assignments in the
/etc/shorewall/params file, you must also set the
FW variable in that file.Example:/etc/shorewall/zones:
#ZONE TYPE OPTIONS
fw firewall
/etc/shorewall/params:
FW=fw
BLARG=$FW:206.124.146.176Because the /etc/shorewall/params file is
simply sourced into the shell, you can place arbitrary shell code in the
file and it will be executed each time that the file is read. Any code
included should follow these guidelines:The code should not have side effects, especially on other
shorewall configuration files.The code should be safe to execute multiple times without
producing different results.Should not depend on where the code is called from.Should not assume anything about the state of Shorewall.The names of any functions or variables declared should begin
with an upper case letter.The /etc/shorewall/params file is processed
by the compiler at compile-time and by the compiled script at
run-time. If you have set EXPORTPARAMS=No in
shorewall.conf, then the
params file is only
processed by the compiler; it is not run by the compiled script.
Beginning with Shorewall 4.4.17, the values of the variables set at
compile time are available at run time with EXPORTPRARMS=No.If you are using Shorewall
Lite and if the params script needs to
set shell variables based on the configuration of the firewall system,
you can use this trick:EXT_IP=$(ssh root@firewall "/sbin/shorewall-lite call find_first_interface_address eth0")The shorewall-lite call command allows you to
call interactively any Shorewall function that you can call in an
extension script.Within your configuration files, only the $VAR and ${VAR}
forms of variable expansion are supported. You may not use the more
exotic forms supported by the shell (${VAR:=val}, ${VAR:-val},
...)Beginning with Shorewall 4.4.27, you may also use options in shorewall.conf (5) (e.g.,
$BLACKLIST_LOGLEVEL).When an option is set to 'No' in shorewall.conf, the corresponding
shell variable will be empty.Options that were not set in shorewall.conf will expand to their
default value.Beginning with Shorewall 4.5.2, configuration files
can access variables defined in the shorewallrc file.Beginning with Shorewall 4.5.11, variables can be altered by
compiler directives.?SET variable valueThe variable can be specified
either with or without a leading '$' to allow using both Perl and
Shell variable representation. The ${...} form (e.g. ${foo}) is not
allowed.The value is a Perl-compatible
expression.The Shorewall compiler performs variable expansion within
the expression. So variables are expanded even when they appear in
single quotes.If a variable within the expression can contain a
non-numeric value, it is a good idea to enclose it in quotes.
Otherwise, the Shorewall compiler has to guess whether to enclose
the variable's value in quotes or not.?RESET variableRemoves the named variable from the
compiler's variable table.Action variables are read-only and cannot be ?SET (although you can
change their values using embedded
Perl).Beginning with Shorewall 4.5.13, Shorewall Variables may be set. When
setting a Shorewall Variable, the variable must
include the leading '@' and the @{...} form is not allowed.Address VariablesPrior to Shorewall 5.0.14, if you use address variables that refer
to an optional interface, the enable command will not
change/insert the rules that use the variable. Therefore, to be
completely safe, if you use such address variables then you must follow
a successful enable command with a
reload command.Beginning with Shorewall 5.0.14, if a Shorewall-defined address
variable's value has changed since the Netfilter ruleset was
instantiated, then a successful enable command will
automatically reload the ruleset.Given that shell variables are expanded at compile time, there is no
way to cause such variables to be expanded at run time. Prior to Shorewall
4.4.17, this made it difficult (to impossible) to include dynamic IP
addresses in a Shorewall-lite
configuration.Version 4.4.17 implemented Run-time address
variables. In configuration files, these variables are
expressed as an apersand ('&') followed by the logical name of an
interface defined in shorewall-interfaces (5). Wildcard interfaces (those
ending in '+') are not supported and will cause a compilation
error.Example:ð0 would represent the
primary IP address of eth0.Beginning with Shorewall 4.5.11, you can define your own address
variables by using this syntax:&{variable}where variable is a valid shell variable
name. The generated script will verify that the
variable contains a valid host or network
address, either from the environment or from it being assigned in your
initextension script, and will
raise an error if it does not. In the error case, the state of the
firewall will remain unchanged.Example:/etc/shorewall/init:SMC_ADDR=10.1.10.11/etc/shorewall/rules:test:debug net:&{SMC_ADDR} fwA second form is also available beginning with Shorewall
4.5.11%{variable}Unlike with the first form, this form does not require the variable
to be set. If the variable is empty, the generated script will supply the
all-zeros address (0.0.0.0 in IPv4 and :: in IPv6). In most cases, the
compiler simply omits rules containing matches on the all-zeros
address.Example:/etc/shorewall/init:SMC_ADDR=10.1.10.11/etc/shorewall/rules:test:debug net:%{SMC_ADDR} fwFor a particular address variable, all references must use the
same prefix character ('&' or '%'). Otherwise, the following error
message is raised:ERROR: Mixed required/optional usage of address variable
variableRun-time address variables may be used in the SOURCE and DEST column
of the following configuration files:shorewall-accounting
(5)Action filesshorewall-blrules
(5)Macro filesshorewall-mangle
(5)shorewall-nat(5)shorewall-rules (5)They may also appear in the ORIGDEST column of:shorewall-accounting
(5)Macro filesAction filesshorewall-rules (5)For optional interfaces, if the interface is not usable at the time
that the firewall starts, one of two approaches are taken, depending on
the context:the all-zero address will be used (0.0.0.0 in IPv4 and :: in
IPv6), resulting in no packets matching the rule (or all packets if
used with exclusion).the entire rule is omitted from the ruleset.Beginning with Shorewall 4.5.1, Run-time Gateway
Variables in the form of a percent sign ('%') followed by a
logical interface name are also supported. These are expanded at run-time
to the gateway through the named interface. For optional interfaces, if
the interface is not usable at the time that the firewall starts, the nil
address will be used (0.0.0.0 in IPv4 and :: in IPv6), resulting in no
packets matching the rule. Run-time gateway variables may be used in the
SOURCE and DEST columns of the following configuration files:shorewall-accounting
(5)Action filesshorewall-blrules
(5)Macro filesshorewall-mangle
(5)shorewall-nat(5) (As a
qualifier to the INTERFACE).shorewall-routes
(5)shorewall-rules (5)Example:%eth0 would represent the IP
address of the gateway out of eth0.If there is no gateway out of the named interface, rules containing
the intefaces's run-time gateway variable are omitted.Port VariablesBeginning with Shorewall 5.1.5, Run-time Port
Variables are supported. These variables have the format
%{variable} and may appear any place that a
port number or service name may appear. Like their address-variable
counterparts above, Run-time Port Variables are most useful when
Shorewall[6]-lite is being used.Example using both Run-time Address and Run-time Port
Variables:/etc/shorewall/init: SERVER_PORT=4126
SERVER_ADDRESS=192.0.44.12/etc/shorewall/rules: ACCEPT net dmz:%{SERVER_ADDRESS} tcp %{SERVER_PORT}Rather than assigning a numerical literal to SERVER_PORT in the
init extension script as shown above, the variable
could be assigned a dynamic value based on a database lookup.If no value is assigned to a Run-time Port Variable in the
init extension script, then the value 255 is
assumed.Care must be exercised when using port variables in port ranges.
At run-time, the generated script will verify that each port variable is
either empty or contains a valid port number or service name. It does
not ensure that the low port number in a range is strictly less than the
high port number, when either of these is specified as a port
variable.Example: The following definitions will result in an
iptables-restore failure during start/restart/reload:/etc/shorewall/init: LOW_PORT=100
HIGH_PORT=50/etc/shorewall/rules: ACCEPT net $FW tcp ${LOW_PORT}:${HIGH_PORT}Action VariablesAction variables were introduced in Shorewall 4.4.16 and may be
accessed within the body of an action.Parameter variablesParameter variables expand to the value of the corresponding
action parameter. $1 is the first parameter,
$2 is the second parameter and so on.Chain nameBeginning with Shorewall 4.5.10, $0 expands to the name of the
action chain. Shorewall generates a separate chain for each unique
(action,log-level,log-tag,parameters) tupple. The first such chain
has the same name as the action itself. Subsequent chains are formed
by prepending '%' to the action name and appending a number to
insure uniqueness. For an action called 'Action', the chains would
be Action, %Action,
%Action0, %Action1 and so
on.Shorewall VariablesShorewall Variables were introduced in Shorewall 4.5.11. To insure
uniqueness, these variables start with the character @; the name of the
variable must be enclosed in {...} when the following character is
alphanumeric or is an underscore ("_"). With the exception of @0 (or it's
alias @chain), Shorewall variables may only be used within an action
body.Prior to Shorewall 4.5.13, Shorewall variables are read-only.
Beginning with Shorewall 4.5.13, their values may be altered using the
?SET directive.The Shorewall variables are:@0 and @chain (@{0} and @{chain})Expands to the name of the current chain. Unlike $0, @0 has
all non-alphanumeric characters except underscore removed. Also
unlike $0, @0 may be used in SWITCH columns in configuration
files.@1, @2, ... (@{1}, @{2}, ...These are synonyms for the Action parameter variables $1, $2,
etc.@loglevel (@{loglevel})Expands to the log level specified when the action was
invoked.@logtag (@{logtag})Expands to the log tag specified when the action was
invoked.@action(@{action})Expands to the name of the action being compiled.@disposition (@{disposition})Added in Shorewall 4.5.13. When a non-inlined action is
entered, this variable is set to the empty value. When an inline
action is entered, the variable's value is unchanged.@caller (@{caller})Added in Shorewall 4.5.13. Within an action, expands to the
name of the chain that invoked the action.Beginning with Shorewall 4.5.13, the values of @chain and
@disposition are used to generated the --log-prefix in logging rules. When
either is empty, the historical value is used to generate the
--log-prefix.Within an action body, if a parameter is omitted in a DEFAULTS
statement, then the value of the corresponding action and Shorewall
variables is '-', while if the parameter is specified as '-' in the
parameter list, the value of the action/Shorewall variable is '', if it is
expanded before the DEFAULTS statement.Additionally, when an expression is evaluated, the value 0 evaluates
as false, so '?IF @n' and '?IF $n' fail if the nth parameter is passed
with value zero. To make testing of the presense of parameters more
efficient and uniform, an new function has been added in Shorewall 5.0.7
for use in ?IF and ?ELSEIF:?IF [!] passed(<variable>)where <variable> is an action or Shorewall variable.'passed(@n)' and 'passed($n)' evaluate to true if the nth parameter
is not empty and its contents are other than '-'. If '!' is present, the
result is inverted.In this simple form, the expression is evaluated by the compiler
without having to invoke the (expensive) Perl exec() function. The
'passed' function may also be used in more complex expressions, but exec()
will be invoked to evaluate those expressions.Conditional EntriesBeginning with Shorewall 4.5.2, lines in configuration files may be
conditionally included or omitted based on the setting of Shell variables.The general form is:?IF $variable
<lines to be included if $variable is non-empty and non-zero>
?ELSE
<lines to be omitted if $variable is non-empty and non-zero>
?ENDIFThe compiler predefines two special
variables that may only be used in ?IF
lines:__IPV4True if this is an IPv4 compilation__IPV6True if this is an IPv6 compilation.Unless variable is one of these
pre-defined ones, it is searched for in the following places in the order
listed.the compiler's environmental variables.variables set in
/etc/shorewall/params.options set in
/etc/shorewall/shorewall.conf.options set in the shorewallrc file when
Shorewall Core was installed.Beginning with Shorewall 4.5.11, the compiler's environmental
variables are search last rather than first.If the variable is still not
found:if it begins with '__', then those leading characters are
stripped off.the variable is then searched for in the defined
capabilities. The current set of capabilities
may be obtained by the command shorewall show
capabilities (the capability names are in
parentheses).If it is not found in any of those places, the
variable is assumed to have a value of 0
(false) in Shorewall versions prior to 4.5.11. In 4.5.11 and later, it is
assumed to have the value '' (an empty string, which also evaluates to
false).The setting in /etc/shorewall/params may be
overridden at runtime, provided the setting in
/etc/shorewall/params is done like this:[ -n "${variable:=0}" ]or like this:[ -n "${variable}" ] || variable=0Either of those will set variable to 0 if it is not set to a
non-empty value in the environment. The setting can be overridden at
runtime:variable=1 shorewall restart -c # use -c to force recompilation if AUTOMAKE=Yes in /etc/shorewall/shorewall.confThe ?ELSE may be omitted if there are no lines to be omitted.The test may also be inverted using '!':?IF ! $variable
<lines to be omitted if $variable is non-empty and non-zero>
?ELSE
<lines to be included if $variable is non-empty and non-zero>
?ENDIFConditional entries may be nested but the number of ?IFs must match
the number of ?ENDs in any give file. INCLUDE
directives are ignored in omitted lines.?IF $variable1
<lines to be included if $variable1 is non-empty and non-zero>
?IF $variable2
<lines to be included if $variable1 and $variable2 are non-empty and non-zero>
?ELSE
<lines to be omitted if $variable1 is non-empty and non-zero and if $variable2 is empty or zero>
?ENDIF
<lines to be included if $variable1 is non-empty and non-zero>
?ELSE
<lines to be omitted if $variable is non-empty and non-zero>
?ENDIFBeginning with Shorewall 4.5.6, rather than a simple variable in ?IF
directives, Perl-compatible expressions are allowed (after the Shorewall
compiler expands all variables, the resulting expression is then evaluated
by Perl). Variables in the expressions are as described above.Example:?IF $BLACKLIST_LOGLEVEL == 6 && ! __LOG_OPTIONSAdditionally, a ?ELSIF directive is supported.Example:?IF expression-1
<lines to be included if expression-1 evaluates to true (non-empty and non-zero)
?ELSIF expression1-2
<lines to be included if expression-1 evaluates to false (zero or empty) and expression-2 evaluates to true
?ELSIF expression-3
<lines to be included if expression-1 and expression-2 both evalute to false and expression-3 evalutes to true
?ELSE
<lines to be included if all three expressions evaluate to false.
?ENDIFBeginning in Shorewall 5.0.7, an error can be raised using the
?ERROR directive:?ERROR messageVariables in the message are evaluated and the result appears in a
standard Shorewall ERROR: message.Example from the 5.0.7 action.GlusterFS:?if @1 !~ /^\d+/ || ! @1 || @1 > 1024
?error Invalid value for Bricks (@1)
?elsif @2 !~ /^[01]$/
?error Invalid value for IB (@2)
?endif
The above code insures that the first action paramater is a non-zero
number <= 1024 and that the second parameter is either 0 or 1. If 2000
is passed for the first parameter, the following error message is
generated: ERROR: Invalid value for Bricks (2000) /usr/share/shorewall/action.GlusterFS (line 15)
from /etc/shorewall/rules (line 45)In Shorewall 5.0.8, ?WARNING and ?INFO directives were added.?WARNING message
?INFO message?WARNING message produces a standard Shorewall WARNING: message,
while ?INFO produces a similar message which is prefaced by INFO: rather
than WARNING:. Both write the message to STDERR. The message is also
written to the STARTUP_LOG, if any, provided that the command is
start, try,
restart, reload,
refresh, or one of the safe-*
commands.See the VERBOSE_MESSAGES option in shorewall.conf(5) for
additional information.In Shorewall 5.1.4, the behavior of ?ERROR, ?WARNING and ?INFO was
changed when they appear in an action file. Rather than reporting the
action filename and line number, the generated message reports where the
action was invoked. For example, the GlusterFS message above was changed
to: ERROR: Invalid value (2000) for the GlusterFS Bricks argument /etc/shorewall/rules (line 45)Embedded Shell and PerlEarlier versions of Shorewall offered extension scripts to allow
users to extend Shorewall's functionality. Extension scripts were designed
to work under the limitations of the Bourne Shell. With the current
Perl-based compiler, Embedded scripts offer a
richer and more flexible extension capability.While inline scripts may be written in either Shell or Perl, those
written in Perl have a lot more power. They may be used in all
configuration files except /etc/shorewall/params and
/etc/shorewall/shorewall.conf.Note:In this section, '[' and ']'
are meta-characters which indicate that what they enclose is optional and
may be omitted.Single line scripts take one of the following forms:[?]PERL <perl
script>[?]SHELL <shell
script>The optional leading question mark (?) is allowed in Shorewall
4.5.5 and later.Shell scripts run in a child shell process and their output is piped
back to the compiler which processes that output as if it were embedded at
the point of the script.Example: The following entries in
/etc/shorewall/rules are equivalent:SHELL for z in net loc dmz; do echo "ACCEPT $z fw tcp 22"; doneACCEPT net fw tcp 22
ACCEPT loc fw tcp 22
ACCEPT dmz fw tcp 22Perl scripts run in the context of the compiler process using Perl's
eval() function. Perl scripts are implicitly prefixed by the
following:package Shorewall::User;
use Shorewall::Config ( qw/shorewall/ );To produce output that will be processed by the compiler as if it
were embedded in the file at the point of the script, pass that output to
the Shorewall::Config::shorewall() function. The Perl equivalent of the
above SHELL script would be:PERL for ( qw/net loc dmz/ ) { shorewall "ACCEPT $_ fw tcp 22"; }A
couple of more points should be mentioned:Compile-time extension scripts are also implicitly prefixed by
"package Shorewall::User;".A compile extension script is
supported. That script is run early in the compilation process and
allows users to load additional modules and to define data and
functions for use in subsequent embedded scripts and extension
scripts.Manual Chains may be
added in the compile extension
script..Multi-line scripts use one of the following forms:[?]BEGIN SHELL
<shell script>
[?]END [ SHELL ][?]BEGIN PERL [;]
<perl script>
[?]END [ PERL ] [;]The optional leading question mark (?) is allowed in Shorewall
4.5.5 and later.Using DNS NamesI personally recommend strongly against using DNS names in
Shorewall configuration files. If you use DNS names and you are called
out of bed at 2:00AM because Shorewall won't start as a result of DNS
problems then don't say that you were not forewarned.Host addresses in Shorewall configuration files may be specified as
either IP addresses or DNS Names.DNS names in iptables rules aren't nearly as useful as they first
appear. When a DNS name appears in a rule, the iptables utility resolves
the name to one or more IP addresses and inserts those addresses into the
rule. So changes in the DNS->IP address relationship that occur after
the firewall has started have absolutely no effect on the firewall's rule
set.For some sites, using DNS names is very risky. Here's an
example:teastep@ursa:~$ dig pop.gmail.com
; <<>> DiG 9.4.2-P1 <<>> pop.gmail.com
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1774
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 7, ADDITIONAL: 0
;; QUESTION SECTION:
;pop.gmail.com. IN A
;; ANSWER SECTION:
pop.gmail.com. 300 IN CNAME gmail-pop.l.google.com.
gmail-pop.l.google.com. 300 IN A 209.85.201.109
gmail-pop.l.google.com. 300 IN A 209.85.201.111Note that the TTL is 300 -- 300 seconds is only 5 minutes. So five
minutes later, the answer may change!So this rule may work for five minutes then suddently stop
working:#ACTION SOURCE DEST PROTO DPORT
POP(ACCEPT) loc net:pop.gmail.comThere are two options in shorewall[6].conf(5) that
affect the use of DNS names in Shorewall[6] config files:DEFER_DNS_RESOLUTION - When set to No, DNS names are resolved at
compile time; when set to Yes, DNS Names are resolved at
runtime.AUTOMAKE - When set to Yes, start,
restart and reload only result
in compilation if one of the files on the CONFIG_PATH has changed
since the the last compilation.So by setting AUTOMAKE=Yes, and DEFER_DNS_RESOLUTION=No, compilation
will only take place at boot time if a change had been make to the config
but no restart or reload had taken
place. This is clearly spelled out in the shorewall.conf manpage. So with
these settings, so long as a 'reload' or 'restart' takes place after the
Shorewall configuration is changes, there should be no DNS-related
problems at boot time.When DEFER_DNS_RESOLUTION=No and AUTOMAKE=Yes and a DNS change
makes it necessary to recompile an existing firewall script, the
option must be used with the
reload or restart command to force
recompilation.If your firewall rules include DNS names then, even if
DEFER_DNS_RESOLUTION=No and AUTOMAKE=Yes:If your /etc/resolv.conf is wrong then your
firewall may not start.If your /etc/nsswitch.conf is wrong then
your firewall may not start.If your Name Server(s) is(are) down then your firewall may not
start.If your startup scripts try to start your firewall before
starting your DNS server then your firewall may not start.Factors totally outside your control (your ISP's router is down
for example), can prevent your firewall from starting.You must bring up your network interfaces prior to starting your
firewall, or the firewall may not start.Each DNS name must be fully qualified and include a minimum of two
periods (although one may be trailing). This restriction is imposed by
Shorewall to insure backward compatibility with existing configuration
files.Valid DNS Namesmail.shorewall.netshorewall.net. (note the trailing period).Invalid DNS Namesmail (not fully qualified)shorewall.net (only one period)DNS names may not be used as:The server address in a DNAT rule (/etc/shorewall/rules
file)In the ADDRESS column of an entry in /etc/shorewall/masq.In the /etc/shorewall/nat file.These restrictions are imposed by Netfilter and not by
Shorewall.Comma-separated ListsComma-separated lists are allowed in a number of contexts within the
configuration files. A comma separated list:Must not have any embedded white space.+ Valid: routefilter,dhcp,arpfilter
Invalid: routefilter, dhcp, arpfilterIf you use line continuation to break a comma-separated list,
the comma must be the last thing on the continued line before '\'
unless the continuation line has no leading white space.Entries in a comma-separated list may appear in any
order.Complementing an Address, Subnet, Protocol or Port ListWhere specifying an IP address, a subnet or an interface, you can
precede the item with ! to specify the complement of the
item. For example, !192.168.1.4 means any host but
192.168.1.4. There must be no white space following the
!.Similarly, in columns that specify an IP protocol, you can precede
the protocol name or number by "!". For example, !tcp means "any protocol
except tcp".This also works with port lists, providing that the list contains 15
or fewer ports (where a port range counts as
two ports). For example !ssh,smtp means "any port except 22 and
25".In Shorewall 4.4.19 and later, icmp type lists are supported but
complementing an icmp type list is not supported. You
may, however, complement a single icmp (icmp6) type.Exclusion ListsWhere a comma-separated list of addresses is accepted, an
exclusion list may also be included. An exclusion
list is a comma-separated list of addresses that begins with "!".Example:!192.168.1.3,192.168.1.12,192.168.1.32/27The above list refers to "All addresses except 192.168.1.3,
192.168.1.12 and 192.168.1.32-192.168.1.63.Exclusion lists can also be added after a network address.Example:192.168.1.0/24!192.168.1.3,192.168.1.12,192.168.1.32/27The above list refers to "All addresses in 192.168.1.0-192.168.1.255
except 192.168.1.3, 192.168.1.12 and 192.168.1.32-192.168.1.63.IP Address RangesIf you kernel and iptables have iprange match support, you may use
IP address ranges in Shorewall configuration file entries; IP address
ranges have the syntax <low IP
address>-<high IP address>.
Example: 192.168.1.5-192.168.1.12.To see if your kernel and iptables have the required support, use
the shorewall show capabilities command:>~ shorewall show capabilities
...
Shorewall has detected the following iptables/netfilter capabilities:
NAT: Available
Packet Mangling: Available
Multi-port Match: Available
Connection Tracking Match: Available
Packet Type Match: Not available
Policy Match: Available
Physdev Match: Available
IP range Match: Available <--------------Protocol Number/Names and Port Numbers/Service NamesUnless otherwise specified, when giving a protocol number you can
use either an integer or a protocol name from
/etc/protocols. Similarly, when giving a port number
you can use either an integer or a service name from
/etc/services.The rules compiler translates protocol names to protocol numbers
and service names to port numbers itself.Also, unless otherwise documented, a protocol number/name can be
preceded by '!' to specify "All protocols except this one" (e.g.,
"!tcp").Port RangesIf you need to specify a range of ports, the proper syntax is
<low port number>:<high port number>. For example, if you want
to forward the range of tcp ports 4000 through 4100 to local host
192.168.1.3, the entry in /etc/shorewall/rules is:#ACTION SOURCE DESTINATION PROTO DPORT
DNAT net loc:192.168.1.3 tcp 4000:4100If you omit the low port number, a value of zero is assumed; if you
omit the high port number, a value of 65535 is assumed.Also, unless otherwise documented, a port range can be preceded by
'!' to specify "All ports except those in this range" (e.g.,
"!4000:4100").Beginning with Shorewall 5.0.14, a hyphen ("-") may also be used to
separate the two port numbers; when using service names, the colon must
still be used.#ACTION SOURCE DESTINATION PROTO DPORT
DNAT net loc:192.168.1.3 tcp 4000-4100Port ListsIn most cases where a port or port range may appear, a
comma-separated list of ports or port ranges may also be entered.
Shorewall requires the Netfilter multiport match capability if ports lists are used
(see the output of "shorewall show
capabilities").Also, unless otherwise documented, a port list can be preceded by
'!' to specify "All ports except these" (e.g., "!80,443").Prior to Shorewall 4.4.4, port lists appearing in the shorewall-routestopped
(5) file may specify no more than 15 ports; port ranges appearing in a
list count as two ports each.ICMP and ICMP6 Types and CodesWhen dealing with ICMP, the DEST PORT specifies the type or type and
code. You may specify the numeric type, the numeric type and code
separated by a slash (e.g., 3/4) or you may use a type name.Type names for IPv4 and their corresponding type or type/code
are:echo-reply' => 0
destination-unreachable => 3
network-unreachable => 3/0
host-unreachable => 3/1
protocol-unreachable => 3/2
port-unreachable => 3/3
fragmentation-needed => 3/4
source-route-failed => 3/5
network-unknown => 3/6
host-unknown => 3/7
network-prohibited => 3/9
host-prohibited => 3/10
TOS-network-unreachable => 3/11
TOS-host-unreachable => 3/12
communication-prohibited => 3/13
host-precedence-violation => 3/14
precedence-cutoff => 3/15
source-quench => 4
redirect => 5
network-redirect => 5/0
host-redirect => 5/1
TOS-network-redirect => 5/2
TOS-host-redirect => 5/3
echo-request => 8
router-advertisement => 9
router-solicitation => 10
time-exceeded => 11
ttl-zero-during-transit => 11/0
ttl-zero-during-reassembly=> 11/1
parameter-problem => 12
ip-header-bad => 12/0
required-option-missing => 12/1
timestamp-request => 13
timestamp-reply => 14
address-mask-request => 17
address-mask-reply => 18Type names for IPv6 and their corresponding type or type/code
are:destination-unreachable => 1
no-route' => 1/0
communication-prohibited => 1/1
address-unreachable' => 1/3
port-unreachable' => 1/4
packet-too-big => 2
time-exceeded' => 3
ttl-exceeded' => 3
ttl-zero-during-transit => 3/0
ttl-zero-during-reassembly => 3/1
parameter-problem => 4
bad-header => 4/0
unknown-header-type => 4/1
unknown-option => 4/2
echo-request => 128
echo-reply => 129
router-solicitation => 133
router-advertisement => 134
neighbour-solicitation => 135
neighbour-advertisement => 136
redirect => 137Shorewall 4.4 does not accept lists if ICMP (ICMP6) types prior to
Shorewall 4.4.19.Using MAC AddressesMedia Access Control (MAC) addresses can be used to specify packet
source in several of the configuration files. In order to control traffic
to/from a host by its MAC address, the host must be on the same network as
the firewall.To use this feature, your kernel must have MAC Address Match support
(CONFIG_IP_NF_MATCH_MAC) included.MAC addresses are 48 bits wide and each Ethernet Controller has a
unique MAC address.In GNU/Linux, MAC addresses are usually written as a series of 6 hex
numbers separated by colons.MAC Address of an Ethernet Controller gateway:~ # ip link ls dev eth0
4: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc htb qlen 1000
link/ether 02:00:08:E3:FA:55 brd ff:ff:ff:ff:ff:ff
gateway:~ #Because Shorewall uses colons as a separator for address fields,
Shorewall requires MAC addresses to be written in another way. In
Shorewall, MAC addresses begin with a tilde (~) and consist
of 6 hex numbers separated by hyphens. In Shorewall, the MAC address in
the example above would be written ~02-00-08-E3-FA-55.It is not necessary to use the special Shorewall notation in the
/etc/shorewall/maclist
file.Rate Limiting (Rate and Burst)Shorewall supports rate limiting in a number of ways. When
specifying a rate limit, both a rate and a
burst value are given.Example from shorewall.conf (5):LOGLIMIT=10/minute:5For each logging rule, the first time the rule is reached, the
packet will be logged; in fact, since the burst is 5, the first five
packets will be logged. After this, it will be 6 seconds (1 minute divided
by the rate of 10) before a message will be logged from the rule,
regardless of how many packets reach it. Also, every 6 seconds which
passes, one of the bursts will be regained; if no packets hit the rule for
30 seconds, the burst will be fully recharged; back where we
started.Shorewall also supports per-IP rate limiting.Another example from shorewall.conf (5):LOGLIMIT="s:5/min:5"Here, the leading "s:" indicates that logging is to be limited by
source IP address ("d:" would indicate limiting by destination IP
address)."s:" is followed by the rate (5 messages per minute) and the burst
(5).The rate and limit arguments have the same meaning as in the example
above.TIME ColumnsSeveral of the files include a TIME colum that allows you to specify
times when the rule is to be applied. Contents of this column is a list of
timeelements separated by apersands
(&).Each timeelement is one of the
following:timestart=hh:mm[:ss]Defines the starting time of day.timestop=hh:mm[:ss]Defines the ending time of day.contiguousAdded in Shoreawll 5.0.12. When timestop is smaller than timestart value, match this as a single time
period instead of distinct intervals. See the Examples below.utcTimes are expressed in Greenwich Mean Time.localtzDeprecated by the Netfilter team in favor of kerneltz. Times are expressed in Local Civil
Time (default).kerneltzAdded in Shorewall 4.5.2. Times are expressed in Local Kernel
Time (requires iptables 1.4.12 or later).weekdays=ddd[,ddd]...where ddd is one of
, , ,
, , or
monthdays=dd[,dd],...where dd is an ordinal day of the
monthdatestart=yyyy[-mm[-dd[hh[:mm[:ss]]]]]Defines the starting date and time.datestop=yyyy[-mm[-dd[hh[:mm[:ss]]]]]Defines the ending date and time.Examples:To match on weekends, use:weekdays=Sat,SunOr, to match (once) on a national holiday block:datestart=2016-12-24&datestop=2016-12-27Since the stop time is actually inclusive, you would need the
following stop time to not match the first second of the new
day:datestart=2016-12-24T17:00&datestop=2016-12-27T23:59:59During Lunch HourThe fourth Friday in the month:weekdays=Fri&monthdays=22,23,24,25,26,27,28Matching across days might not do what is expected. For
instance,weekdays=Mon×tart=23:00×top=01:00Will match Monday, for one hour from midnight to 1 a.m., and
then again for another hour from 23:00 onwards. If this is unwanted,
e.g. if you would like 'match for two hours from Montay 23:00
onwards' you need to also specify the contiguous option in the example
above.SwitchesThere are times when you would like to enable or disable one or more
rules in the configuration without having to do a shorewall
reload or shorewall restart. This may be
accomplished using the SWITCH column in shorewall-rules (5) or shorewall6-rules (5). Using
this column requires that your kernel and iptables include
Condition Match Support and you must be running
Shorewall 4.4.24 or later. See the output of shorewall show
capabilities and shorewall version to
determine if you can use this feature.The SWITCH column contains the name of a
switch. Each switch is initially in the off position. You can turn on the switch named
switch1 by:echo 1 >
/proc/net/nf_condition/switch1You can turn it off again by:echo 0 >
/proc/net/nf_condition/switch1If you simply include the switch name in the SWITCH column, then the
rule is enabled only when the switch is on. If you precede the switch name with ! (e.g.,
!switch1), then the rule is enabled only when the switch is off. Switch settings are retained over
shorewall restart.Shorewall requires that switch names:begin with a letter and be composed of letters, digits,
underscore ('_') or hyphen ('-'); andbe 30 characters or less in length.Multiple rules can be controlled by the same switch.Example:
Forward port 80 to dmz host $BACKUP if switch 'primary_down' is
on.#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER MARK CONNLIMIT TIME HEADERS SWITCH
DNAT net dmz:$BACKUP tcp 80 - - - - - - - - primary_down
Logical Interface NamesWhen dealing with a complex configuration, it is often awkward to
use physical interface names in the Shorewall configuration.You need to remember which interface is which.If you move the configuration to another firewall, the interface
names might not be the same.Beginning with Shorewall 4.4.4, you can use logical interface names
which are mapped to the actual interface using the
option in shorewall-interfaces
(5).Here is an example:#ZONE INTERFACE OPTIONS
net COM_IF dhcp,blacklist,tcpflags,optional,upnp,routefilter=0,nosmurfs,logmartians=0,physical=eth0
net EXT_IF dhcp,blacklist,tcpflags,optional,routefilter=0,nosmurfs,logmartians=0,proxyarp=1,physical=eth2
loc INT_IF dhcp,logmartians=1,routefilter=1,tcpflags,nets=172.20.1.0/24,physical=eth1
dmz VPS_IF logmartians=1,routefilter=0,routeback,physical=venet0
loc TUN_IFphysical=tun+In this example, COM_IF is a logical interface name that refers to
Ethernet interface eth0, EXT_IF is
a logical interface name that refers to Ethernet interface eth2, and so on.Here are a couple of more files from the same configuration:shorewall-masq
(5):#INTERFACE SOURCE ADDRESS
COMMENT Masquerade Local Network
COM_IF 0.0.0.0/0
EXT_IF !206.124.146.0/24 206.124.146.179:persistentshorewall-providers
(5)#NAME NUMBER MARK DUPLICATE INTERFACE GATEWAY OPTIONS COPY
Avvanta 1 0x10000 main EXT_IF 206.124.146.254 loose,fallback INT_IF,VPS_IF,TUN_IF
Comcast 2 0x20000 main COM_IF detect balance INT_IF,VPS_IF,TUN_IFNote in particular that Shorewall translates TUN_IF to tun* in the COPY column.Optional and Required InterfacesNormally, Shorewall assumes that all interfaces described in shorewall-interfaces (5)
are going to be in an up and usable state when Shorewall starts or
restarts. You can alter that assumption by specifying the optional option in the OPTIONS column.When an interface is marked as optional, Shorewall will determine
the interface state at start, reload
and restart and adjust its configuration
accordingly.The arp_filter, arp_ignore, routefilter, logmartians, proxyarp and sourceroute options are not enforced when the
interface is down, thus avoiding an error message such
as:WARNING: Cannot set Martian logging on ppp0If the interface is associated with a provider in shorewall-providers
(5), start, reload and
restart will not fail if the interface is not
usable.When DETECT_DNAT_IPADDRS=Yes in shorewall.conf (5), DNAT
rules in shorewall-rules (5) involving the interface will be omitted
when the interface does not have an IP address.If detect is specified in the
ADDRESS column of an entry in shorewall-masq (5) then the
firewall still starts if the optional interface in the INTERFACE
column does not have an IP address.If you don't want the firewall to start unless a given interface is
usable, then specify required in the
OPTIONS column of shorewall-interfaces (5).
If you have installed and configured the Shorewall-init package, then when
the interface becomes available, an automatic attempt will be made to
start the firewall.Shorewall ConfigurationsShorewall allows you to have configuration directories other than
/etc/shorewall. The shorewall
check, start,
reload and restart commands allow
you to specify an alternate configuration directory and Shorewall will use
the files in the alternate directory rather than the corresponding files
in /etc/shorewall. The alternate directory need not contain a complete
configuration; those files not in the alternate directory will be read
from /etc/shorewall.Shorewall requires that the file
/etc/shorewall/shorewall.conf to always exist.
Certain global settings are always obtained from that file. If you
create alternative configuration directories, do not remove
/etc/shorewall/shorewall.conf.This facility permits you to easily create a test or temporary
configuration bycopying the files that need modification from /etc/shorewall to
a separate directory;modify those files in the separate directory; andspecifying the separate directory in a shorewall
start, shorewall reload or
shorewall restart command (e.g., shorewall
restart /etc/testconfig )Saved ConfigurationsShorewall allows you to save the
currently-running configuration in a form that permits it to be
re-installed quickly. When you save the configuration using the
shorewall save command, the running configuration is
saved in a file in the /var/lib/shorewall directory. The default
name of that file is /var/lib/shorewall/restore but
you can specify a different name as part of the command. For example, the
command shorewall save standard will save the running
configuration in /var/lib/shorewall/standard. A saved
configuration is re-installed using the shorewall
restore command. Again, that command normally will restore the
configuration saved in /var/lib/shorewall/restore but
as with the save command, you can specify a different
file name in the command. For example, shorewall restore
standard will re-install the configuration saved in
/var/lib/shorewall/standard. By permitting you to
save different configurations under different names, Shorewall provides a
means for quickly switching between these different saved
configurations.As mentioned above, the default configuration is called 'restore'
but like most things in Shorewall, that default can be changed. The
default name is specified using the RESTOREFILE option in
/etc/shorewall/shorewall.conf.The default saved configuration is used by Shorewall in a number
of ways besides in the restore command; to avoid
surprises, I recommend that you read the Shorewall Operations
documentation section about saved configurations before creating
one.
shorewall-docs-xml-5.2.3/PortKnocking.xml 0000664 0000000 0000000 00000014443 13427347317 017120 0 ustar root root
Port Knocking and Other Uses of 'Recent Match'TomEastep2005200620092013Thomas 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.The techniques described in this article were superseded in
Shorewall 4.5.19 with the introduction of Shorewall Events.The feature described in this article require 'Recent Match' in
your iptables and kernel. See the output of shorewall show
capabilities to see if you have that match.What is Port Knocking?Port knocking is a technique whereby attempting to connect to port A
enables access to port B from that same host. For the example on which
this article is based, see http://www.soloport.com/iptables.html
which should be considered to be part of this documentation.Implementing Port Knocking in ShorewallIn order to implement this solution, your iptables and kernel must
support the 'recent match' extension (see FAQ
42).In this example:Attempting to connect to port 1600 enables SSH access. Access is
enabled for 60 seconds.Attempting to connect to port 1601 disables SSH access (note
that in the article linked above, attempting to connect to port 1599
also disables access. This is an port scan defence as explained in the
article).To implement that approach:Add an action named SSHKnock (see the Action documentation). Leave the
action.SSHKnock file empty.Create /etc/shorewall/SSHKnock with the following
contents.use Shorewall::Chains;
if ( $level ) {
log_rule_limit( $level,
$chainref,
'SSHKnock',
'ACCEPT',
'',
$tag,
'add',
'-p tcp --dport 22 -m recent --rcheck --name SSH ' );
log_rule_limit( $level,
$chainref,
'SSHKnock',
'DROP',
'',
$tag,
'add',
'-p tcp ! --dport 22 ' );
}
add_rule( $chainref, '-p tcp --dport 22 -m recent --rcheck --seconds 60 --name SSH -j ACCEPT' );
add_rule( $chainref, '-p tcp --dport 1599 -m recent --name SSH --remove -j DROP' );
add_rule( $chainref, '-p tcp --dport 1600 -m recent --name SSH --set -j DROP' );
add_rule( $chainref, '-p tcp --dport 1601 -m recent --name SSH --remove -j DROP' );
1;Now if you want to protect SSH access to the firewall from the
Internet, add this rule in
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
SSHKnock net $FW tcp 22,1599,1600,1601If you want to log the DROPs and ACCEPTs done by SSHKnock, you
can just add a log level as in:#ACTION SOURCE DEST PROTO DPORT
SSHKnock:info net $FW tcp 22,1599,1600,1601Assume that you forward port 22 from external IP address
206.124.146.178 to internal system 192.168.1.5. In
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST
DNAT- net 192.168.1.5 tcp 22 - 206.124.146.178
SSHKnock net $FW tcp 1599,1600,1601
SSHKnock net loc:192.168.1.5 tcp 22 - 206.124.146.178You can use SSHKnock with DNAT on earlier releases provided
that you omit the ORIGDEST entry on the second SSHKnock rule. This
rule will be quite secure provided that you specify 'routefilter' on
your external interface and have NULL_ROUTE_RFC1918=Yes in
shorewall.conf.For another way to implement Port Knocking, see the Manual Chain documentation.Limiting Per-IP Connection RateThis information has been moved to the Actions article.
shorewall-docs-xml-5.2.3/QOSExample.xml 0000664 0000000 0000000 00000037736 13427347317 016500 0 ustar root root
QOS ConfigurationTomEastep2012Thomas 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 configuration was inspired by the one in this thread on the
OpenWRT Forum: https://forum.openwrt.org/viewtopic.php?pid=154533#p154533.
The configuration has been adapted to Shorewall 4.5.6 with the following
changes:The configuration uses an IFB, yet only uses firewall marks in
the OUTPUT and FORWARD chains to classify packets; clearly that
doesn't workTo be more precise, it doesn't work with an unpatched
kernel. The OpenWRT script assumes an 'act_conntrack' patch which
performs conntrack processing on packets before they are sent to
the IFB. That patch is not generally available.The configuration presented here uses U32 classifiers
(shorewall-tcfilters(5)) to classify traffic for download shaping and
uses the POSTROUTING chain for upload shaping.The sample uses a weak form of P2P classification; the one
presented below uses IPP2P.The OpenWRT script assumed that the uplink was ATM -- the one
below makes no assumption (it specifies 'ethernet' with overhead
'0')./etc/shorewall/paramsThe shell variables set in the OpenWRT script are set in the
Shorewall params file:# local network
MYNET=192.168.0.0/24
DOWNLOAD=40000 #download speed in kbit. set xx% of real download speed
UPLOAD=7000 # set xx% of real upload speed
# multiports = up to 15 ports
# ports to be classified as bulk #set after connection mark save and after connection mark restore
TCP_BULK="1024:" #S and D ports
UDP_BULK="1024:" #S and D ports
# Destination ports to be classified as P2P
TCP_P2P="13769" #D ports
UDP_P2P="13769" #D ports
IP_P2P="192.168.0.133"
# Destination ports to be classified as normal
TCP_NORMAL="80,443,25,20,21,110,993,995" # D ports
UDP_NORMAL=""
# Destination ports to be classified as Prio (overules bulk ports)
TCP_PRIO="22,53" #destination ports
UDP_PRIO="22,53" #destination ports
# Destination ports to be classified as VoIP (overules bulk ports)
TCP_VOIP=""
UDP_VOIP="18080"
IP_VOIP="192.168.0.226" #destination and source IP
IP_VOIP="192.168.0.226" #destination and source IP
#!!!!!uplink leaf class parameters!!!!!!!!!
#bulk
UP_LS_BULK_RATE=$(($UPLOAD*5/100))
UP_UL_BULK_RATE=$UPLOAD
#settings leaf qdisc
UP_BULK_RED_PROB=0.05 #red drob probability
UP_BULK_RED_min=6250 #real limit. To limit BULK traffic
UP_BULK_RED_min2=6250 #min for doing the calculations (burst and etc)
UP_BULK_RED_max=$((2 * $UP_BULK_RED_min2 + $UP_BULK_RED_min))
UP_BULK_RED_burst=$(((5 * $UP_BULK_RED_min2) / (3 * 1000)))
UP_BULK_RED_limit=$(($UP_BULK_RED_max * 5))
#P2P
UP_LS_P2P_RATE=$(($UPLOAD * 5 / 100))
UP_UL_P2P_RATE=$UPLOAD
#settings leaf qdisc
UP_P2P_RED_PROB=0.05 #red drob probability
UP_P2P_RED_min=32000 #real limit. To limit P2P traffic
UP_P2P_RED_min2=32000 #min for doing the calculations (burst and etc)
UP_P2P_RED_max=$((5 * $UP_P2P_RED_min2 + $UP_P2P_RED_min))
UP_P2P_RED_burst=$(((5 * $UP_P2P_RED_min2) / (3 * 1000)))
UP_P2P_RED_limit=$(($UP_P2P_RED_max * 5))
#normal class
UP_LS_NORMAL_RATE=$(($UPLOAD * 40 / 100))
UP_UL_NORMAL_RATE=$UPLOAD
#settings leaf qdisc
UP_NORMAL_RED_PROB=0.05 #red drob probability
UP_NORMAL_RED_min=6250 #real limit. To limit NORMAL traffic
UP_NORMAL_RED_min2=6250 #min for doing the calculations (burst and etc)
UP_NORMAL_RED_max=$((2 * $UP_NORMAL_RED_min2 + $UP_NORMAL_RED_min))
UP_NORMAL_RED_burst=$(((5 * $UP_NORMAL_RED_min2) / (3 * 1000)))
UP_NORMAL_RED_limit=$(($UP_NORMAL_RED_max * 5))
#prio
UP_LS_PRIO_RATE=$(($UPLOAD*50/100))
UP_RT_PRIO_RATE="200" #rate in kbit
UP_RT_PRIO_UMAX="400" #lengte of the packets [byte]
UP_RT_PRIO_DMAX="15" #delay in ms
UP_UL_PRIO_RATE=$UPLOAD
#Voip
UP_UL_VOIP_RATE=$UPLOAD
UP_SC_VOIP_RATE="200"
UP_SC_VOIP_UMAX="350" #length of the voip packets [byte]
UP_SC_VOIP_DMAX="10" #delay in ms
#bulk
DOWN_LS_BULK_RATE=$(($DOWNLOAD*5/100))
DOWN_UL_BULK_RATE=$DOWNLOAD
#leaf qdisc parameters
DOWN_BULK_RED_PROB=0.05 #red drob probability
DOWN_BULK_RED_min=62500 #real limit. To limit BULK traffic
DOWN_BULK_RED_min2=62500 #min for doing the calculations (burst and etc)
DOWN_BULK_RED_max=$((2 * $DOWN_BULK_RED_min2 + $DOWN_BULK_RED_min))
DOWN_BULK_RED_burst=$(((5 * $DOWN_BULK_RED_min2) / (3 * 1000)))
DOWN_BULK_RED_limit=$(($DOWN_BULK_RED_max * 5))
#P2P
DOWN_LS_P2P_RATE=$(($DOWNLOAD*5/100))
DOWN_UL_P2P_RATE=4000
#leaf qdisc parameters
DOWN_P2P_RED_PROB=0.05 #red drob probability
DOWN_P2P_RED_min=200000 #real limit. To limit P2P traffic
DOWN_P2P_RED_min2=200000 #min for doing the calculations (burst and etc)
DOWN_P2P_RED_max=$((2 * $DOWN_P2P_RED_min2 + $DOWN_P2P_RED_min))
DOWN_P2P_RED_burst=$(((5 * $DOWN_P2P_RED_min2) / (3 * 1000)))
DOWN_P2P_RED_limit=$(($DOWN_P2P_RED_max * 5))
#normal class
DOWN_LS_NORMAL_RATE=$(($DOWNLOAD*75/100))
DOWN_UL_NORMAL_RATE=$DOWNLOAD
#leaf qdisc parameters
DOWN_NORMAL_RED_PROB=0.05 #red drob probability
DOWN_NORMAL_RED_min=62500 #real limit. To limit NORMAL traffic
DOWN_NORMAL_RED_min2=62500 #min for doing the calculations (burst and etc)
DOWN_NORMAL_RED_max=$((2 * $DOWN_NORMAL_RED_min2 + $DOWN_NORMAL_RED_min))
DOWN_NORMAL_RED_burst=$(((5 * $DOWN_NORMAL_RED_min2) / (3 * 1000)))
DOWN_NORMAL_RED_limit=$(($DOWN_NORMAL_RED_max * 5))
#prio
DOWN_RT_PRIO_RATE="500" #rate in kbit
DOWN_RT_PRIO_UMAX="400" #length of the packets [byte]/
DOWN_RT_PRIO_DMAX="1.5" #delay in ms
DOWN_UL_PRIO_RATE=$DOWNLOAD
#Voip
DOWN_UL_VOIP_RATE=$DOWNLOAD
DOWN_SC_VOIP_RATE="250"
DOWN_SC_VOIP_UMAX="350" #lengt of voip packets [byte]
DOWN_SC_VOIP_DMAX="1.2" #delay in ms/etc/shorewall/initThe init file loads the ifb module, creating a single device:modprobe ifb numifbs=1
ip link set ifb0 up/etc/shorewall/tcdevicesThe tcdevices file describes the two devices:#NUMBER: IN_BANDWITH OUT_BANDWIDTH OPTIONS REDIRECT
1:eth0 - ${UPLOAD}kbit hfsc,linklayer=ethernet,overhead=0
2:ifb0 - ${DOWNLOAD}kbit hfsc eth0/etc/shorewall/tcclassesThe tcclasses file defines the class hierarchy for both
devices:#INTERFACE MARK RATE CEIL PRIORITY OPTIONS
1 1 ${UP_SC_VOIP_RATE}kbit:\
${UP_SC_VOIP_DMAX}:\
${UP_SC_VOIP_UMAX} ${UP_UL_VOIP_RATE}kbit 1
1 2 ${UP_RT_PRIO_RATE}kbit:\
${UP_RT_PRIO_DMAX}:\
${UP_RT_PRIO_UMAX} ${UP_LS_PRIO_RATE}kbit:\
${UP_UL_PRIO_RATE}kbit 1
1 3 - ${UP_LS_NORMAL_RATE}kbit:\
${UP_UL_NORMAL_RATE}kbit 1 red=(limit=$UP_NORMAL_RED_limit,\
min=$UP_NORMAL_RED_min,\
max=$UP_NORMAL_RED_max,\
burst=$UP_NORMAL_RED_burst,\
probability=$UP_NORMAL_RED_PROB,\
ecn)
1 4 - ${UP_LS_P2P_RATE}kbit:\
${UP_UL_P2P_RATE}kbit 1 red=(limit=$UP_P2P_RED_limit,\
min=$UP_P2P_RED_min,\
max=$UP_P2P_RED_max,\
burst=$UP_P2P_RED_burst,\
probability=$UP_P2P_RED_PROB,\
ecn)
1 5 - ${UP_LS_BULK_RATE}kbit:\
${UP_UL_BULK_RATE}kbit 1 default,\
red=(limit=$UP_BULK_RED_limit,\
min=$UP_BULK_RED_min,\
max=$UP_BULK_RED_max,\
burst=$UP_BULK_RED_burst,\
probability=$UP_BULK_RED_PROB,\
ecn)
2:10 - ${UP_SC_VOIP_RATE}kbit:\
${UP_SC_VOIP_DMAX}:\
${UP_SC_VOIP_UMAX} ${UP_UL_VOIP_RATE}kbit 1
2:20 - ${DOWN_RT_PRIO_RATE}kbit:\
${DOWN_RT_PRIO_DMAX}:\
${DOWN_RT_PRIO_UMAX} ${DOWN_UL_PRIO_RATE}kbit 1
2:30 - - ${DOWN_LS_NORMAL_RATE}kbit:\
${DOWN_UL_NORMAL_RATE}kbit 1 red=(limit=$DOWN_NORMAL_RED_limit,\
min=$DOWN_NORMAL_RED_min,\
max=$DOWN_NORMAL_RED_max,\
burst=$DOWN_NORMAL_RED_burst,\
probability=$DOWN_NORMAL_RED_PROB)
2:40 - - ${DOWN_LS_P2P_RATE}kbit:\
${DOWN_UL_P2P_RATE}kbit 1 red=(limit=$DOWN_P2P_RED_limit,\
min=$DOWN_P2P_RED_min,\
max=$DOWN_P2P_RED_max,\
burst=$DOWN_P2P_RED_burst,\
probability=$DOWN_P2P_RED_PROB)
2:50 - - ${DOWN_LS_BULK_RATE}kbit:\
${DOWN_UL_BULK_RATE}kbit 1 default,\
red=(limit=$DOWN_BULK_RED_limit,\
min=$DOWN_BULK_RED_min,\
max=$DOWN_BULK_RED_max,\
burst=$DOWN_BULK_RED_burst,\
probability=$DOWN_BULK_RED_PROB)/etc/shorewall/mangleThe mangle file classifies upload packets:#MARK SOURCE DEST PROTO DPORT SPORT USER TEST
RESTORE:T - - - - - - !0:C
CONTINUE:T - - - - - - !0
2:T - - icmp
1:T - - udp $UDP_VOIP - - 0
1:T $IP_VOIP - - - - - 0
1:T - $IP_VOIP - - - - 0
2:T - - tcp $TCP_PRIO - - 0
2:T - - udp $UDP_PRIO - - 0
2:T - - tcp - $TCP_PRIO - 0
2:T - - udp - $UDP_PRIO - 0
3:T - - tcp $TCP_NORMAL - - 0
4:T - - ipp2p:all - - - 0
5:T - - tcp $TCP_BULK - - 0
5:T - - tcp - $TCP_BULK - 0
5:T - - udp $UDP_BULK - - 0
5:T - - udp - $UDP_BULK - 0
SAVE:T - - - - - - !0/etc/shorewall/tcfiltersThe tcfilters file classifies download packets:#INTERFACE: SOURCE DEST PROTO DPORT SPORT TOS LENGTH
#
# These classify download traffic
#
2:10 - $MYNET udp - $UDP_VOIP
2:20 - $MYNET tcp - $TCP_PRIO
2:20 - $MYNET udp - $UDP_PRIO
2:20 - $MYNET tcp $TCP_PRIO
2:20 - $MYNET udp $UDP_PRIO
2:30 - $MYNET tcp - $TCP_NORMAL
2:50 - $MYNET tcp $TCP_BULK
2:50 - $MYNET tcp - $TCP_BULK
2:50 - $MYNET udp $UDP_BULK
2:50 - $MYNET tcp - $UDP_BULK
shorewall-docs-xml-5.2.3/UPnP.xml 0000664 0000000 0000000 00000012374 13427347317 015333 0 ustar root root
Shorewall and UPnPTomEastep200520102013Thomas 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.UPnPShorewall includes support for UPnP (Universal Plug and Play) using
linux-igd (http://linux-igd.sourceforge.net).
UPnP is required by a number of popular applications including MSN
IM.From a security architecture viewpoint, UPnP is a disaster. It
assumes that:All local systems and their users are completely
trustworthy.No local system is infected with any worm or trojan.If either of these assumptions are not true then UPnP can be used
to totally defeat your firewall and to allow incoming connections to
arbitrary local systems on any port whatsoever. In short: USE UPnP
AT YOUR OWN RISK.Shorewall and linux-igd implement a UPnP Internet
Gateway Device. It will not allow clients on one LAN subnet
to access a UPnP Media Server on another subnet.linux-igd ConfigurationIn /etc/upnpd.conf, you will want:create_forward_rules = yes
prerouting_chain_name = UPnP
forward_chain_name = forwardUPnPShorewall ConfigurationIn /etc/shorewall/interfaces, you need the
'upnp' option on your external interface.Example:#ZONE INTERFACE OPTIONS
net eth1 dhcp,routefilter,tcpflags,upnpIf your loc->fw policy is not ACCEPT then you need this
rule:#ACTION SOURCE DEST
allowinUPnP loc $FWYou MUST have this rule:#ACTION SOURCE DEST
forwardUPnP net locYou must also ensure that you have a route to 224.0.0.0/4 on your
internal (local) interface as described in the linux-igd
documentation.The init script included with the Debian linux-idg package adds
this route during start and deletes it during
stop.Shorewall versions prior to 4.4.10 do not retain the dynamic rules
added by linux-idg over a shorewall restart.If your firewall->loc policy is not ACCEPT, then you also need to
allow UDP traffic from the fireawll to the local zone.ACCEPT $FW loc udp - <dynamic port range>The dynamic port range is obtained by cat
/proc/sys/net/ip_local_port_range.Shorewall on a UPnP ClientIt is sometimes desirable to run UPnP-enabled client programs like
Transmission
(BitTorrent client) on a Shorewall-protected system. Shorewall provides
support for UPnP client access in the form of the upnpclient option in shorewall-interfaces
(5).The upnpclient option causes
Shorewall to detect the default gateway through the interface and to
accept UDP packets from that gateway. Note that, like all aspects of UPnP,
this is a security hole so use this option at your own risk.Note that when multiple clients behind the firewall use UPnP, they
must configure their applications to use unique ports.
shorewall-docs-xml-5.2.3/IPIP.xml 0000664 0000000 0000000 00000013642 13427347317 015251 0 ustar root root
GRE and IPIP TunnelsTomEastep20012002200320042005Thomas 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.GRE and IPIP Tunnels are insecure when used over the Internet; use
them at your own riskGRE and IPIP tunneling with Shorewall can be used to bridge two
masqueraded networks.The simple scripts described in the Linux Advanced Routing and Shaping
HOWTO work fine with Shorewall. Shorewall also includes
a tunnel script for automating tunnel configuration. If you have installed
the RPM, the tunnel script may be found in the Shorewall documentation
directory (usually /usr/share/doc/shorewall-<version>/).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.The tunnel script is not installed in /etc/shorewall
by default -- If you install using the tarball, the script is included in
the tarball; if you install using the RPM, the file is in your Shorewall
documentation directory (normally
/usr/share/doc/shorewall-<version>).In the /etc/shorewall/tunnel script, set the
tunnel_type parameter to the type of tunnel that you want
to create./etc/shorewall/tunneltunnel_type=greIf you use the PPTP connection tracking modules from Netfilter
Patch-O-Matic (ip_conntrack_proto_gre ip_conntrack_pptp,
ip_nat_proto_gre and ip_nat_pptp) then you cannot use GRE
tunnels.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 OPTIONS
vpn tosysbIn /etc/shorewall/tunnels on system A, we need the following:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipip net 134.28.54.2This entry in /etc/shorewall/tunnels, opens the firewall so that the
IP encapsulation protocol (4) will be accepted to/from the remote
gateway.In the tunnel script on system A:tunnel script on system Atunnel=tosysb
myrealip=206.161.148.9 (for GRE tunnel only)
myip=192.168.1.1
hisip=10.0.0.1
gateway=134.28.54.2
subnet=10.0.0.0/8
Similarly, On system B the 192.168.1.0/24 subnet will comprise the
vpn zone. In
/etc/shorewall/interfaces:#ZONE INTERFACE
vpn tosysaIn /etc/shorewall/tunnels on system B, we have:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipip net 206.191.148.9And in the tunnel script on system B:tunnel script on system Btunnel=tosysa
myrealip=134.28.54.2 (for GRE tunnel only)
myip=10.0.0.1
hisip=192.168.1.1
gateway=206.191.148.9
subnet=192.168.1.0/24You can rename the modified tunnel scripts if you like; be sure that
they are secured so that root can execute them.You 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 run the modified tunnel
script with the start argument on each system. The systems
in the two masqueraded subnetworks can now talk to each other
shorewall-docs-xml-5.2.3/quotes.xml 0000664 0000000 0000000 00000017030 13427347317 016023 0 ustar root root
Quotes from UsersTomEastep20032004Thomas 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.What Users are saying...
AS, PolandI want to say that Shorewall documentation is the best
I've ever found on the net. It's helped me a lot in understanding how
network is working. It is the best of breed. It contains not only
Shorewall specific topics with the assumption that all the rest is well
known, but also gives some very useful background information. Thank you
very much for this wonderful piece of work.
ES, Phoenix AZ, USAI have fought with IPtables for untold hours. First I
tried the SUSE firewall, which worked for 80% of what I needed. Then
gShield, which also worked for 80%. Then I set out to write my own
IPtables parser in shell and awk, which was a lot of fun but never got
me past the hey, cool stage. Then I discovered Shorewall.
After about an hour, everything just worked. I am stunned, and very
grateful
SE, California, USAIn two words, I'd call Shorewall "brilliant simplicity".
Define general rules of what it is you want to do, and let the software
determine the specific rules on how to implement it. It's great only
having to define specific rules for specific instances. I have a much
higher degree of confidence in my firewall than I have had previously.
Thank you for Shorewall!.
BC, USAThe configuration is intuitive and flexible, and much
easier than any of the other iptables-based firewall programs out there.
After sifting through many other scripts, it is obvious that yours is
the most well thought-out and complete one available.
JL, OhioI just installed Shorewall after weeks of messing with
ipchains/iptables and I had it up and running in under 20
minutes!
JV, SpainMy case was almost like [the one above]. Well. instead
of weeks it was months for me, and I think
I needed two minutes more:One to see that I had no Internet access from the
firewall itself.Other to see that this was the default
configuration, and it was enough to uncomment a line in
/etc/shorewall/policy.Minutes instead of months! Congratulations and thanks
for such a simple and well documented thing for something as huge as
iptables
MMI downloaded Shorewall 1.2.0 and installed it on
Mandrake 8.1 without any problems. Your documentation is great and I
really appreciate your network configuration info. That really helped me
out alot. THANKS!!!
B.R, Netherlands[Shorewall is a] great, great project. I've used/tested
may firewall scripts but this one is till now the
best.
Mario Kerecki, TorontoNever in my +12 year career as a sys admin have I
witnessed someone so relentless in developing a secure, state of the
art, safe and useful product as the Shorewall firewall package for no
cost or obligation involved.
SM, Germanyone time more to report, that your great shorewall in
the latest release 1.2.9 is working fine for me with SUSE Linux 7.3! I
now have 7 machines up and running with shorewall on several versions -
starting with 1.2.2 up to the new 1.2.9 and I never have encountered any
problems!
SE, USYou have the best support of any other package I've ever
used.
Name withheld by request, EuropeBecause our company has information which has been
classified by the national government as secret, our security doesn't
stop by putting a fence around our company. Information security is a
hot issue. We also make use of checkpoint firewalls, but not all of the
Internet servers are guarded by checkpoint, some of them are
running....Shorewall.
RM, Austriathanx for all your efforts you put into shorewall - this
product stands out against a lot of commercial stuff i´ve been working
with in terms of flexibility, quality & support
RG, TorontoI have never seen such a complete firewall package that
is so easy to configure. I searched the Debian package system for
firewall scripts and Shorewall won hands down.
RP, GuatemalaMy respects... I've just found and installed Shorewall
1.3.3-1 and it is a wonderful piece of software. I've just sent out an
email to about 30 people recommending it. :-)While I had previously taken the time (maybe 40 hours)
to really understand ipchains, then spent at least an hour per server
customizing and carefully scrutinizing firewall rules, I've got
shorewall running on my home firewall, with rule sets and policies that I
know make sense, in under 20 minutes.
shorewall-docs-xml-5.2.3/kernel.xml 0000664 0000000 0000000 00000037004 13427347317 015766 0 ustar root root
Kernel ConfigurationTomEastep2001-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 is
unmaintained.Network Options ConfigurationHere's a screen shot of my Network Options Configuration:While not all of the options that I've selected are required, they
should be sufficient for most applications. Here's an excerpt from the
corresponding .config file (Note: If you are running a kernel older than
2.4.17, be sure to select CONFIG_NETLINK and CONFIG_RTNETLINK):
#
# Networking options
#
CONFIG_PACKET=y
# CONFIG_PACKET_MMAP is not set
# CONFIG_NETLINK_DEV is not set
CONFIG_NETFILTER=y
# CONFIG_NETFILTER_DEBUG is not set
CONFIG_FILTER=y
CONFIG_UNIX=y
CONFIG_INET=y
CONFIG_IP_MULTICAST=y
CONFIG_IP_ADVANCED_ROUTER=y
CONFIG_IP_MULTIPLE_TABLES=y
CONFIG_IP_ROUTE_FWMARK=y
CONFIG_IP_ROUTE_NAT=y
CONFIG_IP_ROUTE_MULTIPATH=y
CONFIG_IP_ROUTE_TOS=y
CONFIG_IP_ROUTE_VERBOSE=y
# CONFIG_IP_ROUTE_LARGE_TABLES is not set
# CONFIG_IP_PNP is not set
CONFIG_NET_IPIP=y
CONFIG_NET_IPGRE=y
# CONFIG_NET_IPGRE_BROADCAST is not set
# CONFIG_IP_MROUTE is not set
# CONFIG_ARPD is not set
CONFIG_INET_ECN=y
CONFIG_SYN_COOKIES=y
Netfilter ConfigurationHere's a screen shot of my Netfilter configuration:Note that I have built everything I need as modules. You can also
build everything into your kernel but if you want to be able to deal with
FTP running on a non-standard port then you must modularize FTP Protocol support.Here's the corresponding part of my .config file:
#
# IP: Netfilter Configuration
#
CONFIG_IP_NF_CONNTRACK=m
CONFIG_IP_NF_FTP=m
CONFIG_IP_NF_AMANDA=m
CONFIG_IP_NF_TFTP=m
# CONFIG_IP_NF_IRC is not set
# CONFIG_IP_NF_QUEUE is not set
CONFIG_IP_NF_IPTABLES=m
CONFIG_IP_NF_MATCH_LIMIT=m
CONFIG_IP_NF_MATCH_MAC=m
CONFIG_IP_NF_MATCH_PKTTYPE=m
CONFIG_IP_NF_MATCH_MARK=m
CONFIG_IP_NF_MATCH_MULTIPORT=m
CONFIG_IP_NF_MATCH_TOS=m
CONFIG_IP_NF_MATCH_ECN=m
CONFIG_IP_NF_MATCH_DSCP=m
CONFIG_IP_NF_MATCH_AH_ESP=m
CONFIG_IP_NF_MATCH_LENGTH=m
# CONFIG_IP_NF_MATCH_TTL is not set
CONFIG_IP_NF_MATCH_TCPMSS=m
CONFIG_IP_NF_MATCH_HELPER=m
CONFIG_IP_NF_MATCH_STATE=m
CONFIG_IP_NF_MATCH_CONNTRACK=m
CONFIG_IP_NF_MATCH_UNCLEAN=m
# CONFIG_IP_NF_MATCH_OWNER is not set
CONFIG_IP_NF_FILTER=m
CONFIG_IP_NF_TARGET_REJECT=m
# CONFIG_IP_NF_TARGET_MIRROR is not set
CONFIG_IP_NF_NAT=m
CONFIG_IP_NF_NAT_NEEDED=y
CONFIG_IP_NF_TARGET_MASQUERADE=m
CONFIG_IP_NF_TARGET_REDIRECT=m
CONFIG_IP_NF_NAT_AMANDA=m
CONFIG_IP_NF_NAT_LOCAL=y
# CONFIG_IP_NF_NAT_SNMP_BASIC is not set
CONFIG_IP_NF_NAT_FTP=m
CONFIG_IP_NF_NAT_TFTP=m
CONFIG_IP_NF_MANGLE=m
CONFIG_IP_NF_TARGET_TOS=m
CONFIG_IP_NF_TARGET_ECN=m
CONFIG_IP_NF_TARGET_DSCP=m
CONFIG_IP_NF_TARGET_MARK=m
CONFIG_IP_NF_TARGET_LOG=m
CONFIG_IP_NF_TARGET_ULOG=m
CONFIG_IP_NF_TARGET_TCPMSS=m
CONFIG_IP_NF_ARPTABLES=m
CONFIG_IP_NF_ARPFILTER=m
# CONFIG_IP_NF_COMPAT_IPCHAINS is not set
# CONFIG_IP_NF_COMPAT_IPFWADM is not set
Kernel 2.6 Netfilter OptionsHere's a screenshot of my modularized 2.6 Kernel config (Navigation:
Device Drivers → Networking Support → Networking Options → Network Packet
Filtering (replaces ipchains) → IP: Netfilter configuration):Here is the corresponding part of the .config file:
CONFIG_IP_NF_CONNTRACK=m
CONFIG_IP_NF_FTP=m
CONFIG_IP_NF_IRC=m
CONFIG_IP_NF_TFTP=m
CONFIG_IP_NF_AMANDA=m
CONFIG_IP_NF_QUEUE=m
CONFIG_IP_NF_IPTABLES=m
CONFIG_IP_NF_MATCH_LIMIT=m
CONFIG_IP_NF_MATCH_IPRANGE=m
CONFIG_IP_NF_MATCH_MAC=m
CONFIG_IP_NF_MATCH_PKTTYPE=m
CONFIG_IP_NF_MATCH_MARK=m
CONFIG_IP_NF_MATCH_MULTIPORT=m
CONFIG_IP_NF_MATCH_TOS=m
CONFIG_IP_NF_MATCH_RECENT=m
CONFIG_IP_NF_MATCH_ECN=m
CONFIG_IP_NF_MATCH_DSCP=m
CONFIG_IP_NF_MATCH_AH_ESP=m
CONFIG_IP_NF_MATCH_LENGTH=m
CONFIG_IP_NF_MATCH_TTL=m
CONFIG_IP_NF_MATCH_TCPMSS=m
CONFIG_IP_NF_MATCH_HELPER=m
CONFIG_IP_NF_MATCH_STATE=m
CONFIG_IP_NF_MATCH_CONNTRACK=m
CONFIG_IP_NF_MATCH_OWNER=m
CONFIG_IP_NF_MATCH_PHYSDEV=m
CONFIG_IP_NF_FILTER=m
CONFIG_IP_NF_TARGET_REJECT=m
CONFIG_IP_NF_NAT=m
CONFIG_IP_NF_NAT_NEEDED=y
CONFIG_IP_NF_TARGET_MASQUERADE=m
CONFIG_IP_NF_TARGET_REDIRECT=m
CONFIG_IP_NF_TARGET_NETMAP=m
CONFIG_IP_NF_TARGET_SAME=m
CONFIG_IP_NF_NAT_LOCAL=y
CONFIG_IP_NF_NAT_SNMP_BASIC=m
CONFIG_IP_NF_NAT_IRC=m
CONFIG_IP_NF_NAT_FTP=m
CONFIG_IP_NF_NAT_TFTP=m
CONFIG_IP_NF_NAT_AMANDA=m
CONFIG_IP_NF_MANGLE=m
CONFIG_IP_NF_TARGET_TOS=m
CONFIG_IP_NF_TARGET_ECN=m
CONFIG_IP_NF_TARGET_DSCP=m
CONFIG_IP_NF_TARGET_MARK=m
CONFIG_IP_NF_TARGET_CLASSIFY=m
CONFIG_IP_NF_TARGET_LOG=m
CONFIG_IP_NF_TARGET_ULOG=m
CONFIG_IP_NF_TARGET_TCPMSS=m
# CONFIG_IP_NF_ARPTABLES is not set
# CONFIG_IP_NF_COMPAT_IPCHAINS is not set
# CONFIG_IP_NF_COMPAT_IPFWADM is not set
# CONFIG_IP_NF_RAW is not set
CONFIG_IP_NF_MATCH_ADDRTYPE=m
# CONFIG_IP_NF_MATCH_REALM is not set
CONFIG_IP6_NF_QUEUE=m
CONFIG_IP6_NF_IPTABLES=m
CONFIG_IP6_NF_MATCH_LIMIT=m
CONFIG_IP6_NF_MATCH_MAC=m
CONFIG_IP6_NF_MATCH_RT=m
CONFIG_IP6_NF_MATCH_OPTS=m
CONFIG_IP6_NF_MATCH_FRAG=m
CONFIG_IP6_NF_MATCH_HL=m
CONFIG_IP6_NF_MATCH_MULTIPORT=m
CONFIG_IP6_NF_MATCH_OWNER=m
CONFIG_IP6_NF_MATCH_MARK=m
CONFIG_IP6_NF_MATCH_IPV6HEADER=m
CONFIG_IP6_NF_MATCH_AHESP=m
CONFIG_IP6_NF_MATCH_LENGTH=m
CONFIG_IP6_NF_MATCH_EUI64=m
CONFIG_IP6_NF_FILTER=m
CONFIG_IP6_NF_TARGET_LOG=m
CONFIG_IP6_NF_MANGLE=m
CONFIG_IP6_NF_TARGET_MARK=m
# CONFIG_IP6_NF_RAW is not set
CONFIG_DECNET_NF_GRABULATOR=m
CONFIG_BRIDGE_NF_EBTABLES=m
Kernel 2.6.16 and Later Netfilter OptionsHere's a screenshot of my modularized 2.6.16 Kernel config
(Navigation: Networking → Networking Options → Network Packet Filtering
(replaces ipchains) → Core Netfilter configuration):Note that is is particularly important to select "Netfilter Xtables
support (required for ip_tables).Here's a screenshot of the IP Netfilter config (Navigation:
Networking → Networking Options → Network Packet Filtering (replaces
ipchains) → IP: Netfilter configuration):Here is the corresponding part of the .config file:
Kernel 2.6.20 and Later Netfilter OptionsBeginning with kernel 2.6.20, the Netfilter kernel configuration was
completely changed. It is split into "Core Netfilter Configuration" and
"IP Netfilter Configuration". The first graphic shows the link to the
Netfilter configuration from the "Networking Options" menu:The next graphic show the Core Configuration settings - these are
the standard Ubuntu setting with the exception of CONNMARK Target support
(Ubuntu inexplicably includes connmark match support but not CONNTRACK
target support).The next graphic shows the IP
Netfilter Configuration -- these are the standard Ubuntu settings.Here is the
corresponding CONFIG file excerpt.CONFIG_NETFILTER_XT_TARGET_CLASSIFY=m
CONFIG_NETFILTER_XT_TARGET_CONNMARK=m
CONFIG_NETFILTER_XT_TARGET_DSCP=m
CONFIG_NETFILTER_XT_TARGET_MARK=m
CONFIG_NETFILTER_XT_TARGET_NFQUEUE=m
CONFIG_NETFILTER_XT_TARGET_NFLOG=m
# CONFIG_NETFILTER_XT_TARGET_NOTRACK is not set
CONFIG_NETFILTER_XT_TARGET_SECMARK=m
CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=m
CONFIG_NETFILTER_XT_MATCH_COMMENT=m
CONFIG_NETFILTER_XT_MATCH_CONNBYTES=m
CONFIG_NETFILTER_XT_MATCH_CONNMARK=m
CONFIG_NETFILTER_XT_MATCH_CONNTRACK=m
CONFIG_NETFILTER_XT_MATCH_DCCP=m
CONFIG_NETFILTER_XT_MATCH_DSCP=m
CONFIG_NETFILTER_XT_MATCH_ESP=m
CONFIG_NETFILTER_XT_MATCH_HELPER=m
CONFIG_NETFILTER_XT_MATCH_LENGTH=m
CONFIG_NETFILTER_XT_MATCH_LIMIT=m
CONFIG_NETFILTER_XT_MATCH_MAC=m
CONFIG_NETFILTER_XT_MATCH_MARK=m
CONFIG_NETFILTER_XT_MATCH_POLICY=m
CONFIG_NETFILTER_XT_MATCH_MULTIPORT=m
CONFIG_NETFILTER_XT_MATCH_PHYSDEV=m
CONFIG_NETFILTER_XT_MATCH_PKTTYPE=m
CONFIG_NETFILTER_XT_MATCH_QUOTA=m
CONFIG_NETFILTER_XT_MATCH_REALM=m
CONFIG_NETFILTER_XT_MATCH_SCTP=m
CONFIG_NETFILTER_XT_MATCH_STATE=m
CONFIG_NETFILTER_XT_MATCH_STATISTIC=m
CONFIG_NETFILTER_XT_MATCH_STRING=m
CONFIG_NETFILTER_XT_MATCH_TCPMSS=m
CONFIG_NETFILTER_XT_MATCH_HASHLIMIT=m
CONFIG_NF_CONNTRACK_SUPPORT=y
CONFIG_NF_CONNTRACK_ENABLED=m
# CONFIG_IP_NF_CONNTRACK_SUPPORT is not set
CONFIG_NF_CONNTRACK=m
CONFIG_NF_CT_ACCT=y
CONFIG_NF_CONNTRACK_MARK=y
CONFIG_NF_CONNTRACK_SECMARK=y
CONFIG_NF_CONNTRACK_EVENTS=y
CONFIG_NF_CT_PROTO_GRE=m
CONFIG_NF_CT_PROTO_SCTP=m
CONFIG_NF_CONNTRACK_AMANDA=m
CONFIG_NF_CONNTRACK_FTP=m
CONFIG_NF_CONNTRACK_H323=m
CONFIG_NF_CONNTRACK_IRC=m
CONFIG_NF_CONNTRACK_NETBIOS_NS=m
CONFIG_NF_CONNTRACK_PPTP=m
CONFIG_NF_CONNTRACK_SIP=m
CONFIG_NF_CONNTRACK_TFTP=m
CONFIG_NF_CT_NETLINK=m
CONFIG_NF_CONNTRACK_IPV4=m
CONFIG_NF_CONNTRACK_PROC_COMPAT=y
CONFIG_IP_NF_QUEUE=m
CONFIG_IP_NF_IPTABLES=m
CONFIG_IP_NF_MATCH_IPRANGE=m
CONFIG_IP_NF_MATCH_TOS=m
CONFIG_IP_NF_MATCH_RECENT=m
CONFIG_IP_NF_MATCH_ECN=m
CONFIG_IP_NF_MATCH_AH=m
CONFIG_IP_NF_MATCH_TTL=m
CONFIG_IP_NF_MATCH_OWNER=m
CONFIG_IP_NF_MATCH_ADDRTYPE=m
CONFIG_IP_NF_FILTER=m
CONFIG_IP_NF_TARGET_REJECT=m
CONFIG_IP_NF_TARGET_LOG=m
CONFIG_IP_NF_TARGET_ULOG=m
CONFIG_IP_NF_TARGET_TCPMSS=m
CONFIG_NF_NAT=m
CONFIG_NF_NAT_NEEDED=y
CONFIG_IP_NF_TARGET_MASQUERADE=m
CONFIG_IP_NF_TARGET_REDIRECT=m
CONFIG_IP_NF_TARGET_NETMAP=m
CONFIG_IP_NF_TARGET_SAME=m
CONFIG_NF_NAT_SNMP_BASIC=m
CONFIG_NF_NAT_PROTO_GRE=m
CONFIG_NF_NAT_FTP=m
CONFIG_NF_NAT_IRC=m
CONFIG_NF_NAT_TFTP=m
CONFIG_NF_NAT_AMANDA=m
CONFIG_NF_NAT_PPTP=m
CONFIG_NF_NAT_H323=m
CONFIG_NF_NAT_SIP=m
CONFIG_IP_NF_MANGLE=m
CONFIG_IP_NF_TARGET_TOS=m
CONFIG_IP_NF_TARGET_ECN=m
CONFIG_IP_NF_TARGET_TTL=m
CONFIG_IP_NF_TARGET_CLUSTERIP=m
CONFIG_IP_NF_RAW=m
CONFIG_IP_NF_ARPTABLES=m
CONFIG_IP_NF_ARPFILTER=m
CONFIG_IP_NF_ARP_MANGLE=m
Minimal Configuration using Kernel 2.6.20 and laterMassimo Burcheri has contributed this minimal configuration which is
suitable for securing a laptop or desktop. It is strictly a "no-frills"
configuration and represents the minimum that will work with Shorewall
when using only the very basic Shorewall features described in the one-interface quickstart guide.Here are the
corresponding entries from the .config file:# Networking
#
CONFIG_NET=y
#
# Networking options
#
# CONFIG_NETDEBUG is not set
CONFIG_PACKET=y
CONFIG_UNIX=y
CONFIG_INET=y
CONFIG_IP_FIB_HASH=y
CONFIG_TCP_CONG_CUBIC=y
CONFIG_DEFAULT_TCP_CONG="cubic"
#
# IP: Virtual Server Configuration
#
CONFIG_NETFILTER=y
#
# Core Netfilter Configuration
#
CONFIG_NETFILTER_NETLINK=m
CONFIG_NETFILTER_NETLINK_QUEUE=m
CONFIG_NETFILTER_NETLINK_LOG=m
CONFIG_NF_CONNTRACK_ENABLED=m
CONFIG_NF_CONNTRACK_SUPPORT=y
CONFIG_NF_CONNTRACK=m
CONFIG_NETFILTER_XTABLES=m
CONFIG_NETFILTER_XT_TARGET_MARK=m
CONFIG_NETFILTER_XT_MATCH_MAC=m
CONFIG_NETFILTER_XT_MATCH_MULTIPORT=m
CONFIG_NETFILTER_XT_MATCH_PKTTYPE=m
CONFIG_NETFILTER_XT_MATCH_STATE=m
#
# IP: Netfilter Configuration
#
CONFIG_NF_CONNTRACK_IPV4=m
CONFIG_NF_CONNTRACK_PROC_COMPAT=y
CONFIG_IP_NF_IPTABLES=m
CONFIG_IP_NF_MATCH_ADDRTYPE=m
CONFIG_IP_NF_FILTER=m
CONFIG_IP_NF_TARGET_REJECT=m
CONFIG_IP_NF_TARGET_LOG=m
CONFIG_IP_NF_MANGLE=m
CONFIG_IP_NF_ARPTABLES=m
CONFIG_IP_NF_ARPFILTER=m
shorewall-docs-xml-5.2.3/MyNetwork.xml 0000664 0000000 0000000 00000114105 13427347317 016443 0 ustar root root
My Network ConfigurationTomEastep20092015Thomas 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.The ruleset shown in this article uses Shorewall features that are
not available in Shorewall versions prior to 4.6.11IntroductionThe configuration described in this article represents the network
at shorewall.org during the summer of 2015. It uses the following
Shorewall features:Two Internet
InterfacesA DMZ with three "systems" using Proxy
ARP and running in Linux Containers
(LXC)IPv6 Access through two 6to4
TunnelsIpsetsTransparent proxy using
SquidLinux runs the firewall and the servers (although they run in LXC
containers on the firewall system). Linux is not used natively on any of
our other systems.. I rather run Windows natively (Windows 7 Professional)
and run Linux in VMs under VirtualBox.
This approach has a number of advantages:Efficient disk utilization.The virtual disks used by Linux are just files in the NTFS file
system. There is no need to pre-allocate one or more partitions for
use by Linux. Some large applications, like Google Earth, are
installed only on Windows.Avoids proprietary hardware issues.The Linux VMs emulate standard hardware that is well-supported
by Linux.Avoids DRM hasslesAll DRM-protected media can be handled under Windows.VirtualBox is fast (when your processor supports virtualization
extensions) and very easy to use. I highly recommend it!Network TopologyOur network is diagrammed in the following graphic.We have two accounts with Comcast:ComcastCThis is a high-speed (40mb/8mb) link with a single dynamic IPv4
address. We are not allowed to run servers accessible through this
account.ComcastBComcast Business Class Service with a /29
(70.90.191.120/29).The wired local network is restricted to my home office. The
wireless network is managed by a wireless router which we use only as an
access point -- its WAN interface is unused and it is configured to not do
NAT. The wireless network uses WPA2 personal security.Shorewall ConfigurationThis section contains excerpts from the Shorewall
configuration./etc/shorewall/mirrorsMIRRORS=62.216.169.37,\
62.216.184.105,\
63.229.2.114,\
...Defines the IP addresses of the Shorewall mirror sites./etc/shorewall/paramsINCLUDE mirrors
LOG="NFLOG(0,0,1)"
INT_IF=eth0
TUN_IF=tun+
COMB_IF=eth2
COMC_IF=eth1
MYNET=70.90.191.120/29 #External IP addresses handled by this router
DMZ_NET=70.90.191.124/31
FW_NET=70.90.191.120/30
INT_NET=172.20.1.0/24
DYN_NET=$(find_first_interface_address_if_any $COMC_IF)
SMC_ADDR=10.1.10.11
[ -n "${DYN_NET:=67.170.122.219}" ]
DYN_NET=${DYN_NET}/32
DMZ=fw:$DMZ_NET
LISTS=:70.90.191.124
SERVER=:70.90.191.125
MAIL=172.20.1.200
PROXY=Yes
STATISTICAL=Yes
SQUID2=Yes
[ -n "${EXPERIMENTAL:=0}" ]
As shown, this file defines variables to hold the various
lists of IP addresses that I need to maintain. To simplify network
reconfiguration, I also use variables to define the log level and the
network interfaces./etc/shorewall/shorewall.conf###############################################################################
# S T A R T U P E N A B L E D
###############################################################################
STARTUP_ENABLED=Yes
###############################################################################
# V E R B O S I T Y
###############################################################################
VERBOSITY=1
###############################################################################
# L O G G I N G
###############################################################################
BLACKLIST_LOG_LEVEL=none
INVALID_LOG_LEVEL=
LOG_BACKEND=ULOG
LOG_MARTIANS=Yes
LOG_VERBOSITY=1
LOGALLNEW=
LOGFILE=/var/log/ulogd/ulogd.syslogemu.log
LOGFORMAT=": %s %s"
LOGTAGONLY=Yes
LOGLIMIT="s:5/min"
MACLIST_LOG_LEVEL="$LOG"
RELATED_LOG_LEVEL="$LOG"
RPFILTER_LOG_LEVEL=info
SFILTER_LOG_LEVEL="$LOG"
SMURF_LOG_LEVEL="$LOG"
STARTUP_LOG=/var/log/shorewall-init.log
TCP_FLAGS_LOG_LEVEL="$LOG"
UNTRACKED_LOG_LEVEL=
###############################################################################
# L O C A T I O N O F F I L E S A N D D I R E C T O R I E S
###############################################################################
ARPTABLES=
CONFIG_PATH="/etc/shorewall:/etc/shorewall-common:/usr/share/shorewall:/usr/share/shorewall/Shorewall"
GEOIPDIR=/usr/share/xt_geoip/LE
IPTABLES=/sbin/iptables
IP=/sbin/ip
IPSET=
LOCKFILE=/var/lib/shorewall/lock
MODULESDIR=
NFACCT=
PATH="/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin"
PERL=/usr/bin/perl
RESTOREFILE=
SHOREWALL_SHELL=/bin/bash
SUBSYSLOCK=
TC=
###############################################################################
# D E F A U L T A C T I O N S / M A C R O S
###############################################################################
ACCEPT_DEFAULT=none
DROP_DEFAULT=Drop
NFQUEUE_DEFAULT=none
QUEUE_DEFAULT=none
REJECT_DEFAULT=Reject
###############################################################################
# R S H / R C P C O M M A N D S
###############################################################################
RCP_COMMAND='scp ${files} ${root}@${system}:${destination}'
RSH_COMMAND='ssh ${root}@${system} ${command}'
###############################################################################
# F I R E W A L L O P T I O N S
###############################################################################
ACCOUNTING=Yes
ACCOUNTING_TABLE=mangle
ADD_IP_ALIASES=No
ADD_SNAT_ALIASES=No
ADMINISABSENTMINDED=Yes
BASIC_FILTERS=No
IGNOREUNKNOWNVARIABLES=No
AUTOCOMMENT=Yes
AUTOHELPERS=Yes
AUTOMAKE=Yes
BLACKLIST="NEW,INVALID,UNTRACKED"
CHAIN_SCRIPTS=No
CLAMPMSS=Yes
CLEAR_TC=Yes
COMPLETE=No
DEFER_DNS_RESOLUTION=No
DELETE_THEN_ADD=No
DETECT_DNAT_IPADDRS=No
DISABLE_IPV6=No
DONT_LOAD="nf_nat_sip,nf_conntrack_sip,nf_conntrack_h323,nf_nat_h323"
DYNAMIC_BLACKLIST=Yes
EXPAND_POLICIES=Yes
EXPORTMODULES=Yes
FASTACCEPT=Yes
FORWARD_CLEAR_MARK=Yes
HELPERS="ftp,irc"
IMPLICIT_CONTINUE=No
INLINE_MATCHES=Yes
IPSET_WARNINGS=No
IP_FORWARDING=Yes
KEEP_RT_TABLES=Yes
LEGACY_FASTSTART=Yes
LOAD_HELPERS_ONLY=Yes
MACLIST_TABLE=mangle
MACLIST_TTL=60
MANGLE_ENABLED=Yes
MAPOLDACTIONS=No
MARK_IN_FORWARD_CHAIN=No
MODULE_SUFFIX="ko ko.xz"
MULTICAST=No
MUTEX_TIMEOUT=60
NULL_ROUTE_RFC1918=unreachable
OPTIMIZE=All
OPTIMIZE_ACCOUNTING=No
REJECT_ACTION=RejectAct
REQUIRE_INTERFACE=No
RESTORE_DEFAULT_ROUTE=No
RESTORE_ROUTEMARKS=Yes
RETAIN_ALIASES=No
ROUTE_FILTER=No
SAVE_ARPTABLES=Yes
SAVE_IPSETS=ipv4
TC_ENABLED=No
TC_EXPERT=No
TC_PRIOMAP="2 3 3 3 2 3 1 1 2 2 2 2 2 2 2 2"
TRACK_PROVIDERS=Yes
TRACK_RULES=No
USE_DEFAULT_RT=Yes
USE_PHYSICAL_NAMES=Yes
USE_RT_NAMES=Yes
WARNOLDCAPVERSION=Yes
WORKAROUNDS=No
ZONE2ZONE=-
###############################################################################
# P A C K E T D I S P O S I T I O N
###############################################################################
BLACKLIST_DISPOSITION=DROP
INVALID_DISPOSITION=CONTINUE
MACLIST_DISPOSITION=ACCEPT
RELATED_DISPOSITION=REJECT
RPFILTER_DISPOSITION=DROP
SMURF_DISPOSITION=DROP
SFILTER_DISPOSITION=DROP
TCP_FLAGS_DISPOSITION=DROP
UNTRACKED_DISPOSITION=DROP
################################################################################
# P A C K E T M A R K L A Y O U T
################################################################################
TC_BITS=8
PROVIDER_BITS=2
PROVIDER_OFFSET=16
MASK_BITS=8
ZONE_BITS=0
################################################################################
# L E G A C Y O P T I O N
# D O N O T D E L E T E O R A L T E R
################################################################################
IPSECFILE=zonesI don't believe that there is anything
remarkable there/etc/shorewall/actionsMirrors # Accept traffic from Shorewall Mirrors
SSHLIMIT
SSH_BL
tarpit inline # Wrapper for TARPIT
/etc/shorewall/action.Mirrors#TARGET SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE
?COMMENT Accept traffic from Mirrors
?FORMAT 2
DEFAULTS -
$1 $MIRRORS
I make this into an action so the rather long list of rules
go into their own chain. See the rules file
-- this action is used for rsync traffic./etc/shorewall/action.tarpit#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER MARK CONNLIMIT TIME HEADERS SWITCH HELPER
$LOG { rate=s:1/min }
TARPIT
/etc/shorewall/zones#ZONE TYPE
fw firewall
loc ip #Local Zone
net ipv4 #Internet
dmz ipv4 #LXC Containers
smc:net ip #10.0.1.0/24
/etc/shorewall/interfaces#ZONE INTERFACE OPTIONS
loc INT_IF dhcp,physical=$INT_IF,ignore=1,wait=5,routefilter,nets=172.20.1.0/24,routeback,tcpflags=0
net COMB_IF optional,sourceroute=0,routefilter=0,arp_ignore=1,proxyarp=0,physical=$COMB_IF,upnp,nosmurfs,tcpflags
net COMC_IF optional,sourceroute=0,routefilter=0,arp_ignore=1,proxyarp=0,physical=$COMC_IF,upnp,nosmurfs,tcpflags,dhcp
dmz br0 routeback,proxyarp=1,required,wait=30
- ifb0 ignore
/etc/shorewall/hosts#ZONE HOST(S) OPTIONS
smc COMB_IF:10.1.10.0/24 mss=1400
smc COMC_IF:10.0.0.0/24
/etc/shorewall/policy#SOURCE DEST POLICY LOGLEVEL LIMIT
$FW dmz REJECT $LOG
$FW net REJECT $LOG
?else
$FW dmz REJECT $LOG
$FW net REJECT $LOG
$FW all ACCEPT
smc loc ACCEPT
smc fw CONTINUE
smc net NONE
loc smc ACCEPT
loc net ACCEPT
loc fw REJECT $LOG
net net NONE
net smc NONE
net all DROP:Drop $LOG 8/sec:30
dmz fw REJECT:Reject $LOG
all all REJECT:Reject $LOG
/etc/shorewall/accounting#ACTION CHAIN SOURCE DESTINATION PROTO DPORT SPORT USER MARK IPSEC
?COMMENT
?SECTION PREROUTING
?SECTION INPUT
ACCOUNT(fw-net,$FW_NET) - COMB_IF
COUNT - COMB_IF - tcp - 80
COUNT - COMC_IF - tcp - 80
COUNT - br0:70.90.191.124 - tcp 80 =
?SECTION OUTPUT
ACCOUNT(fw-net,$FW_NET) - - COMB_IF
COUNT - - COMB_IF tcp 80
COUNT - - COMC_IF tcp 80
?SECTION FORWARD
ACCOUNT(dmz-net,$DMZ_NET) - br0 COMB_IF
ACCOUNT(dmz-net,$DMZ_NET) - COMB_IF br0
ACCOUNT(loc-net,$INT_NET) - COMB_IF INT_IF
ACCOUNT(loc-net,$INT_NET) - INT_IF COMB_IF
/etc/shorewall/blrules#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER MARK CONNLIMIT TIME HEADERS SWITCH
WHITELIST net:70.90.191.126 all
BLACKLIST net:+blacklist all
BLACKLIST net all udp 1023:1033,1434,5948,23773
DROP net all tcp 57,1433,1434,2401,2745,3127,3306,3410,4899,5554,5948,6101,8081,9898,23773
DROP net:63.149.127.103 all
DROP net:175.143.53.113 all
DROP net:121.134.248.190 all
REJECT net:188.176.145.22 dmz tcp 25
DROP net fw udp 111
Invalid(DROP) net all/etc/shorewall/findgwif [ -f /var/lib/dhcpcd/dhcpcd-eth1.info ]; then
. /var/lib/dhcpcd/dhcpcd-eth1.info
echo $GATEWAY
fi
The Comcast line has a dynamic IP address assigned with the
help of dhclient./etc/shorewall/isusablelocal status
status=0
[ -f /etc/shorewall/${1}.status ] && status=$(cat /etc/shorewall/${1}.status)
return $statusFor use with lsm./etc/shorewall/lib.privatestart_lsm() {
#
# Kill any existing lsm process(es)
#
killall lsm 2> /dev/null
#
# Create the Shorewall-specific part of the LSM configuration. This file is
# included by /etc/lsm/lsm.conf
#
# ComcastB has a static gateway while ComcastC's is dynamic
#
cat <<EOF > /etc/lsm/shorewall.conf
connection {
name=ComcastB
checkip=76.28.230.1
device=$COMB_IF
ttl=2
}
connection {
name=ComcastC
checkip=76.28.230.188
device=$COMC_IF
ttl=3
}
EOF
cat <<EOF > /var/lib/shorewall/eth0.info
ETH0_GATEWAY=$SW_ETH0_GATEWAY
ETH0_ADDRESS=$SW_ETH0_ADDRESS
EOF
#
# Clear status on start
#
if [ $COMMAND = start ]; then
for interface in eth0 eth1; do
echo 0 > ${VARDIR}/$interface.status
done
fi
#
# Run LSM -- by default, it forks into the background
#
/usr/local/sbin/lsm /etc/lsm/lsm.conf >> /var/log/lsm
}This function configures and starts lsm./etc/shorewall/masq#INTERFACE SOURCE ADDRESS PROTO
?COMMENT Use the SMC's local net address when communicating with that net
COMB_IF:10.1.10.0/24 0.0.0.0/0 %{SMC_ADDR}
?COMMENT Masquerade Local Network
COMB_IF !70.90.191.120/29 70.90.191.121 ; -m statistic --mode random --probability 0.50
COMB_IF !70.90.191.120/29 70.90.191.123
COMC_IF 0.0.0.0/0
#INT_IF:172.20.1.15 172.20.1.0/24 172.20.1.254
br0 70.90.191.120/29 70.90.191.121 tcp 80
I split connections out of COMB_IF between the two IP
addresses configured on the interface./etc/shorewall/conntrack?FORMAT 2
#ACTION SOURCE DEST PROTO DPORT SPORT
#
DROP net - udp 3551
NOTRACK net - tcp 23
NOTRACK loc 172.20.1.255 udp
NOTRACK loc 255.255.255.255 udp
NOTRACK $FW 255.255.255.255 udp
NOTRACK $FW 172.20.1.255 udp
NOTRACK $FW 70.90.191.127 udp
NOTRACK net:192.88.99.1 -
NOTRACK $FW 192.88.99.1
?if $AUTOHELPERS
?if __CT_TARGET && __AMANDA_HELPER
CT:helper:amanda all - udp 10080
?endif
?if __CT_TARGET && __FTP_HELPER
CT:helper:ftp all - tcp 21
?endif
?if __CT_TARGET && __H323_HELPER
CT:helper:RAS all - udp 1719
CT:helper:Q.931 all - tcp 1720
?endif
?if __CT_TARGET && __IRC_HELPER
CT:helper:irc all - tcp 6667
?endif
?if __CT_TARGET && __NETBIOS_NS_HELPER
CT:helper:netbios-ns all - udp 137
?endif
?if __CT_TARGET && __PPTP_HELPER
CT:helper:pptp all - tcp 1729
?endif
?if __CT_TARGET && __SANE_HELPER
CT:helper:sane all - tcp 6566
?endif
#?if __CT_TARGET && __SIP_HELPER
#CT:helper:sip all - udp 5060
#?endif
?if __CT_TARGET && __SNMP_HELPER
CT:helper:snmp all - udp 161
?endif
?if __CT_TARGET && __TFTP_HELPER
CT:helper:tftp all - udp 69
?endif
?endif
This file omits the 6to4 traffic originating from 6to4 relays
as well as broadcast traffic (which Netfilter doesn't handle)./etc/shorewall/providers#NAME NUMBER MARK DUPLICATE INTERFACE GATEWAY OPTIONS COPY
?IF $STATISTICAL
ComcastB 1 0x10000 - COMB_IF 70.90.191.126 loose,load=0.66666667,fallback
ComcastC 2 0x20000 - COMC_IF detect loose,load=0.33333333
?ELSE
ComcastB 1 0x10000 - COMB_IF 70.90.191.126 nohostroute,loose,balance=2
ComcastC 2 0x20000 - COMC_IF detect nohostroute,loose,balance
?ENDIF
?IF $PROXY && ! $SQUID2
TProxy 3 - - lo - tproxy
?ENDIF
root@gateway:/etc/shorewall#
See the Multi-ISP article for an
explaination of the multi-ISP aspects of this configuration./etc/shorewall/proxyarp<empty>As mentioned above, I set the proxyarp on the associated
external interface instead of defining proxy ARP in this file./etc/shorewall/restoredif [ -z "$(ps ax | grep 'lsm ' | grep -v 'grep ' )" ]; then
start_lsm
fi
chmod 744 ${VARDIR}/stateIf lsm isn't running then start it.
Make the state file world-readable./etc/shorewall/rtrules#SOURCE DEST PROVIDER PRIORITY
70.90.191.121,\
70.90.191.123 - ComcastB 1000
&COMC_IF - ComcastC 1000
br0 - ComcastB 11000
172.20.1.191 - ComcastB 1000These
entries simply ensure that outgoing traffic uses the correct
interface./etc/shorewall/stoppedrules#TARGET HOST(S) DEST PROTO DPORT SPORT
ACCEPT INT_IF:172.20.1.0/24 $FW
NOTRACK COMB_IF - 41
NOTRACK $FW COMB_IF 41
ACCEPT COMB_IF $FW 41
ACCEPT COMC_IF $FW udp 67:68Keep
the lights on while Shorewall is stopped./etc/shorewall/rules################################################################################################################################################################################################
#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER MARK CONNLIMIT TIME HEADERS SWITCH
?if $VERSION < 40500
?SHELL echo " ERROR: Shorewall version is too low" >&2; exit 1
?endif
?begin perl
1;
?end perl
?SECTION ALL
#ACCEPT net:smc.shorewall.net $FW
#RST(LOG) all all
?SECTION ESTABLISHED
#SSH(REJECT) net loc:1.2.3.4 { time=timestart=18:48 }
?SECTION RELATED
ACCEPT all dmz:70.90.191.125 tcp 61001:62000 { helper=ftp }
ACCEPT dmz all tcp { helper=ftp }
ACCEPT all net tcp { helper=ftp }
ACCEPT all all icmp
RST(ACCEPT) all all tcp
ACCEPT dmz dmz
ACCEPT $FW all
?SECTION INVALID
DROP net all
?SECTION UNTRACKED
ACCEPT net:192.88.99.1 $FW 41
tarpit net all tcp 23
Broadcast(ACCEPT)\
all $FW
ACCEPT all $FW udp
CONTINUE loc $FW
CONTINUE $FW all
?SECTION NEW
DNSAmp(ACCEPT) loc fw
REJECT:$LOG loc net tcp 25 #Stop direct loc->net SMTP (Comcast uses submission).
REJECT:$LOG loc net udp 1025:1031 #MS Messaging
?COMMENT Stop NETBIOS crap
REJECT all net tcp 137,445
REJECT all net udp 137:139
?COMMENT Disallow port 333
REJECT all net tcp 3333
?COMMENT Stop Teredo
REJECT all net udp 3544
?COMMENT Stop my idiotic work laptop from sending to the net with an HP source IP address
{ action=DROP, source=loc:!172.20.0.0/22, dest=net } #
?COMMENT
#dropInvalid net all tcp
################################################################################################################################################################################################
# Local network to DMZ
#
DNAT loc dmz:70.90.191.125 tcp www - 70.90.191.123
ACCEPT loc dmz tcp ssh,smtp,465,548,587,www,ftp,imaps,https,5901:5903
ACCEPT loc dmz udp 3478:3479,33434:33524
################################################################################################################################################################################################
# SMC network to DMZ
#
ACCEPT smc dmz tcp ssh,smtp,465,587,www,ftp,imaps,https,5901:5903
ACCEPT smc dmz udp 33434:33524
################################################################################################################################################################################################
# SMC network to LOC
#
################################################################################################################################################################################################
# Local Network to Firewall
#
?IF $SQUID2
REDIRECT loc 3128 tcp 80 {origdest="!172.20.1.0/24,70.90.191.120/29,155.98.64.80,81.19.16.0/21,10.1.10.1"}
?ENDIF
ACCEPT loc fw udp 53,111,123,177,192,631,1024:
SMB(ACCEPT) loc fw
ACCEPT loc fw tcp 22,53,80,111,229,548,2049,3000,32765:61000
ACCEPT loc fw tcp 3128
mDNS(ACCEPT) loc fw
ACCEPT loc fw tcp 5001
ACCEPT loc:172.20.2.149 fw tcp 3551 #APCUPSD
################################################################################################################################################################################################
# SMC Network to Firewall
#
ACCEPT smc fw udp 53,111,123,177,192,631,1024:
SMB(ACCEPT) smc fw
ACCEPT smc fw tcp 22,53,111,548,2049,3000,3128,32765:32768,49152
mDNS(ACCEPT) smc fw
################################################################################################################################################################################################
# SMC Network to multiple destinations
#
Ping(ACCEPT) smc dmz,fw
################################################################################################################################################################################################
# Local Network to Internet
#REJECT:info loc net tcp 80,443
################################################################################################################################################################################################
# Local Network to multiple destinations
#
Ping(ACCEPT) loc dmz,fw
################################################################################################################################################################################################
# Internet to ALL -- drop NewNotSyn packets
#
dropNotSyn net fw,loc,smc tcp
AutoBL(SSH,60,-,-,-,-,$LOG)\
net all tcp 22
################################################################################################################################################################################################
# Internet to DMZ
#
ACCEPT net dmz udp 33434:33454
ACCEPT net dmz tcp 25 - - smtp:2/min:4,mail:60/min:100
DNAT- net 70.90.191.125 tcp https - 70.90.191.123
DNAT- net 70.90.191.125 tcp http - 70.90.191.123
DNAT- all 172.20.2.44 tcp ssh - 70.90.191.123
ACCEPT net dmz:70.90.191.122 tcp https,imaps
ACCEPT net dmz:70.90.191.124 tcp http,https,465,587,imaps
ACCEPT net dmz:70.90.191.125 tcp http,ftp
Mirrors(ACCEPT:none)\ #Continuation test
net dmz tcp 873
Ping(ACCEPT) net dmz
DROP net dmz tcp http,https
################################################################################################################################################################################################
#
# UPnP
#
ACCEPT loc fw udp 1900
forwardUPnP net loc
#
# Silently Handle common probes
#
REJECT net loc tcp www,ftp,https
DROP net loc icmp 8
################################################################################################################################################################################################
# DMZ to DMZ
#
################################################################################################################################################################################################
DNAT dmz dmz:70.90.191.125:80 tcp 80 - 70.90.191.121
# DMZ to Internet
#
ACCEPT dmz net udp ntp,domain
ACCEPT dmz net tcp domain,echo,ftp,ssh,smtp,whois,www,81,nntp,https,993,465,587,2401,2702,2703,5901,8080,9418,11371
#
# 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
Ping(ACCEPT) dmz all
################################################################################################################################################################################################
# DMZ to fw
#
DNS(ACCEPT) dmz $FW
HTTP(ACCEPT) dmz $FW
Ping(ACCEPT) dmz $FW
################################################################################################################################################################################################
# Internet to Firewall
#
REJECT net fw tcp www,ftp,https
ACCEPT net fw udp 3478:3479,33434:33454
ACCEPT net fw tcp 22 - - s:ssh:1/min:3
ACCEPT net fw tcp 51413
?COMMENT IPv6 tunnel ping
ACCEPT net fw:70.90.191.121,70.90.191.122/31\
icmp 8
ACCEPT net:COMC_IF fw icmp 8
?COMMENT
################################################################################################################################################################################################
# Firewall to DMZ
#
ACCEPT fw dmz tcp www,ftp,ssh,smtp,https,465,587,993,3128,5901
REJECT fw dmz udp 137:139
Ping(ACCEPT) fw dmz
################################################################################################################################################################################################
# Firewall to NET
#
DNS(ACCEPT) fw net
NTP(ACCEPT) fw net
DNAT- fw 172.20.1.254:3128 tcp 80 - - - !:proxy
ACCEPT+ fw net tcp 43,80,443,3466 - - - -
ACCEPT fw net tcp 3128 - - - !:proxy
FTP(ACCEPT) fw net - - - - - proxy
Git(ACCEPT) fw net - - - - - teastep
ACCEPT fw net tcp 22
NNTP(ACCEPT) fw net
Ping(ACCEPT) fw net
ACCEPT fw net udp 33434:33524
#ACCEPT:info fw net - - - - - root
ACCEPT fw net tcp 25,143,993 - - - teastep
################################################################################################################################################################################################
#
?COMMENT Freenode Probes
DROP net:\
82.96.96.3,\
85.190.0.3 any!loc,smc
?COMMENT
################################################################################################################################################################################################
/etc/shorewall/startedif [ "$COMMAND" = start -o -z "$(ps ax | grep 'lsm ' | grep -v 'grep ' )" ]; then
start_lsm
fi
If lsm isn't running then start it./etc/shorewall/stoppedif [ "$COMMAND" = stop -o "$COMMAND" = clear ]; then
killall lsm 2> /dev/null
fi
chmod 744 ${VARDIR}/stateKill lsm if the command is stop or
clear. Make the state file world-readable./etc/shorewall/tunnels#TYPE ZONE GATEWAY GATEWAY
# ZONE
6to4 net 216.218.226.238
6to4 net 192.88.99.1
shorewall-docs-xml-5.2.3/template.xml 0000664 0000000 0000000 00000002116 13427347317 016315 0 ustar root root
TomEastep2017Thomas 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-docs-xml-5.2.3/survey-200603.xml 0000664 0000000 0000000 00000050766 13427347317 016605 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.2.3/SharedConfig.xml 0000664 0000000 0000000 00000112156 13427347317 017044 0 ustar root root
Shared Shorewall and Shorewall6 ConfigurationTomEastep2017Thomas 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.IntroductionNetfilter separates management of IPv4 and IPv6 configurations. Each
address family has its own utility (iptables and ip6tables), and changes
made to the configuration of one address family do not affect the other.
While Shorewall also separates the address families in this way, it is
possible for Shorewall and Shorewall6 to share almost all of the
configuration files. This article gives an example.What is shown here currently works best with Debian and
derivatives, or when the tarball installer is used and the SPARSE option
is enabled when running configure[.pl].EnvironmentIn this example, each address family has two Internet interfaces.
Both address families share a fast uplink (eth0) that has a single public
IPv4 address, but can delegate IPv6 subnets to the Shorewall-based router.
Both address families also have a production uplink. For IPv4, Ethernet is
used (eth1) and supports the public IPv4 subnet 70.90.191.120/29. For
IPv6, a Hurricane Electric 6in4 tunnel is used (sit1), which provides the
public IPv6 subnet 2001:470:b:227::/64. The router also has two bridges. A
DMZ bridge (br0) provides access to containers running a web server, a
mail exchanger, and an IMAPS mail access server. The second bridge (br1)
provides access to a container running irssi under screen, allowing
constant access to and monitoring of IRC channels.Here is a diagram of this installation:ConfigurationHere are the contents of /etc/shorewall/ and /etc/shorewal6/:root@gateway:~# ls -l /etc/shorewall/
total 92
-rw-r--r-- 1 root root 201 Mar 19 2017 action.Mirrors
-rw-r--r-- 1 root root 109 Oct 20 09:18 actions
-rw-r--r-- 1 root root 654 Oct 13 13:46 conntrack
-rw-r--r-- 1 root root 104 Oct 13 13:21 hosts
-rw-r--r-- 1 root root 867 Jul 1 10:50 interfaces
-rw-r--r-- 1 root root 107 Jun 29 15:14 isusable
-rw-r--r-- 1 root root 240 Oct 13 13:34 macro.FTP
-rw-r--r-- 1 root root 559 Oct 19 12:56 mangle
-rw-r--r-- 1 root root 1290 Jun 29 15:16 mirrors
-rw-r--r-- 1 root root 2687 Oct 15 14:20 params
-rw-r--r-- 1 root root 738 Oct 15 12:16 policy
-rw-r--r-- 1 root root 1838 Oct 11 08:29 providers
-rw-r--r-- 1 root root 398 Mar 18 2017 proxyarp
-rw-r--r-- 1 root root 738 Nov 8 09:34 routes
-rw-r--r-- 1 root root 729 Nov 7 12:52 rtrules
-rw-r--r-- 1 root root 6367 Oct 13 13:21 rules
-rw-r--r-- 1 root root 5520 Oct 19 10:01 shorewall.conf
-rw-r--r-- 1 root root 1090 Oct 25 15:17 snat
-rw-r--r-- 1 root root 181 Jun 29 15:12 started
-rw-r--r-- 1 root root 435 Oct 13 13:21 tunnels
-rw-r--r-- 1 root root 941 Oct 15 11:27 zones
root@gateway:~# ls -l /etc/shorewall6/
total 8
lrwxrwxrwx 1 root root 20 Jul 6 16:35 mirrors -> ../shorewall/mirrors
lrwxrwxrwx 1 root root 19 Jul 6 12:48 params -> ../shorewall/params
-rw-r--r-- 1 root root 5332 Oct 14 11:53 shorewall6.conf
root@gateway:~#
The various configuration files are described in the sections that
follow. Note that in all cases, these files use the alternate format for column
specification./usr/share/shorewall/shorewallrcThe key setting here is SPARSE=Very#
# Created by Shorewall Core version 5.0.12-RC1 configure.pl - Sep 25 2016 09:30:55
# rc file: shorewallrc.debian.systemd
#
HOST=debian
PREFIX=/usr
SHAREDIR=${PREFIX}/share
LIBEXECDIR=${PREFIX}/share
PERLLIBDIR=${PREFIX}/share/shorewall
CONFDIR=/etc
SBINDIR=/sbin
MANDIR=${PREFIX}/share/man
INITDIR=
INITSOURCE=init.debian.sh
INITFILE=
AUXINITSOURCE=
AUXINITFILE=
SERVICEDIR=/lib/systemd/system
SERVICEFILE=$PRODUCT.service.debian
SYSCONFFILE=default.debian
SYSCONFDIR=/etc/default
SPARSE=Very
ANNOTATED=
VARLIB=/var/lib
VARDIR=${VARLIB}/$PRODUCT
DEFAULT_PAGER=/usr/bin/less
shorewall.conf and shorewall6.confThese are the only files that are not shared between the two
address families. The key setting is CONFIG_PATH in
shorewall6.conf:CONFIG_PATH="${CONFDIR}/shorewall6:${CONFDIR}/shorewall:/usr/share/shorewall6:${SHAREDIR}/shorewall"/etc/shorewall6/ is only used for processing
the params and shorewall6.conf
files.shorewall.confThe contents of /etc/shorewall/shorewall.conf are as
follows:###############################################################################
#
# Shorewall Version 5 -- /etc/shorewall/shorewall.conf
#
# For information about the settings in this file, type "man shorewall.conf"
#
# Manpage also online at http://www.shorewall.net/manpages/shorewall.conf.html
###############################################################################
# S T A R T U P E N A B L E D
###############################################################################
STARTUP_ENABLED=Yes
###############################################################################
# V E R B O S I T Y
###############################################################################
VERBOSITY=1
###############################################################################
# P A G E R
###############################################################################
PAGER=pager
###############################################################################
# F I R E W A L L
###############################################################################
FIREWALL=
###############################################################################
# L O G G I N G
###############################################################################
LOG_LEVEL="NFLOG(0,64,1)"
BLACKLIST_LOG_LEVEL="none"
INVALID_LOG_LEVEL=
LOG_BACKEND=netlink
LOG_MARTIANS=Yes
LOG_VERBOSITY=1
LOGALLNEW=
LOGFILE=/var/log/ulogd/ulogd.syslogemu.log
LOGFORMAT=": %s %s"
LOGTAGONLY=Yes
LOGLIMIT="s:5/min"
MACLIST_LOG_LEVEL="$LOG_LEVEL"
RELATED_LOG_LEVEL="$LOG_LEVEL:,related"
RPFILTER_LOG_LEVEL="$LOG_LEVEL:,rpfilter"
SFILTER_LOG_LEVEL="$LOG_LEVEL"
SMURF_LOG_LEVEL="$LOG_LEVEL"
STARTUP_LOG=/var/log/shorewall-init.log
TCP_FLAGS_LOG_LEVEL="$LOG_LEVEL"
UNTRACKED_LOG_LEVEL=
###############################################################################
# L O C A T I O N O F F I L E S A N D D I R E C T O R I E S
###############################################################################
ARPTABLES=
CONFIG_PATH="/etc/shorewall:/usr/share/shorewall:/usr/share/shorewall/Shorewall"
GEOIPDIR=/usr/share/xt_geoip/LE
IPTABLES=/sbin/iptables
IP=/sbin/ip
IPSET=
LOCKFILE=/var/lib/shorewall/lock
MODULESDIR="+extra/RTPENGINE"
NFACCT=
PATH="/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin"
PERL=/usr/bin/perl
RESTOREFILE=
SHOREWALL_SHELL=/bin/sh
SUBSYSLOCK=
TC=
###############################################################################
# D E F A U L T A C T I O N S / M A C R O S
###############################################################################
ACCEPT_DEFAULT="none"
BLACKLIST_DEFAULT="NotSyn(DROP):$LOG_LEVEL"
DROP_DEFAULT="Broadcast(DROP),Multicast(DROP)"
NFQUEUE_DEFAULT="none"
QUEUE_DEFAULT="none"
REJECT_DEFAULT="Broadcast(DROP),Multicast(DROP)"
###############################################################################
# R S H / R C P C O M M A N D S
###############################################################################
RCP_COMMAND='scp ${files} ${root}@${system}:${destination}'
RSH_COMMAND='ssh ${root}@${system} ${command}'
###############################################################################
# F I R E W A L L O P T I O N S
###############################################################################
ACCOUNTING=Yes
ACCOUNTING_TABLE=mangle
ADD_IP_ALIASES=No
ADD_SNAT_ALIASES=No
ADMINISABSENTMINDED=Yes
AUTOCOMMENT=Yes
AUTOHELPERS=No
AUTOMAKE=Yes
BALANCE_PROVIDERS=No
BASIC_FILTERS=No
BLACKLIST="NEW,INVALID,UNTRACKED"
CLAMPMSS=Yes
CLEAR_TC=Yes
COMPLETE=No
DEFER_DNS_RESOLUTION=No
DELETE_THEN_ADD=No
DETECT_DNAT_IPADDRS=No
DISABLE_IPV6=No
DOCKER=No
DONT_LOAD="nf_nat_sip,nf_conntrack_sip,nf_conntrack_h323,nf_nat_h323"
DYNAMIC_BLACKLIST="ipset-only,disconnect,timeout=7200"
EXPAND_POLICIES=Yes
EXPORTMODULES=Yes
FASTACCEPT=Yes
FORWARD_CLEAR_MARK=No
HELPERS="ftp,irc"
IGNOREUNKNOWNVARIABLES=No
IMPLICIT_CONTINUE=No
INLINE_MATCHES=Yes
IPSET_WARNINGS=Yes
IP_FORWARDING=Yes
KEEP_RT_TABLES=Yes
LOAD_HELPERS_ONLY=Yes
MACLIST_TABLE=filter
MACLIST_TTL=60
MANGLE_ENABLED=Yes
MAPOLDACTIONS=No
MARK_IN_FORWARD_CHAIN=No
MINIUPNPD=No
MULTICAST=No
MUTEX_TIMEOUT=60
NULL_ROUTE_RFC1918=unreachable
OPTIMIZE=All
OPTIMIZE_ACCOUNTING=No
PERL_HASH_SEED=12345
REJECT_ACTION=
REQUIRE_INTERFACE=No
RESTART=restart
RESTORE_DEFAULT_ROUTE=No
RESTORE_ROUTEMARKS=Yes
RETAIN_ALIASES=No
ROUTE_FILTER=No
SAVE_ARPTABLES=No
SAVE_IPSETS=ipv4
TC_ENABLED=No
TC_EXPERT=No
TC_PRIOMAP="2 3 3 3 2 3 1 1 2 2 2 2 2 2 2 2"
TRACK_PROVIDERS=Yes
TRACK_RULES=No
USE_DEFAULT_RT=Yes
USE_NFLOG_SIZE=Yes
USE_PHYSICAL_NAMES=Yes
USE_RT_NAMES=Yes
VERBOSE_MESSAGES=No
WARNOLDCAPVERSION=Yes
WORKAROUNDS=No
ZERO_MARKS=No
ZONE2ZONE=-
###############################################################################
# P A C K E T D I S P O S I T I O N
###############################################################################
BLACKLIST_DISPOSITION=DROP
INVALID_DISPOSITION=CONTINUE
MACLIST_DISPOSITION=ACCEPT
RELATED_DISPOSITION=REJECT
RPFILTER_DISPOSITION=DROP
SMURF_DISPOSITION=DROP
SFILTER_DISPOSITION=DROP
TCP_FLAGS_DISPOSITION=DROP
UNTRACKED_DISPOSITION=DROP
################################################################################
# P A C K E T M A R K L A Y O U T
################################################################################
TC_BITS=8
PROVIDER_BITS=2
PROVIDER_OFFSET=16
MASK_BITS=8
ZONE_BITS=0
shorewall6.confThe contents of /etc/shorewall6/shorewall6.conf are:###############################################################################
#
# Shorewall Version 5 -- /etc/shorewall6/shorewall6.conf
#
# For information about the settings in this file, type "man shorewall6.conf"
#
# Manpage also online at
# http://www.shorewall.net/manpages6/shorewall6.conf.html
###############################################################################
# S T A R T U P E N A B L E D
###############################################################################
STARTUP_ENABLED=Yes
###############################################################################
# V E R B O S I T Y
###############################################################################
VERBOSITY=1
###############################################################################
# P A G E R
###############################################################################
PAGER=pager
###############################################################################
# F I R E W A L L
###############################################################################
FIREWALL=
###############################################################################
# L O G G I N G
###############################################################################
LOG_LEVEL="NFLOG(0,64,1)"
BLACKLIST_LOG_LEVEL="none"
INVALID_LOG_LEVEL=
LOG_BACKEND=netlink
LOG_VERBOSITY=2
LOGALLNEW=
LOGFILE=/var/log/ulogd/ulogd.syslogemu.log
LOGFORMAT="%s %s "
LOGLIMIT="s:5/min"
LOGTAGONLY=Yes
MACLIST_LOG_LEVEL="$LOG_LEVEL"
RELATED_LOG_LEVEL=
RPFILTER_LOG_LEVEL="$LOG_LEVEL"
SFILTER_LOG_LEVEL="$LOG_LEVEL"
SMURF_LOG_LEVEL="$LOG_LEVEL"
STARTUP_LOG=/var/log/shorewall6-init.log
TCP_FLAGS_LOG_LEVEL="$LOG_LEVEL"
UNTRACKED_LOG_LEVEL=
###############################################################################
# L O C A T I O N O F F I L E S A N D D I R E C T O R I E S
###############################################################################
CONFIG_PATH="${CONFDIR}/shorewall6:${CONFDIR}/shorewall:/usr/share/shorewall6:${SHAREDIR}/shorewall"
GEOIPDIR=/usr/share/xt_geoip/LE
IP6TABLES=
IP=
IPSET=
LOCKFILE=
MODULESDIR="+extra/RTPENGINE"
NFACCT=
PERL=/usr/bin/perl
PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin"
RESTOREFILE=restore
SHOREWALL_SHELL=/bin/sh
SUBSYSLOCK=/var/lock/subsys/shorewall6
TC=
###############################################################################
# D E F A U L T A C T I O N S / M A C R O S
###############################################################################
ACCEPT_DEFAULT="none"
BLACKLIST_DEFAULT="AllowICMPs,Broadcast(DROP),Multicast(DROP),dropNotSyn:$LOG_LEVEL,dropInvalid:$LOG_LEVEL,DropDNSrep:$LOG_LEVEL"
DROP_DEFAULT="AllowICMPs,Broadcast(DROP),Multicast(DROP)"
NFQUEUE_DEFAULT="none"
QUEUE_DEFAULT="none"
REJECT_DEFAULT="AllowICMPs,Broadcast(DROP),Multicast(DROP)"
###############################################################################
# R S H / R C P C O M M A N D S
###############################################################################
RCP_COMMAND='scp ${files} ${root}@${system}:${destination}'
RSH_COMMAND='ssh ${root}@${system} ${command}'
###############################################################################
# F I R E W A L L O P T I O N S
###############################################################################
ACCOUNTING=Yes
ACCOUNTING_TABLE=mangle
ADMINISABSENTMINDED=Yes
AUTOCOMMENT=Yes
AUTOHELPERS=No
AUTOMAKE=Yes
BALANCE_PROVIDERS=No
BASIC_FILTERS=No
BLACKLIST="NEW,INVALID,UNTRACKED"
CLAMPMSS=Yes
CLEAR_TC=No
COMPLETE=No
DEFER_DNS_RESOLUTION=Yes
DELETE_THEN_ADD=No
DONT_LOAD=
DYNAMIC_BLACKLIST="ipset-only,disconnect,timeout=7200"
EXPAND_POLICIES=Yes
EXPORTMODULES=Yes
FASTACCEPT=Yes
FORWARD_CLEAR_MARK=No
HELPERS=ftp
IGNOREUNKNOWNVARIABLES=No
IMPLICIT_CONTINUE=No
INLINE_MATCHES=No
IPSET_WARNINGS=Yes
IP_FORWARDING=Keep
KEEP_RT_TABLES=Yes
LOAD_HELPERS_ONLY=Yes
MACLIST_TABLE=filter
MACLIST_TTL=
MANGLE_ENABLED=Yes
MARK_IN_FORWARD_CHAIN=No
MINIUPNPD=No
MUTEX_TIMEOUT=60
OPTIMIZE=All
OPTIMIZE_ACCOUNTING=No
PERL_HASH_SEED=0
REJECT_ACTION=
REQUIRE_INTERFACE=No
RESTART=restart
RESTORE_DEFAULT_ROUTE=No
RESTORE_ROUTEMARKS=Yes
SAVE_IPSETS=No
TC_ENABLED=Shared
TC_EXPERT=No
TC_PRIOMAP="2 3 3 3 2 3 1 1 2 2 2 2 2 2 2 2"
TRACK_PROVIDERS=Yes
TRACK_RULES=No
USE_DEFAULT_RT=Yes
USE_NFLOG_SIZE=Yes
USE_PHYSICAL_NAMES=No
USE_RT_NAMES=No
VERBOSE_MESSAGES=No
WARNOLDCAPVERSION=Yes
WORKAROUNDS=No
ZERO_MARKS=No
ZONE2ZONE=-
###############################################################################
# P A C K E T D I S P O S I T I O N
###############################################################################
BLACKLIST_DISPOSITION=DROP
INVALID_DISPOSITION=CONTINUE
MACLIST_DISPOSITION=REJECT
RELATED_DISPOSITION=REJECT
SFILTER_DISPOSITION=DROP
RPFILTER_DISPOSITION=DROP
SMURF_DISPOSITION=DROP
TCP_FLAGS_DISPOSITION=DROP
UNTRACKED_DISPOSITION=DROP
################################################################################
# P A C K E T M A R K L A Y O U T
################################################################################
TC_BITS=8
PROVIDER_BITS=2
PROVIDER_OFFSET=8
MASK_BITS=8
ZONE_BITS=0
paramsBecause addresses and interfaces are different between the two
address families, they cannot be hard-coded in the configuration files.
/etc/shorewall/params is used to set shell
variables whose contents will vary between Shorewall and Shorewall6. In
the params file and in run-time extension files,
the shell variable g_family can be used
to determine which address family to use; if IPv4, then $g_family will
expand to 4 and if IPv6, $g_family will expand to 6.The contents of /etc/shorewall/params is as follows:INCLUDE mirrors #Sets the MIRRORS variable for the Mirrors action
#
# Set compile-time variables depending on the address family
#
if [ $g_family = 4 ]; then
#
# IPv4 compilation
#
FALLBACK=Yes # Make FAST_IF the primary and PROD_IF the fallback interface
# See /etc/shorewall/providers
STATISTICAL=No # Don't use statistical load balancing
LISTS=70.90.191.124 # IP address of lists.shorewall.net (MX)
MAIL=70.90.191.122 # IP address of mail.shorewall.net (IMAPS)
SERVER=70.90.191.125 # IP address of www.shorewall.org
PROXY= # Use TPROXY for local web access
ALL=0.0.0.0/0 # Entire address space
LOC_ADDR=172.20.1.253 # IP address of the local LAN interface
FAST_GATEWAY=10.2.10.1 # Default gateway through the IF_FAST interface
FAST_MARK=0x20000 # Multi-ISP mark setting for IF_FAST
IPSECMSS=1460
#
# Interface Options
#
LOC_OPTIONS=dhcp,ignore=1,wait=5,routefilter,routeback,tcpflags=0,nodbl,physical=eth2
FAST_OPTIONS=optional,dhcp,tcpflags,logmartians,nosmurfs,sourceroute=0,arp_ignore=1,proxyarp=0,upnp,nosmurfs,physical=eth0
PROD_OPTIONS=optional,dhcp,tcpflags,logmartians,nosmurfs,sourceroute=0,arp_ignore=1,proxyarp=0,upnp,nosmurfs,physical=eth1
DMZ_OPTIONS=routeback,proxyarp=1,required,wait=30,nets=70.90.191.120/29,dhcp,nodbl,physical=br0
IRC_OPTIONS=routeback,proxyarp=1,required,wait=30,nets=172.20.2.0/24,dhcp,nodbl,physical=br1
else
#
# IPv6 compilation
#
FALLBACK=Yes # Make FAST_IF the primary and PROD_IF the fallback interface
# See /etc/shorewall/providers
STATISTICAL=No # Don't use statistical load balancing
LISTS=[2001:470:b:227::42] # IP address of lists.shorewall.net (MX and HTTPS)
MAIL=[2001:470:b:227::45] # IP address of mail.shorewall.net (IMAPS and HTTPS)
SERVER=[2001:470:b:227::43] # IP address of www.shorewall.org (HTTP, FTP and RSYNC)
PROXY=3 # Use TPROXY for local web access
ALL=[::]/0 # Entire address space
LOC_ADDR=[2601:601:a000:16f0::1] # IP address of the local LAN interface
FAST_GATEWAY=fe80::22e5:2aff:feb7:f2cf # Default gateway through the IF_FAST interface
FAST_MARK=0x100 # Multi-ISP mark setting for IF_FAST
IPSECMSS=1440
#
# Interface Options
#
PROD_OPTIONS=forward=1,optional,physical=sit1
FAST_OPTIONS=forward=1,optional,dhcp,upnp,physical=eth0
LOC_OPTIONS=forward=1,nodbl,routeback,physical=eth2
DMZ_OPTIONS=routeback,forward=1,required,wait=30,nodbl,physical=br0
IRC_OPTIONS=routeback,forward=1,required,wait=30,nodbl,physical=br1
fizonesHere is the /etc/shorewall/zones file:###############################################################################
#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
#
# By using the 'ip' type, both Shorewall and Shorewall6 can share this file
#
fw { TYPE=firewall }
net { TYPE=ip }
loc { TYPE=ip }
dmz { TYPE=ip }
apps { TYPE=ip }
vpn { TYPE=ipsec, OPTIONS=mode=tunnel,proto=esp,mss=$IPSECMSS }
interfaces/etc/shorewall/interfaces makes heavy use of variables set in
/etc/shorewall/params:#
# The two address families use different production interfaces and different
#
# LOC_IF is the local LAN for both families
# FAST_IF is a Comcast IPv6 beta uplink which is used for internet access from the local lan for both families
# PROD_IF is the interface used by shorewall.org servers
# For IPv4, it is eth1
# For IPv6, it is sit1 (Hurricane Electric 6in4 link)
# DMZ_IF is a bridge to the production containers
# IRC_IF is a bridge to a container that currently runs irssi under screen
loc { INTERFACE=LOC_IF, OPTIONS=$LOC_OPTIONS }
net { INTERFACE=FAST_IF, OPTIONS=$FAST_OPTIONS }
net { INTERFACE=PROD_IF, OPTIONS=$PROD_OPTIONS }
dmz { INTERFACE=DMZ_IF, OPTIONS=$DMZ_OPTIONS }
apps { INTERFACE=IRC_IF, OPTIONS=$IRC_OPTIONS }
hosts/etc/shorewall/hosts is used to define the vpn zone:#ZONE HOSTS OPTIONS
vpn { HOSTS=PROD_IF:$ALL }
vpn { HOSTS=FAST_IF:$ALL }
vpn { HOSTS=LOC_IF:$ALL }
policyThe same set of policies apply to both address families:#SOURCE DEST POLICY LOGLEVEL RATE
$FW { DEST=dmz,net, POLICY=REJECT, LOGLEVEL=$LOG_LEVEL }
$FW { DEST=all, POLICY=ACCEPT }
loc { DEST=net, POLICY=ACCEPT }
loc,vpn,apps { DEST=loc,vpn,apps POLICY=ACCEPT }
loc { DEST=fw, POLICY=REJECT, LOGLEVEL=$LOG_LEVEL }
net { DEST=net, POLICY=NONE }
net { DEST=fw, POLICY=BLACKLIST:+Broadcast(DROP),Multicast(DROP),DropDNSrep:$LOG_LEVEL, LOGLEVEL=$LOG_LEVEL, RATE=8/sec:30 }
net { DEST=all, POLICY=BLACKLIST:+DropDNSrep:$LOG_LEVEL, LOGLEVEL=$LOG_LEVEL, RATE=8/sec:30 }
dmz { DEST=fw, POLICY=REJECT, LOGLEVEL=$LOG_LEVEL }
all { DEST=all, POLICY=REJECT, LOGLEVEL=$LOG_LEVEL }
providersThe providers file is set up to allow for three different
configurations:FALLBACK -- FAST_IF is the primary interface and PROD_IF is
the fallbackSTATISTICAL -- Statistical load balancing between FAST_IF and
PROD_IFIPv4 only -- balance between FAST_IF and PROD_IF#
# This could be cleaned up a bit, but I'm leaving it as is for now
#
# - The two address families use different fw mark geometry
# - The two address families use different fallback interfaces
# - The 'balance' option doesn't work as expected in IPv6 so I have no balance configuration for Shorewall6
# - IPv4 uses the 'loose' option on PROD_IF
#
?if $FALLBACK
# FAST_IF is primary, PROD_IF is fallback
#
?info Compiling with FALLBACK
IPv6Beta { NUMBER=1, MARK=$FAST_MARK, INTERFACE=FAST_IF, GATEWAY=$FAST_GATEWAY, OPTIONS=loose,primary,persistent,noautosrc }
?if __IPV4
ComcastB { NUMBER=4, MARK=0x10000, INTERFACE=PROD_IF, GATEWAY=10.1.10.1, OPTIONS=loose,fallback,persistent }
?else
HE { NUMBER=2, MARK=0x200, INTERFACE=PROD_IF, OPTIONS=fallback,persistent }
?endif
?elsif $STATISTICAL
# Statistically balance traffic between FAST_IF and PROD_IF
?info Compiling with STATISTICAL
?if __IPV4
IPv6Beta { NUMBER=1, MARK=0x20000, INTERFACE=FAST_IF, GATEWAY=$FAST_GATEWAY, OPTIONS=loose,load=0.66666667,primary }
?else
HE { NUMBER=2, MARK=0x200, INTERFACE=PROD_IF, OPTIONS=track,load=0.33333333,persistent }
?endif
?else
?INFO Compiling with BALANCE
IPv6Beta { NUMBER=1, MARK=0x100, INTERFACE=eth0, GATEWAY=$FAST_GATEWAY, OPTIONS=track,balance=2,loose,persistent }
?if __IPV4
ComcastB { NUMBER=4, MARK=0x10000, INTERFACE=IPV4_IF, GATEWAY=10.1.10.1, OPTIONS=nohostroute,loose,balance,persistent }
?else
?warning No BALANCE IPv6 configuration
HE { NUMBER=2, MARK=0x200, INTERFACE=PROD_IF, OPTIONS=fallback,persistent }
?endif
?endif
Tproxy { NUMBER=3, INTERFACE=lo, OPTIONS=tproxy }
rtrulesThe routing rules are quite dependent on the address
family:#SOURCE DEST PROVIDER PRIORITY
#
# This file ensures that the DMZ is routed out of the IF_PROD interface
# and that the IPv6 subnets delegated by the Beta router are routed out
# of the IF_FAST interface.
#
?if __IPV4
{ SOURCE=70.90.191.121,70.90.191.123,10.1.10.1 PROVIDER=ComcastB, PRIORITY=1000! }
{ SOURCE=&FAST_IF, PROVIDER=IPv6Beta, PRIORITY=1000! }
{ SOURCE=br0, PROVIDER=ComcastB, PRIORITY=11000 }
?else
{ SOURCE=2601:601:a000:1600::/64 PROVIDER=IPv6Beta, PRIORITY=1000! }
{ SOURCE=2001:470:B:227::/64, PROVIDER=HE, PRIORITY=1000! }
{ SOURCE=2601:601:a000:16f0::/60 PROVIDER=IPv6Beta, PRIORITY=11000 }
?endifroutesThis file is used only for IPv6:#PROVIDER DEST GATEWAY DEVICE OPTIONS
?if __IPV6
#
# In my version of FOOLSM (1.0.10), the 'sourceip' option doesn't work.
# As a result, routing rules that specify the source IPv6 address are
# not effective in routing the 'ping' request packets out of FAST_IF.
# The following route solves that problem.
#
{ PROVIDER=main, DEST=2001:558:4082:d3::1/128, GATEWAY=fe80::22e5:2aff:feb7:f2cf, DEVICE=FAST_IF, OPTIONS=persistent }
?endifactions/etc/shorewall/actions defines one action:#ACTION COMMENT
Mirrors # Accept traffic from Shorewall Mirrors
/etc/shorewall/action.Mirrors:#TARGET SOURCE DEST PROTO DEST SOURCE ORIGINAL RATE
# PORT PORT(S) DEST LIMIT
?COMMENT Accept traffic from Mirrors
?FORMAT 2
DEFAULTS -
$1 $MIRRORS
Macros/etc/shorewall/macro.FTP:###############################################################################
#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER
PARAM - - tcp 21
This is just the normal Shorewall FTP macro without the helper
logic -- we take care of that in the conntrack file below.conntrackIn addition to invoking the FTP helper on TCP port 21, this file
notracks some IPv4 traffic:#ACTION SOURCE DEST PROTO DPORT SPORT USER SWITCH
CT:helper:ftp:P { PROTO=tcp, DPORT=21 }
CT:helper:ftp:O { PROTO=tcp, DPORT=21 }
?if __IPV4
#
# Don't track IPv4 broadcasts
#
NOTRACK:P { SOURCE=LOC_IF, DEST=172.20.1.255, PROTO=udp }
NOTRACK:P { DEST=255.255.255.255, PROTO=udp }
NOTRACK:O { DEST=255.255.255.255, PROTO=udp }
NOTRACK:O { DEST=172.20.1.255, PROTO=udp }
NOTRACK:O { DEST=70.90.191.127, PROTO=udp }
?endif
rules/etc/shorewall/rules has only a couple of rules that are
conditional based on address family:#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER MARK CONNLIMIT TIME HEADERS SWITCH HELPER
?SECTION ALL
Ping(ACCEPT) { SOURCE=net, DEST=all, RATE=d:ping:2/sec:10 }
Trcrt(ACCEPT) { SOURCE=net, DEST=all, RATE=d:ping:2/sec:10 }
?SECTION ESTABLISHED
?SECTION RELATED
ACCEPT { SOURCE=all, DEST=dmz:$SERVER, PROTO=tcp, DPORT=61001:62000, helper=ftp }
ACCEPT { SOURCE=dmz, DEST=all, PROTO=tcp, helper=ftp }
ACCEPT { SOURCE=all, DEST=net, PROTO=tcp, helper=ftp }
ACCEPT { SOURCE=$FW, DEST=loc, PROTO=tcp, helper=ftp }
ACCEPT { SOURCE=loc, DEST=$FW, PROTO=tcp, helper=ftp }
ACCEPT { SOURCE=all, DEST=all, PROTO=icmp }
RST(ACCEPT) { SOURCE=all, DEST=all }
ACCEPT { SOURCE=dmz, DEST=dmz }
?SECTION INVALID
RST(ACCEPT) { SOURCE=all, DEST=all }
DROP { SOURCE=net, DEST=all }
FIN { SOURCE=all, DEST=all }
?SECTION UNTRACKED
?if __IPV4
Broadcast(ACCEPT) { SOURCE=all, DEST=$FW }
ACCEPT { SOURCE=all, DEST=$FW, PROTO=udp }
CONTINUE { SOURCE=loc, DEST=$FW }
CONTINUE { SOURCE=$FW, DEST=all }
?endif
?SECTION NEW
######################################################################################################
# Stop certain outgoing traffic to the net
#
REJECT:$LOG_LEVEL { SOURCE=loc,vpn,apps DEST=net, PROTO=tcp, DPORT=25 } #Stop direct loc->net SMTP (Comcast uses submission).
REJECT:$LOG_LEVEL { SOURCE=loc,vpn,apps DEST=net, PROTO=udp, DPORT=1025:1031 } #MS Messaging
REJECT { SOURCE=all, DEST=net, PROTO=tcp, DPORT=137,445, comment="Stop NETBIOS Crap" }
REJECT { SOURCE=all, DEST=net, PROTO=udp, DPORT=137:139, comment="Stop NETBIOS Crap" }
REJECT { SOURCE=all, DEST=net, PROTO=tcp, DPORT=3333, comment="Disallow port 3333" }
REJECT { SOURCE=all, DEST=net, PROTO=udp, DPORT=3544, comment="Stop Teredo" }
?COMMENT
######################################################################################################
# 6in4
#
?if __IPV4
ACCEPT { SOURCE=net:216.218.226.238, DEST=$FW, PROTO=41 }
ACCEPT { SOURCE=$FW, DEST=net:216.218.226.238, PROTO=41 }
?endif
######################################################################################################
# Ping
#
Ping(ACCEPT) { SOURCE=$FW,loc,dmz,vpn, DEST=$FW,loc,dmz,vpn }
Ping(ACCEPT) { SOURCE=all, DEST=net }
######################################################################################################
# SSH
#
AutoBL(SSH,60,-,-,-,-,$LOG_LEVEL)\
{ SOURCE=net, DEST=all, PROTO=tcp, DPORT=22 }
SSH(ACCEPT) { SOURCE=all, DEST=all }
?if __IPV4
SSH(DNAT-) { SOURCE=net, DEST=172.20.2.44, PROTO=tcp, DPORT=ssh, ORIGDEST=70.90.191.123 }
?endif
######################################################################################################
# DNS
#
DNS(ACCEPT) { SOURCE=loc,dmz,vpn,apps, DEST=$FW }
DNS(ACCEPT) { SOURCE=$FW, DEST=net }
######################################################################################################
# Traceroute
#
Trcrt(ACCEPT) { SOURCE=all, DEST=net }
Trcrt(ACCEPT) { SOURCE=net, DEST=$FW,dmz }
######################################################################################################
# Email
#
SMTP(ACCEPT) { SOURCE=net,$FW, DEST=dmz:$LISTS }
SMTP(ACCEPT) { SOURCE=dmz:$LISTS, DEST=net:PROD_IF }
SMTP(REJECT) { SOURCE=dmz:$LISTS, DEST=net }
IMAPS(ACCEPT) { SOURCE=all, DEST=dmz:$MAIL }
Submission(ACCEPT) { SOURCE=all, DEST=dmz:$LISTS }
SMTPS(ACCEPT) { SOURCE=all, DEST=dmz:$LISTS }
IMAP(ACCEPT) { SOURCE=loc,vpn, DEST=net }
######################################################################################################
# NTP
#
NTP(ACCEPT) { SOURCE=all, DEST=net }
NTP(ACCEPT) { SOURCE=loc,vpn,dmz,apps DEST=$FW }
######################################################################################################
# Squid
ACCEPT { SOURCE=loc,vpn, DEST=$FW, PROTO=tcp, DPORT=3128 }
######################################################################################################
# HTTP/HTTPS
#
Web(ACCEPT) { SOURCE=loc,vpn DEST=$FW }
Web(ACCEPT) { SOURCE=$FW, DEST=net, USER=proxy }
Web(DROP) { SOURCE=net, DEST=fw, PROTO=tcp, comment="Do not blacklist web crawlers" }
HTTP(ACCEPT) { SOURCE=net,loc,vpn,apps,$FW DEST=dmz:$SERVER,$LISTS,$MAIL }
HTTPS(ACCEPT) { SOURCE=net,loc,vpn,apps,$FW DEST=dmz:$LISTS,$MAIL }
Web(ACCEPT) { SOURCE=dmz,apps DEST=net,$FW }
Web(ACCEPT) { SOURCE=$FW, DEST=net, USER=root }
Web(ACCEPT) { SOURCE=$FW, DEST=net, USER=teastep }
Web(ACCEPT) { SOURCE=$FW, DEST=net, USER=_apt }
######################################################################################################
# FTP
#
FTP(ACCEPT) { SOURCE=loc,vpn,apps DEST=net }
FTP(ACCEPT) { SOURCE=dmz, DEST=net }
FTP(ACCEPT) { SOURCE=$FW, DEST=net, USER=root }
FTP(ACCEPT) { SOURCE=all, DEST=dmz:$SERVER }
#
# 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_LEVEL { SOURCE=dmz, DEST=net, PROTO=tcp, DPORT=1024:, SPORT=20 }
######################################################################################################
# whois
#
Whois(ACCEPT) { SOURCE=all, DEST=net }
######################################################################################################
# SMB
#
SMBBI(ACCEPT) { SOURCE=loc, DEST=$FW }
SMBBI(ACCEPT) { SOURCE=vpn, DEST=$FW }
######################################################################################################
# IRC
#
IRC(ACCEPT) { SOURCE=loc,apps, DEST=net }
######################################################################################################
# Rsync
#
Mirrors(ACCEPT:none) { SOURCE=net, DEST=dmz:$SERVER, PROTO=tcp, DPORT=873 }
mangleNote that TPROXY can be enabled/disabled via a shell variable
setting in /etc/shorewall/params:#ACTION SOURCE DEST PROTO DPORT SPORT USER TEST LENGTH TOS CONNBYTES HELPER PROBABILITY DSCP
?if __IPV4
#
# I've had a checksum issue with certain IPv4 UDP packets
#
CHECKSUM:T { DEST=FAST_IF, PROTO=udp }
CHECKSUM:T { DEST=DMZ_IF, PROTO=udp }
?endif
?if $PROXY
#
# Use TPROXY for web access from the local LAN
#
DIVERT:R { PROTO=tcp, SPORT=80 }
DIVERT:R { PROTO=tcp, DPORT=80 }
TPROXY(3129,$LOC_ADDR) { SOURCE=LOC_IF, PROTO=tcp, DPORT=80 }
?endif
snatNAT entries are quite dependent on the address family:#ACTION SOURCE DEST PROTO PORT IPSEC MARK USER SWITCH ORIGDEST PROBABILITY
?if __IPV4
MASQUERADE { SOURCE=172.20.1.0/24,172.20.2.0/23, DEST=FAST_IF }
MASQUERADE { SOURCE=70.90.191.120/29, DEST=FAST_IF }
SNAT(70.90.191.121) { SOURCE=!70.90.191.120/29, DEST=PROD_IF, PROBABILITY=0.50, COMMENT="Masquerade Local Network" }
SNAT(70.90.191.123) { SOURCE=!70.90.191.120/29, DEST=PROD_IF, COMMENT="Masquerade Local Network" }
SNAT(172.20.1.253) { SOURCE=172.20.3.0/24, DEST=LOC_IF:172.20.1.100 }
?else
SNAT(&PROD_IF) { SOURCE=2601:601:8b00:bf0::/60, DEST=PROD_IF }
SNAT(&FAST_IF) { SOURCE=2001:470:b:227::/64,2001:470:a:227::2, DEST=FAST_IF }
?endif
tunnelsBoth address families define IPsec tunnels:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsecnat {ZONE=net, GATEWAY=$ALL, GATEWAY_ZONE=vpn }
ipsecnat {ZONE=loc, GATEWAY=$ALL, GATEWAY_ZONE=vpn }
proxyarpThis file is only used in the IPv4 configuration:#ADDRESS INTERFACE EXTERNAL HAVEROUTE PERSISTENT
70.90.191.122 { INTERFACE=br0, EXTERNAL=eth1, HAVEROUTE=yes, PERSISTENT=no }
isuableThis is just the standard Shorewall isusable extension
script:local status
status=0
[ -f ${VARDIR}/${1}.status ] && status=$(cat ${VARDIR}/${1}.status)
return $status
started/etc/shorewall/started only does something in the IPv4
configuration, although it gets compiled into both scripts:if [ $g_family = 4 ]; then
qt $IP -4 route replace 70.90.191.122 dev br0
qt $IP -4 route replace 70.90.191.124 dev br0
qt $IP -4 route replace 70.90.191.125 dev br0
fi
shorewall-docs-xml-5.2.3/blacklisting_support_ru.xml 0000664 0000000 0000000 00000030055 13427347317 021455 0 ustar root root
Чёрные списки в ShorewallTomEastep2002-2006Thomas M. Eastep2007Russian Translation: Grigory MokhinЭтот документ разрешается копировать, распространять и/или изменять при выполнении условий лицензии GNU Free Documentation License версии 1.2 или более поздней, опубликованной Free Software Foundation; без неизменяемых разделов, без текста на верхней обложке, без текста на нижней обложке. Копия лицензии приведена по ссылке GNU Free Documentation License.ВведениеВ Shorewall предусмотрены два вида чёрных списков, статические и динамические. Опция BLACKLISTNEWONLY в файле /etc/shorewall/shorewall.conf задаёт параметры фильтрации согласно этим спискам:BLACKLISTNEWONLY=No -- проверка осуществляется для всех входящих пакетов. Новые записи в чёрном списке позволяют прервать уже существующие соединения.BLACKLISTNEWONLY=Yes -- проверка осуществляется только для новых запросов на установление соединения. Записи в чёрном списке не влияют на уже существующие соединения. На соответствие чёрному списку проверяется только адрес источника.На соответствие чёрному списку проверяется только адрес источника . Чёрные списки закрывают доступ только хостам, перечисленным в списке, но не закрывают доступ к самим этим хостам.Динамические чёрные списки в Shorewall непригодны для случаев, когда список содержит тысячи адресов. Статические списки могут работать с большим числом адресов, но только при использовании наборов IP (ipset). Без ipset большие чёрные списки будут загружаться слишком долго и заметно снизят производительность файрвола.Статические чёрные спискиДалее описаны параметры конфигурации статических чёрных списков в Shorewall:Пакеты с хостов из чёрного списка будут отбрасываться без уведомления (drop) или с уведомлением (reject), согласно параметру BLACKLIST_DISPOSITION из файла /etc/shorewall/shorewall.conf.Пакеты с хостов из чёрного списка будут заноситься в протокол с заданным уровнем syslog согласно параметру BLACKLIST_LOGLEVEL из файла /etc/shorewall/shorewall.conf.IP-адреса или подсети, которые требуется занести в чёрный список, указываются в файле /etc/shorewall/blacklist. В этом файле можно также указать имена протоколов, номера портов или имена служб.Интерфейсы, для которых входящие пакеты проверяются на соответствие чёрному списку, задаются с помощью опции blacklist в файле /etc/shorewall/interfaces.Чёрный список из файла /etc/shorewall/blacklist можно обновить командой shorewall refresh.При наличии большого статического чёрного списка можно включить опцию DELAYBLACKLISTLOAD в файле shorewall.conf (начиная с Shorewall версии 2.2.0). Если DELAYBLACKLISTLOAD=Yes, то Shorewall будет загружать правила чёрного списка после установления соединений. Хотя при этом соединения с хостов из чёрного списка могут осуществляться в течение времени создания списка, эта опция позволяет существенно снизить время запрета соединений в ходе выполнения команд "shorewall [re]start".Для определения статического чёрного списка в Shorewall начиная с версии 2.4.0 поддерживаются наборы IP, или ipsets. Пример:#ADDRESS/SUBNET PROTOCOL PORT
+Blacklistports[dst]
+Blacklistnets[src,dst]
+Blacklist[src,dst]
#LAST LINE -- ADD YOUR ENTRIES BEFORE THIS ONE -- DO NOT REMOVEВ этом примере задан ipset набора портов (portmap) Blacklistports для запрета трафика на целевые порты, указанные в этом ipset. Есть также списки сетей - Blacklistnets (типа nethash) и адресов - Blacklist (типа iphash), закрывающие доступ из подсетей и с отдельных адресов. Обратите внимание, что указаны [src,dst], чтобы можно было связать отдельные записи наборов с другими portmap ipset и включить чёрные списки сочетаний ( адрес источника, целевой порт). Пример: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 SMTPПри этом блокируется трафик SMTP с хоста 206.124.146.177.Динамические чёрные спискиДинамические списки не имеют никаких параметров конфигурации, но настраиваются следующими командами /sbin/shorewall[-lite]:drop <список IP-адресов> - пакеты с указанных IP-адресов будут отбрасываться файрволом без уведомления. reject <список IP-адресов> - пакеты с указанных IP-адресов будут отбрасываться файрволом с уведомлением. allow <список IP-адресов> - разрешить пакеты с хостов, ранее занесённых в чёрный список командами drop или reject. save - сохранить конфигурацию динамического чёрного списка; она будет восстановлена автоматически при следующем перезапуске файрвола.show dynamic - показать конфигурацию динамического чёрного списка.Начиная с Shorewall версии 3.2.0 Beta2 доступны следующие дополнительные команды:logdrop <список IP-адресов> - пакеты с указанных IP-адресов будут заноситься в протокол и отбрасываться файрволом без уведомления. Уровень протокола задаётся опцией BLACKLIST_LOGLEVEL в ходе последнего [пере]запуска (по умолчанию - 'info', если опция BLACKLIST_LOGLEVEL не задана).logreject <список IP-адресов> - пакеты с указанных IP-адресов будут заноситься в протокол и отбрасываться файрволом с уведомлением. Уровень протокола задаётся опцией BLACKLIST_LOGLEVEL в ходе последнего [пере]запуска (по умолчанию - 'info', если опция BLACKLIST_LOGLEVEL не задана).Динамические чёрные списки не зависят от опции blacklist в файле /etc/shorewall/interfaces.Игноpиpовать пакеты с двух IP-адресовshorewall[-lite] drop 192.0.2.124 192.0.2.125При этом блокируется доступ с хостов 192.0.2.124 и 192.0.2.125Разрешить пакеты с IP-адресаshorewall[-lite] allow 192.0.2.125Разрешает трафик с 192.0.2.125.
shorewall-docs-xml-5.2.3/MultiISP_ru.xml 0000664 0000000 0000000 00000151624 13427347317 016667 0 ustar root root
Shorewall и подключение к Internet по нескольким каналамTomEastep200520062007Thomas M. Eastep2007Russian Translation: Grigory MokhinЭтот документ разрешается копировать, распространять и/или изменять при выполнении условий лицензии GNU Free Documentation License версии 1.2 или более поздней, опубликованной Free Software Foundation; без неизменяемых разделов, без текста на верхней обложке, без текста на нижней обложке. Копия лицензии приведена по ссылке GNU Free Documentation License.Вы должны установить современный дистрибутив, который обновляется поставщиком, прежде чем пытаться настроить работу в этом режиме. Старые дистрибутивы не удовлетворяют минимальным требованиям, и вам потребуется перекомпилировать iptables, ядро и прочее программное обеспечение в системе. Если вы проигнорируете этот совет, то не рассчитывайте, что кто-либо сможет вам помочь..Чтение только документации Shorewall не будет достаточным для понимания раскрываемых здесь тем. Shorewall упрощает работу с iptables, но разработчики Shorewall не имеют достаточных ресурсов, чтобы учить вас основам управляемой маршрутизации в Linux (равно как и пособие по вождению комбайна не учит правильно выращивать пшеницу). Скорее всего вам потребуется обратиться к следующим дополнительным источникам:LARTC HOWTO: http://www.lartc.orgВывод команды man ipВывод команд ip route help и ip rule helpПоддержка нескольких соединений с InternetНачиная с версии 2.3.2 в Shorewall реализована ограниченная поддержка нескольких соединений с Internet. Ниже описаны существующие ограничения:Используется статическая конфигурация маршрутов. Поэтому не предусмотрены меры по защите от сбоя какого-либо из каналов связи с провайдером.Изменения маршрутизации и очистка кэша маршрутов осуществляются при запуске и при перезапуске Shorewall (если не указана опция "-n" для shorewall restart). Вообще говоря, в идеальном случае перезапуск пакетного фильтра никак не должен влиять на маршрутизацию.В версиях Shorewall ниже 3.4.0 маршруты и правила маршрутизации, добавляемые при запуске, не удалялись полностью в ходе выполнения команд shorewall stop, shorewall clear или shorewall restart.ОбзорПредположим, что система, в которой работает файрвол, подключена к двум провайдерам по двум интерфейсам Ethernet, как показано на рисунке.eth0 подключен к ISP1. IP-адрес eth0 - это 206.124.146.176, и шлюз провайдера имеет IP-адрес 206.124.146.254.eth1 подключен к ISP2. IP-адрес eth1 - это 130.252.99.27, и шлюз провайдера имеет IP-адрес 130.252.99.254.eth2 подключен к локальной сети. У него может быть любой IP-адрес.Все эти провайдеры должны быть перечислены в файле /etc/shorewall/providers.В записях в файле /etc/shorewall/providers можно указать, что для исходящих соединений должно быть включено распределение нагрузки по двум каналам связи с провайдерами. В записях в файле /etc/shorewall/tcrules можно указать, что некоторые исходящие соединения должны использовать определённый канал провайдера. Правила в файле /etc/shorewall/tcrules необязательны для того, чтобы настройка /etc/shorewall/providers работала, но необходимо указать уникальное значение MARK для каждого из провайдеров, чтобы Shorewall настроил правила маркировки.Если задать опцию track в файле /etc/shorewall/providers, то соединения из Internet будут автоматически маршрутизироваться обратно через правильный интерфейс на соответствующий шлюз провайдера. Это будет работать как в том случае, когда соединение обрабатывается самим файрволом, так и для соединений, маршрутизируемых или пробрасываемых к системам позади файрвола.Shorewall настраивает маршрутизацию и обновляет файл /etc/iproute2/rt_tables, включая в него имена таблиц и их номера.При этом используются функции маркировки пакетов для управления маршрутизацией. Как следствие этого возникают ограничения на записи в файле /etc/shorewall/tcrules:Маркировка пакетов для целей управления трафиком не может осуществляться в цепочке PREROUTING для соединений с участием провайдеров, для которых задана опция 'track' (см. далее).Нельзя использовать опции SAVE или RESTORE.Нельзя использовать маркировку соединений.Файл /etc/shorewall/providers может также использоваться в других сценариях маршрутизации. В документации по работе с Squid приведены примеры.Файл /etc/shorewall/providersДалее описаны поля этого файла. Как и везде в файлах конфигурации Shorewall, укажите в поле для столбца "-", если не требуется задавать никакое значение.NAMEИмя провайдера. Должно начинаться с буквы и состоять из букв и цифр. Имя провайдера становится именем сгенерированной таблицы маршрутизации для этого провайдера.NUMBERЧисло от 1 до 252. Оно будет номером таблицы маршрутизации для сгенерированной таблицы для этого провайдера.MARKМетка, применяемая в файле /etc/shorewall/tcrules для направления пакетов через этого провайдера. Shorewall также помечает этой меткой соединения, которые входят через этого провайдера, и восстанавливает метку пакета в цепочке PREROUTING. Метка должна быть целым числом от 1 до 255.Начиная с Shorewall версии 3.2.0 Beta 6, можно задать опцию HIGH_ROUTE_MARKS=Yes в файле /etc/shorewall/shorewall.conf. Это позволяет решить следующие задачи:Использовать метки пакетов для управления трафиком, при условии что эти метки присваиваются в цепочке FORWARD.Использовать значения меток > 255 для меток провайдера. Эти метки должны быть кратными 256 в диапазоне 256-65280 (в 16-ричном представлении 0x100 - 0xFF00, с нулевыми младшими 8 битами).DUPLICATEИмя или номер таблицы маршрутизации, которая будет продублирована. Можно указать 'main' или имя или номер ранее объявленного провайдера. Для большинства приложений здесь достаточно будет указать 'main'.INTERFACEИмя интерфейса канала связи с провайдером.В реализации поддержки нескольких подключений с провайдерами Shorewall предполагается, что каждый провайдер подключен к собственному интерфейсу.GATEWAYIP-адрес шлюза провайдера.Здесь можно указать detect для автоматического определения IP-адреса шлюза.Совет:"detect" следует указывать в том случае, если интерфейс из поля INTERFACE настраивается динамически по DHCP.OPTIONSСписок параметров через запятую, описанных ниже:trackЕсли эта опция включена, то будут отслеживаться соединения, ВХОДЯЩИЕ через этот интерфейс, чтобы ответы могли маршрутизироваться обратно через этот же интерфейс.Укажите 'track', если через этого провайдера к локальным серверам будут обращаться хосты из Internet. Вместе с 'track' всегда следует указывать опцию 'balance'.Для работы с этой функцией ядро и iptables должны поддерживать цель CONNMARK и сравнение connmark. Расширение цели ROUTE не требуется.В iptables 1.3.1 есть ошибка в реализации CONNMARK и iptables-save/iptables-restore. Поэтому при настройке нескольких провайдеров команда shorewall restore может быть не выполнена. Если это имеет место, примените исправление iptables, доступное по адресу http://shorewall.net/pub/shorewall/contrib/iptables/CONNMARK.diff.Если используется файл /etc/shorewall/providers для настройки нескольких соединений с Internet, укажите опцию 'track', даже если в ней нет необходимости. Она помогает поддерживать длительные соединения, в которых могут быть долгие периоды отсутствия трафика.balanceОпция 'balance' позволяет распределять нагрузку исходящих потоков между несколькими провайдерами. Распределение нагрузки не будет идеальным, поскольку оно осуществляется посредством маршрутов, а маршруты кэшируются. При этом маршрут к хостам, к которым часто обращаются пользователи, будет проходить всегда через одного и того же провайдера.По умолчанию всем провайдерам присваивается одинаковый вес (1). Вес конкретного провайдера можно изменить опцией balance с "=" и весом (например, balance=2). Веса отражают относительную пропускную способность каналов связи с провайдером. Они должны быть небольшими числами, потому что ядро создает дополнительные маршруты для каждого приращения веса. Если файл /etc/shorewall/providers используется для настройки нескольких соединений с Internet, укажите опцию 'balance', даже если в ней нет необходимости. Для направления всего трафика через какого-либо определенного провайдера можно использовать файл /etc/shorewall/tcrules. Если вы проигнорируете этот совет, то прочитайте FAQ 57 и FAQ 58.Если указана опция 'balance', но весь трафик по-прежнему идёт через одного провайдера, то причина этого может состоять в том, что ядро не собрано с опцией CONFIG_IP_ROUTE_MULTIPATH_CACHED=n. У некоторых пользователей пересборка ядра с этой опцией помогла устранить неполадку.Эта неполадка присутствует в ядре SuSE 10.0, и согласно в этом случае может возникать критическая ошибка ядра. В SUSE 10.1 и SLES 10 опция CONFIG_IP_ROUTE_MULTIPATH_CACHED=n включена по умолчанию. Источник неполадки описан здесь: несовместимость между исправлениями от LARTC и опцией CONFIG_IP_ROUTE_MULTIPATH_CACHED.looseНе включать правила маршрутизации, которые принудительно направляют через данный интерфейс трафик, исходный IP-адрес которого совпадает с адресом интерфейса канала с провайдером. Эта опция полезна для определения провайдеров, которые должны использоваться только при наличии соответствующей метки пакета. Эту опцию нельзя указывать совместно с balance.optional (начиная с Shorewall 3.2.2)Shorewall определит, работает ли этот интерфейс и настроен ли его IP-адрес. Если он не настроен, то будет показано предупреждение, а сам провайдер не будет включен.Параметр 'optional' предназначен для определения состояния интерфейсов, которые могли бы вызвать сбой команды shorewall start или shorewall restart - однако даже если интерфейс находится в состоянии, в котором Shorewall может [пере]запуститься без ошибок, это не означает, что трафик может с гарантией проходить через этот интерфейс.Для тех, кто окончательно запутался в том, что такое track и balance:track управляет входящими соединениями.balance управляет исходящими соединениями.COPYЕсли в поле DUPLICATE указана существующая таблица, то Shorewall копирует все маршруты, проходящие через интерфейс, указанный в столбце INTERFACE, а также через интерфейс, указанный в этом поле. В этом поле следует указать все интерфейсы в системе файрвола, исключая интерфейсы Internet, указанные в поле INTERFACE этого файла.Какие функции выполняет запись в файле providersДобавление записи в файле providers приводит к созданию альтернативной таблицы маршрутизации. Помимо этого:Если не указана опция loose, то создается правило ip для каждого IP-адреса из поля INTERFACE, которое обеспечивает маршрутизацию трафика с этого адреса через соответствующую таблицу маршрутизации.Если указана опция track, то соединения, для которых хотя бы один пакет прошел на интерфейс, указанный в поле INTERFACE, получат метку соединения, заданную в поле MARK. В цепочке PREROUTING метка пакетов, имеющих метку соединения, будет задана равной метке соединения, и такие помеченные пакеты не будут подчиняться правилам для цепочки PREROUTING, заданным в файле /etc/shorewall/tcrules. Это обеспечивает маршрутизацию через правильный интерфейс для входящих соединений.Если указана опция balance, то Shorewall заменит маршрут по умолчанию с весом 100 в таблице маршрутизации 'main' маршрутом с распределением нагрузки между шлюзами, для которых опция balance включена. Поэтому, если вы настраиваете маршруты по умолчанию, то укажите их вес меньше, чем 100, иначе маршрут, добавленный Shorewall, не будет иметь силы.Больше эти записи не делают ничего. Вспомните основной принцип, описанный в документации по маршрутизации Shorewall:Маршрутизация отвечает за то, куда направляются пакеты.После того, как маршрут пакета определён, файрвол (Shorewall) определяет, разрешить ли отправку пакета по его маршруту.Итак, если вы хотите направить трафик через определённого провайдера, то необходимо пометить этот трафик значением MARK провайдера в файле /etc/shorewall/tcrules и пометить пакет в цепочке PREROUTING; другим способом будет указание соответствующих правил в файле /etc/shorewall/rtrules.В Shorewall версий ниже 3.4.0 записи из файла /etc/shorewall/providers необратимо изменяют маршрутизацию системы, то есть эти изменения не отменяются при вызове команды shorewall stop или shorewall clear. Для того чтобы восстановить исходные маршруты, может потребоваться перезапустить сеть. Обычно это делает команда /etc/init.d/network restart или /etc/init.d/networking restart. Обратитесь к документации по сети вашего дистрибутива.Дополнительные замечания:Влияние изменений, вносимых Shorewall в таблицу маршрутизации, можно уменьшить, указав параметр metric для каждого настраиваемого маршрута по умолчанию. Shorewall создаст маршрут по умолчанию с распределением нагрузки (если опция balance включена для какого-либо из провайдеров), который не будет включать метрику и тем самым не будет заменять никакой существующий маршрут, для которого метрика отлична от нуля.Опция -n команд shorewall restart и shorewall restore позволяет предотвратить изменение маршрутизации.Файл /etc/shorewall/stopped можно также использовать для восстановления маршрутизации при остановке Shorewall. Когда система работает в обычной конфигурации маршрутизации (одна таблица), то ее содержимое можно сохранить следующим образом:ip route ls > routesНиже приведен пример файла routes для моей системы:192.168.1.1 dev eth3 scope link
206.124.146.177 dev eth1 scope link
192.168.2.2 dev tun0 proto kernel scope link src 192.168.2.1
192.168.2.0/24 via 192.168.2.2 dev tun0
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.254
206.124.146.0/24 dev eth3 proto kernel scope link src 206.124.146.176
169.254.0.0/16 dev eth0 scope link
127.0.0.0/8 dev lo scope link
default via 206.124.146.254 dev eth3Отредактируйте этот файл следующим образом:ip route flush table main
ip route add 192.168.1.1 dev eth3 scope link
ip route add 206.124.146.177 dev eth1 scope link
192.168.2.2 dev tun0 proto kernel scope link src 192.168.2.1
192.168.2.0/24 via 192.168.2.2 dev tun0
192.168.2.2 dev tun0 proto kernel scope link src 192.168.2.1
192.168.2.2 dev tun0 proto kernel scope link src 192.168.2.1
ip route add 206.124.146.177 dev eth1 scope link
ip route add 206.124.146.177 dev eth1 scope link
ip route add 206.124.146.177 dev eth1 scope link
ip route flush cacheСохраните этот файл как /etc/shorewall/stopped.В этот файл можно также добавить следующее:ip rule ls | while read priority rule; do
case ${priority%:} in
0|3276[67])
;;
*)
ip rule del $rule
;;
esac
doneЭтот код удаляет все правила маршрутов, за исключением маршрута по умолчанию.Какие функции НЕ выполняет запись в файле providersShorewall - это инструмент для настройки Netfilter, а не процесс, который непрерывно работает в системе, поэтому записи в файле providers не обеспечивают автоматического переключения в случае сбоя одного из каналов связи с Internet .Марсианские пакетыВ конфигурации с несколькими провайдерами часто возникает типичная неполадка с "марсианскими пакетами". Если для сетевых интерфейсов задана опция routefilter в файле /etc/shorewall/interfaces (а вместе с этой опцией должны быть задана опция logmartians), то могут возникать ошибки, и в протоколе будут сообщения следующего вида: Feb 9 17:23:45 gw.ilinx kernel: martian source 206.124.146.176 from 64.86.88.116, on dev eth1
Feb 9 17:23:45 gw.ilinx kernel: ll header: 00:a0:24:2a:1f:72:00:13:5f:07:97:05:08:00Это сообщение может ввести в заблуждение. Исходным IP входящего пакета является 64.86.88.116, а целевым IP - 206.124.146.176. Следует также учитывать, что целевой IP-адрес входящего пакета мог быть уже изменен, либо в DNAT, либо записью в файле /etc/shorewall/masq (SNAT или Masquerade) для первоначального исходящего соединения. Поэтому целевой IP-адрес (206.124.146.176) может отличаться от исходного целевого IP-адреса пришедшего пакета. Эти неполадки могут возникать по следующим причинам: Оба внешних интерфейса подключены на один хаб или коммутатор. Никогда не подключайте несколько интерфейсов файрвола на один хаб, если хотите избежать неприятных и труднообъяснимых неполадок. В файле providers указаны вместе опции loose и balance. Это приводит к тому, что отдельные соединения будут перескакивать между интерфейсами, и будут возникать ошибки. Локальный трафик направляется через один из интерфейсов с помощью маркировки пакетов записью из файла /etc/shorewall/tcrules. Вместо этого следует привязать приложение к соответствующему локальному IP-адресу требуемого интерфейса. См. далее.Если больше ничего не помогает, удалите опцию routefilter для внешнего интерфейса. При этом можно добавить правила для регистрации и сбрасывания пакетов из Интернета, имеющих адрес источника из вашей локальной сети. Например, если локальная сеть в указанной выше конфигурации имеет адреса 192.168.1.0/24, то добавьте следующее правило:#ACTION SOURCE DEST
DROP:info net:192.168.1.0/24 allBe sure the above rule is added before any other rules with net in the SOURCE column.ПримерКонфигурация схемы сети, показанной на рисунке в начале этого документа, описывается в файле /etc/shorewall/providers следующим образом.#NAME NUMBER MARK DUPLICATE INTERFACE GATEWAY OPTIONS COPY
ISP1 1 1 main eth0 206.124.146.254 track,balance eth2
ISP2 2 2 main eth1 130.252.99.254 track,balance eth2Прочие файлы конфигурации будут иметь следующий вид: /etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net eth0 detect …
net eth1 detect …/etc/shorewall/policy:#SOURCE DESTINATION POLICY LIMIT:BURST
net net DROPЕсли соединения файрвола будут перенаправляться с помощью правил /etc/shorewall/tcrules, или если для провайдеров указана опция balance, то независимо от того, есть ли маскируемые хосты, в файл /etc/shorewall/masq необходимо добавить следующие записи.#INTERFACE SUBNET ADDRESS
eth0 130.252.99.27 206.124.146.176
eth1 206.124.146.176 130.252.99.27Эти записи обеспечивают отправку пакетов, созданных в системе файрвола, с правильным исходным IP-адресом, соответствующим интерфейсу, через который они направляются.Если какой-либо из интерфейсов имеет динамический IP-адрес, то указанные правила можно создать с помощью переменных оболочки. Например, если eth0 имеет динамический IP-адрес:/etc/shorewall/params:ETH0_IP=$(find_first_interface_address eth0)/etc/shorewall/masq:#INTERFACE SUBNET ADDRESS
eth0 130.252.99.27 $ETH0_IP
eth1 $ETH0_IP 130.252.99.27Если есть маскируемые хосты, то настройте в файле /etc/shorewall/masq маскарадинг для обоих провайдеров. Например, если маскируются хосты, подключенные через eth2 то это делается так:#INTERFACE SUBNET ADDRESS
eth0 eth2 206.124.146.176
eth1 eth2 130.252.99.27Записи в файле /etc/shorewall/masq никак не влияют на то, через какого провайдера пройдёт конкретное соединение. Для этого применяются правила в файле /etc/shorewall/tcrules или /etc/shorewall/rtrules.Предположим, что требуется направить весь исходящий трафик SMTP из локальной сети через провайдера 2. В файле /etc/shorewall/tcrules укажите следующее (и в версии Shorewall ниже 3.0.0 также задайте TC_ENABLED=Yes в файле /etc/shorewall/shorewall.conf).#MARK SOURCE DEST PROTO PORT(S) CLIENT USER TEST
# PORT(S)
2:P <локальная сеть> 0.0.0.0/0 tcp 25Если провайдеров больше, чем 2Для более чем двух провайдеров требуется внести соответствующие дополнения: Для каждого внешнего адреса в файл /etc/shorewall/masq необходимо добавить записи для случаев, когда соединение, использующее этот адрес как SOURCE, направляется через интерфейс с отличным адресом. Для каждого внешнего интерфейса в файл /etc/shorewall/masq необходимо добавить записи для каждой внутренней подсети, которая будет маскироваться (или для которой применяется SNAT) через этот интерфейс. Например, для eth3 с IP-адресом 16.105.78.4 и шлюзом 16.105.78.254, необходимо добавить следующее:/etc/shorewall/providers:#NAME NUMBER MARK DUPLICATE INTERFACE GATEWAY OPTIONS COPY
ISP1 1 1 main eth0 206.124.146.254 track,balance eth2
ISP2 2 2 main eth1 130.252.99.254 track,balance eth2
ISP3 3 3 main eth3 16.105.78.254 track,balance eth2/etc/shorewall/masq:#INTERFACE SUBNET ADDRESS
eth0 130.252.99.27 206.124.146.176
eth3 130.252.99.27 16.105.78.4
eth1 206.124.146.176 130.252.99.27
eth3 206.124.146.176 16.105.78.4
eth0 16.106.78.4 206.124.146.176
eth1 16.106.78.4 130.252.99.27
eth0 eth2 206.124.146.176
eth1 eth2 130.252.99.27
eth3 eth2 16.105.78.4Приложения, работающие в системе файрволаИногда возникают неполадки с приложениями, работающими в системе файрвола. Это часто имеет место, для для внешних интерфейсов в файле /etc/shorewall/interfaces указана опция routefilter (см. выше). В этом случае рекомендуется связать приложение с определенным локальным IP-адресом вместо 0.Примеры:Squid: В файле squid.conf задайте tcp_outgoing_address равным IP-адресу интерфейса, на котором будет работать Squid.Для OpenVPN задайте опцию local(--local в командной строке с IP-адресом, на котором должен принимать соединения сервер./etc/shorewall/rtrulesФайл /etc/shorewall/rtrules добавлен в Shorewall в версии 3.2.0. Файл rtrules позволяет направлять определенный трафик через конкретного провайдера, как и записи из файла tcrules . Разница между этими двумя файлами состоит в том что записи в rtrules никак не связаны с Netfilter.В Shorewall версий ниже 3.4.0 записи из файла /etc/shorewall/rtrules необратимо изменяют маршрутизацию в системе, то есть эти изменения не отменяются при вызове команды shorewall stop или shorewall clear. Для того чтобы восстановить исходные маршруты, может потребоваться перезапустить сеть. Обычно это делает команда /etc/init.d/network restart или /etc/init.d/networking restart. Обратитесь к документации по сети вашего дистрибутива.Также обратите внимание на предупреждение в разделе Какие функции выполняет запись в файле providers.Правила маршрутизацииПравила маршрутизации управляются ядром Linux. Их можно просмотреть командой ip rule ls . При маршрутизации пакета правила обрабатываются в указанном порядке, пока не будет найден маршрут пакета.gateway:~ # ip rule ls
0: from all lookup local <=== Локальные IP-адреса (система файрвола)
10001: from all fwmark 0x1 lookup Blarg <=== Это и следующее правило генерируются
10002: from all fwmark 0x2 lookup Comcast записями 'MARK' из /etc/shorewall/providers.
20000: from 206.124.146.176 lookup Blarg <=== Это и следующее правило не генерируются, если
20256: from 24.12.22.33 lookup Comcast указана опция 'loose'; они основаны на выводе 'ip addr ls'
32766: from all lookup main <=== Это таблица маршрутизации, показанная в выводе 'iproute -n'
32767: from all lookup default <=== Эта таблица обычно пуста
gateway:~ #В этом примере настроены два провайдера: Blarg и Comcast, с метками MARK 1 и 2 соответственно.Файл rtrulesДалее описаны столбцы файла:SOURCE (Необязательный)IP-адрес (подсеть или хост), с которыми совпадает исходный IP-адрес пакета. Может указываться как имя интерфейса, за которым следует необязательная часть из ":" и адреса. Если указано устройство 'lo', то пакет должен исходить из системы файрвола.DEST (Необязательный)IP-адрес (подсеть или хост), с которыми совпадает целевой IP-адрес пакета.Если опущен SOURCE или DEST, то в укажите в одном из этих полей "-". Необходимо задать хотя бы одно из полей SOURCE или DEST.PROVIDERПровайдер, через которого должен проходить трафик. Может быть задан как имя провайдера или его номер.PRIORITYПриоритет правила, определяющий порядок обработки правил.1000-1999: перед правилами Shorewall, генерируемыми на основе меток 'MARK'11000- 11999: после правил 'MARK', но перед правилами Shorewall, генерируемыми для интерфейсов провайдеров.26000-26999: после интерфейсов провайдеров, но перед правилом 'default'.Правила с одинаковым приоритетом обрабатываются в том порядке, как они указаны в файле.Пример 1: Направить весь трафик, приходящий на eth1, через Comcast.#SOURCE DEST PROVIDER PRIORITY
eth1 - Comcast 1000С этим правилом вывод ip rule ls будет следующим.gateway:~ # ip rule ls
0: from all lookup local
1000: from all iif eth1 lookup Comcast
10001: from all fwmark 0x1 lookup Blarg
10002: from all fwmark 0x2 lookup Comcast
20000: from 206.124.146.176 lookup Blarg
20256: from 24.12.22.33 lookup Comcast
32766: from all lookup main
32767: from all lookup default
gateway:~ #Обратите внимание, что приоритет 1000 приводит к тому, что проверка на eth1 осуществляется перед проверкой fwmark.Пример 2: Используется OpenVPN (маршрутизируемая конфигурация /tunX) в сочетании с несколькими провайдерами. В этом случае необходимо настроить правило, согласно которому трафик OpenVPN будет направляться обратно через интерфейс tunX, а не через какого-либо из провайдеров. 10.8.0.0/24 - это подсеть, выбранная для OpenVPN (сервер 10.8.0.0 255.255.255.0).#SOURCE DEST PROVIDER PRIORITY
- 10.8.0.0/24 main 1000
shorewall-docs-xml-5.2.3/Anatomy.xml 0000664 0000000 0000000 00000105057 13427347317 016122 0 ustar root root
Anatomy of Shorewall 5.0/5.1TomEastep20072009201220152017Thomas 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 5.0 consists of six packages.Shorewall Core. This package
contains the core Shorewall shell libraries and is required to install
any of the other packages. Beginning with Shorewall 5.1.0, it also
includes the Command Line Interface (CLI) program common to all of the
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 firewall.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. These scripts set shell
variables in the shorewallrc file which is normally installed in
/usr/share/shorewall/. The name of the variable is included in
parentheses in the section headings below./sbin ($SBINDIR)The /sbin/shorewall shell program is used to
interact with Shorewall. See shorewall(8)./usr/share/shorewall (${SHAREDIR}/shorewall)The 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.macro.* - 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/shorewall (${CONFDIR}/shorewall)This is where the modifiable IPv4 configuration files are
installed./etc/init.d or /etc/rc.d (depends on distribution) ($INITDIR) or
/lib/systemd/system ($SERVICEDIR)An init script is installed here. Depending on the distribution,
it is named shorewall or
rc.firewall. Only installed on systems where
systemd is not installed.When systemd is installed, the Shorewall .service files are
installed in the directory specified by the SERVICEDIR variable in
/usr/share/shorewall/shorewallrc./var/lib/shorewall (${VARLIB}/shorewall)Shorewall 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:/sbin ($SBINDIR)Prior to Shorewall 5.1.0, the
/sbin/shorewall6 shell program is used to interact
with Shorewall6. See shorewall6(8). Beginning with
Shorewall 5.1.0, /sbin/shorewall6 is a symbolic
link to /sbin/shorewall. See shorewall(8)./usr/share/shorewall6 (${SHAREDIR}/shorewall6)The 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/shorewall6 (${CONFDIR}/shorewall6)This is where the modifiable IPv6 configuration files are
installed./etc/init.d or /etc/rc.d (depends on distribution) ($INITDIR) or
/lib/systemd/system ($SERVICEDIR)An init script is installed here. Depending on the distribution,
it is named shorewall6 or
rc.firewall. Only installed on systems where
systemd is not installed.When systemd is installed, the Shorewall .service files are
installed in the directory specified by the SERVICEDIR variable in
/usr/share/shorewall/shorewallrc./var/lib/shorewall6 (${VARLIB}/shorewall6)Shorewall6 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./sbin ($SBINDIR)The /sbin/shorewall-lite shell program is
used to interact with Shorewall lite. See shorewall-lite(8). Beginning
with Shorewall 5.1.0, /sbin/shorewall-lite is a
symbolic link to /sbin/shorewall. See shorewall(8)./etc/init.d or /etc/rc.d (depends on distribution) ($INITDIR) or
/lib/systemd/system ($SERVICEDIR)An init script is installed here. Depending on the distribution,
it is named shorewall-lite or
rc.firewall. Only installed on systems where
systemd is not installed.When systemd is installed, the Shorewall .service files are
installed in the directory specified by the SERVICEDIR variable in
/usr/share/shorewall/shorewallrc./etc/shorewall-lite (${CONFDIR}/shorewall-lite)This is where the modifiable configuration files are
installed./usr/share/shorewall-lite (${SHAREDIR}/shorewall-lite)The 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-lite (${VARLIB}/shorewall-lite)Shorewall-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).
Beginning with Shorewall 5.1.0,
/sbin/shorewall6-lite is a symbolic link to
/sbin/shorewall. See shorewall(8)./etc/init.d or /etc/rc.d (depends on distribution) ($INITDIR) or
/lib/systemd/system ($SERVICEDIR)An init script is installed here. Depending on the distribution,
it is named shorewall6-lite or
rc.firewall. Only installed on systems where
systemd is not installed.When systemd is installed, the Shorewall .service files are
installed in the directory specified by the SERVICEDIR variable in
/usr/share/shorewall/shorewallrc./etc/shorewall6-lite (${CONFDIR}/shorewall6-lite)This is where the modifiable configuration files are
installed./usr/share/shorewall6-lite (${SHAREDIR}/shorewall6-lite)The 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-lite (${VARLIB}/shorewall6-lite)Shorewall6-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.2.3/PacketHandling.xml 0000664 0000000 0000000 00000031460 13427347317 017362 0 ustar root root
Packet HandlingTomEastep2004200520092014Thomas 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 article will try to help you understand how packets pass
through a firewall configured by Shorewall. You may find it useful to have
a copy of the Netfilter
Overview handy to refer to.The discussion that follows assumes that you are running a current
kernel (2.6.20 or later) with the recommended
options included. Otherwise processing may be somewhat different
from described below depending on the features supported by your
kernel.Where a packet is covered by steps in more than one of the following
sections, processing occurs in the order in which the sections
appear.Packets Entering the Firewall from OutsideCertain processing occurs on packets entering the firewall from the
outside that don't occur for packets that originate on the firewall
itself.The TOS field in the packet is conditionally altered based on
the contents of your /etc/shorewall/tos file.
This occurs in the pretos chain of
the mangle table.Packets are marked based on the contents of your
/etc/shorewall/mangle
(/etc/shorewall/tcrules) file and the setting of
MARK_IN_FORWARD_CHAIN in
/etc/shorewall/shorewall.conf. This occurs in the
tcpre chain of the
mangle table.The destination IP address and/or port number are rewritten
according to DNAT[-] and REDIRECT[-] rules in
/etc/shorewall/rules. For new connection
requests, this occurs in a chain in the nat table
called zone_dnat
where zone is the zone where the request
originated. For packets that are part of an already established
connection, the destination rewriting takes place without any
involvement of a Netfilter rule.If the destination was not rewritten in the previous step then
it may be rewritten based on entries in /etc/shorewall/nat. For new
connection requests, this occurs in a nat table
chain called interface_in where
interface is the interface on which the packet
entered the firewall. For packets that are part of an already
established connection, the destination rewriting takes place without
any involvement of a Netfilter rule.The packet passes through the accounting rules defined in
/etc/shorewall/accounting.If FASTACCEPT=Yes in shorewall.conf and the
packet is part of or related to an existing connection, it is
accepted.The packet is processed according to your Blacklisting configuration
(dynamic blacklist first). If BLACKLISTNEWONLY=Yes in
/etc/shorewall/shorewall.conf then only new
connection requests are processed. Processing occurs in the dynamic
and blacklstIf the interface on which the packet entered the firewall has
the nosmurfs option specified in
/etc/shorewall/interfaces, then if the packet is
a new connection request is checked for being a smurf in the
filter table's smurfs chain.If:the packet will be processed by the firewall itselfthe interface on which the packet arrived has the
dhcp option in
/etc/shorewall/interfaces.packet's protocol is UDP with destination port 67 or
68.then the packet is ACCEPTed in the filter
table's interface_in chain (for
example, eth0_in). Note that if the interface is its associated zones
only interface, then the interface_in chain is
optimized away and its rules are transferred to another chain.If the interface on which the packet entered the firewall has
the tcpflags option specified in
/etc/shorewall/interfaces and the packet's
protocol is TCP then the TCP flags are checked by the tcpflags chain (filter
table).All PacketsRegardless of whether the packet originated on the firewall or came
from outside, certain processing steps are common.Packets are marked based on the contents of your
/etc/shorewall/mangle file and the setting of
MARK_IN_FORWARD_CHAIN in
/etc/shorewall/shorewall.conf. This occurs in the
tcfor chain of the
mangle table.The remaining processing in this list occurs in the
filter table.If either the host sending the packet or the host to which the
packet is addressed is not in any defined zone then the all->all
policy is applied to the packet (including logging). This can occur in
the INPUT, FORWARD or OUTPUT chains.If the packet is part of an established connection or is part of
a related connection then no further processing takes place in the
filter table
(zone12zone2
chain where zone1 is the source zone and
zone2 is the destination zone).The packet is processed according to your
/etc/shorewall/rules file. This happens in chains
named zone12zone2
chain where zone1 is the source zone and
zone2 is the destination zone. Note that in the
presence of nested or
overlapping zones and CONTINUE policies, a packet may go
through more than one of these chains.Note: If the packet gets to this step, it did not match any
rule.If the applicable policy has a common
action then that action is applied (chain has the same name as
the action).If the applicable policy has logging specified, the packet is
logged.The policy is applied (the packet is accepted, dropped or
rejected).Packets Originating on the FirewallPackets that originate on the firewall itself undergo additional
processing.The TOS field in the packet is conditionally altered based on
the contents of your /etc/shorewall/tos file.
This occurs in the outtos chain of
the mangle table.Packets are marked based on the contents of your
/etc/shorewall/mangle file. This occurs in the
tcout chain of the
mangle table.Packets Leaving the FirewallPackets being sent to another host undergo additional
processing.The source IP address only gets rewritten by the first matching
rule below.The source IP address may be rewritten according to DNAT rules
that specify SNAT. If this is a new connection request, then the
rewriting occurs in a nat table chain called
zone_snat where
zone is the destination zone. For packets that
are part of an already established connection, the destination
rewriting takes place without any involvement of a Netfilter
rule.If FASTACCEPT=Yes in shorewall.conf and the
packet is part of or related to an existing connection, it is
accepted.The source IP address may be rewritten according to an entry in
the /etc/shorewall/nat file. If this is a new
connection request, then the rewriting occurs in a
nat table chain called interface_snat where
interface is the interface on which the packet
will be sent. For packets that are part of an already established
connection, the destination rewriting takes place without any
involvement of a Netfilter rule.The source IP address may be rewritten according to an entry in
the /etc/shorewall/masq or
/etc/shorewall/snat file (Shorewall 5.0.14 or
later). If this is a new connection request, then the rewriting occurs
in a nat table chain called interface_masq where
interface is the interface on which the packet
will be sent. For packets that are part of an already established
connection, the destination rewriting takes place without any
involvement of a Netfilter rule.
shorewall-docs-xml-5.2.3/OpenVZ.xml 0000664 0000000 0000000 00000067420 13427347317 015674 0 ustar root root
Shorewall and OpenVZTomEastep2009Thomas 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.IntroductionOpen Virtuoso (OpenVZ)
is an open source kernel-based virtualization solution from
Parallels (formerly
SWSoft). Virtual servers take the form of
containers (the OpenVZ documentation calls these
Virtual Environments or VEs)
which are created via templates. Templates are
available for a wide variety of distributions and architectures.OpenVZ requires a patched kernel. Beginning with Lenny,
Debian supplies OpenVZ kernels through the standard
stable repository.Shorewall on an OpenVZ HostAs with any Shorewall installation involving other software, we
suggest that you first install OpenVZ and get it working before attempting
to add Shorewall. Alternatively, execute shorewall
clear while installing and
configuring OpenVZ.NetworkingThe default OpenVZ networking configuration uses Proxy ARP. You
assign containers IP addresses in the IP network from one of your
interfaces and you are expected to set the proxy_arp flag on that
interface
(/proc/sys/net/ipv4/conf/interface/proxy_arp).OpenVZ creates a point-to-point virtual interface in the host with
a rather odd configuration.Example (Single VE with IP address 206.124.146.178):gateway:~# ip addr ls dev venet0
10: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
link/void
gateway:~# ip route ls dev venet0
206.124.146.178 scope link
gateway:~# The interface has no IP configuration yet it has a route to
206.124.146.178!From within the VE with IP address 206.124.146.178, we have the
following:server:~ # ip addr ls
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 brd 127.255.255.255 scope host lo
inet 127.0.0.2/8 brd 127.255.255.255 scope host secondary lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
link/void
inet 127.0.0.1/32 scope host venet0
inet 206.124.146.178/32 scope global venet0:0
server:~ # ip route ls
192.0.2.0/24 dev venet0 scope link
127.0.0.0/8 dev lo scope link
default via 192.0.2.1 dev venet0
server:~ # There are a couple of unique features of this
configuration:127.0.0.1/32 is configured on venet0 although the main routing
table routes loopback traffic through the lo interface as normal.There is a route to 192.0.2.0/24 through venet0 even though
the interface has no IP address in that network. Note: 192.0.2.0/24
is reserved for use in documentation and for testing.The default route is via 192.0.2.1 yet there is no interface
on the host with that IP address.All of this doesn't really affect the Shorewall configuration but
it is interesting none the less.Shorewall ConfigurationWe recommend handling the strange OpenVZ configuration in
Shorewall as follows:/etc/shorewall/zones:###############################################################################
#ZONE TYPE OPTIONS IN_OPTION OUT_OPTIONS
net ipv4
vz ipv4/etc/shorewall/interfaces:###############################################################################
#ZONE INTERFACE OPTIONS
net eth0 proxyarp=1
vz venet0 routeback,arp_filter=0Multi-ISPIf you run Shorewall Multi-ISP support on the host, you should
arrange for traffic to your containers to use the main routing table. In
the configuration shown here, this entry in /etc/shorewall/rtrules is
appropriate:#SOURCE DEST PROVIDER PRIORITY
- 206.124.146.178 main 1000RFC 1918 Addresses in a ContainerYou can assign an RFC 1918 address to a VE and use masquerade/SNAT
to provide Internet access to the container. This is just a normal
simple Shorewall configuration as shown in the Two-interface Quick Start Guide. In this
configuration the firewall's internal interface is venet0. Be sure to include the options
shown above.Shorewall in an OpenVZ Virtual EnvironmentIf you have obtained an OpenVZ VE from a hosting service provider,
you may find it difficult to configure any type of firewall within your
VE. There are two VE parameters that control iptables behavior within the
container:--iptables name Restrict access to iptables modules inside a container (The
OpenVZ claims that by default all iptables modules that are loaded
in the host system are accessible inside a container; I haven't
tried that).You can use the following values for
name: ,
, ,
, ,
, ,
, ,
, ,
, ,
,
, ,
, ,
, ,
, ,
, .If your provider is using this option, you may be in deep
trouble trying to use Shorewall in your container. Look at the
output of shorewall show capabilities and weep.
Then try to get your provider to remove this restriction on your
container.--numiptent numThis parameter limits the number of iptables rules that are
allowed within the container. The default is 100 which is too small
for a Shorewall configuration. We recommend setting this to at least
200.if you see annoying error messages as shown below during
start/restart, remove the module-init-tools package from the VE.server:/etc/shorewall # shorewall restart
Compiling...
Compiling /etc/shorewall/zones...
Compiling /etc/shorewall/interfaces...
Determining Hosts in Zones...
Preprocessing Action Files...
Pre-processing /usr/share/shorewall/action.Drop...
Pre-processing /usr/share/shorewall/action.Reject...
Compiling /etc/shorewall/policy...
Adding Anti-smurf Rules
Adding rules for DHCP
Compiling TCP Flags filtering...
Compiling Kernel Route Filtering...
Compiling Martian Logging...
Compiling MAC Filtration -- Phase 1...
Compiling /etc/shorewall/rules...
Generating Transitive Closure of Used-action List...
Processing /usr/share/shorewall/action.Reject for chain Reject...
Processing /usr/share/shorewall/action.Drop for chain Drop...
Compiling MAC Filtration -- Phase 2...
Applying Policies...
Generating Rule Matrix...
Creating iptables-restore input...
Compiling iptables-restore input for chain mangle:...
Compiling /etc/shorewall/routestopped...
Shorewall configuration compiled to /var/lib/shorewall/.restart
Restarting Shorewall....
Initializing...
Processing /etc/shorewall/init ...
Processing /etc/shorewall/tcclear ...
Setting up Route Filtering...
Setting up Martian Logging...
Setting up Proxy ARP...
Setting up Traffic Control...
Preparing iptables-restore input...
Running /usr/sbin/iptables-restore...
FATAL: Could not load /lib/modules/2.6.26-2-openvz-amd64/modules.dep: No such file or directory
FATAL: Could not load /lib/modules/2.6.26-2-openvz-amd64/modules.dep: No such file or directory
FATAL: Could not load /lib/modules/2.6.26-2-openvz-amd64/modules.dep: No such file or directory
FATAL: Could not load /lib/modules/2.6.26-2-openvz-amd64/modules.dep: No such file or directory
IPv4 Forwarding Enabled
Processing /etc/shorewall/start ...
Processing /etc/shorewall/started ...
done.
Working ExampleThis section presents a working example. This is the configuration
at shorewall.net during the summer of 2009.The network diagram is shown below.The two systems shown in the green box are OpenVZ Virtual
Environments (containers).OpenVZ ConfigurationIn the files below, items in bold
font are relevant to the networking/Shorewall
configuration./etc/vz/conf (long lines folded for
clarity).## Global parameters
VIRTUOZZO=yes
LOCKDIR=/var/lib/vz/lock
DUMPDIR=/var/lib/vz/dump
VE0CPUUNITS=1000
## Logging parameters
LOGGING=yes
LOGFILE=/var/log/vzctl.log
LOG_LEVEL=0
VERBOSE=0
## Disk quota parameters
DISK_QUOTA=no
VZFASTBOOT=no
# The name of the device whose ip address will be used as source ip for VE.
# By default automatically assigned.
VE_ROUTE_SRC_DEV="eth3"
# Controls which interfaces to send ARP requests and modify APR tables on.
NEIGHBOUR_DEVS=detect
## Template parameters
TEMPLATE=/var/lib/vz/template
## Defaults for VEs
VE_ROOT=/home/vz/root/$VEID
VE_PRIVATE=/home/vz/private/$VEID
CONFIGFILE="vps.basic"
#DEF_OSTEMPLATE="fedora-core-4"
DEF_OSTEMPLATE="debian"
## Load vzwdog module
VZWDOG="no"
## IPv4 iptables kernel modules
IPTABLES="iptable_filter iptable_mangle ipt_limit ipt_multiport ipt_tos
ipt_TOS ipt_REJECT ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_LOG ipt_length
ip_conntrack ip_conntrack_ftp ip_conntrack_irc ipt_conntrack
ipt_state ipt_helper iptable_nat ip_nat_ftp ip_nat_irc ipt_REDIRECT
xt_mac ipt_owner"
## Enable IPv6
IPV6="no"/etc/vz/conf/101.conf:ONBOOT="yes"
# UBC parameters (in form of barrier:limit)
KMEMSIZE="574890800:589781600"
LOCKEDPAGES="256:256"
PRIVVMPAGES="1073741824:2137483648"
SHMPAGES="21504:21504"
NUMPROC="240:240"
PHYSPAGES="0:9223372036854775807"
VMGUARPAGES="262144:9223372036854775807"
OOMGUARPAGES="26112:9223372036854775807"
NUMTCPSOCK="360:360"
NUMFLOCK="188:206"
NUMPTY="16:16"
NUMSIGINFO="256:256"
TCPSNDBUF="1720320:2703360"
TCPRCVBUF="1720320:2703360"
OTHERSOCKBUF="1126080:2097152"
DGRAMRCVBUF="262144:262144"
NUMOTHERSOCK="360:360"
DCACHESIZE="3409920:3624960"
NUMFILE="9312:9312"
AVNUMPROC="180:180"
NUMIPTENT="200:200"
# Disk quota parameters (in form of softlimit:hardlimit)
DISKSPACE="1048576:1153024"
DISKINODES="200000:220000"
QUOTATIME="0"
# CPU fair sheduler parameter
CPUUNITS="1000"
VE_ROOT="/home/vz/root/$VEID"
VE_PRIVATE="/home/vz/private/$VEID"
OSTEMPLATE="suse-11.1-x86_64"
ORIGIN_SAMPLE="vps.basic"
HOSTNAME="lists.shorewall.net"
IP_ADDRESS="206.124.146.177"
NAMESERVER="127.0.0.1"
NAME="lists"
SEARCHDOMAIN="shorewall.net"This VE is the main server at shorewall.net. Note that some of the
memory parameters are set ridiculously large -- I got tired of
out-of-memory issues./etc/vz/conf/102.conf (nearly default
configuration on Debian):ONBOOT="yes"
# UBC parameters (in form of barrier:limit)
KMEMSIZE="14372700:14790164"
LOCKEDPAGES="256:256"
PRIVVMPAGES="65536:69632"
SHMPAGES="21504:21504"
NUMPROC="240:240"
PHYSPAGES="0:9223372036854775807"
VMGUARPAGES="33792:9223372036854775807"
OOMGUARPAGES="26112:9223372036854775807"
NUMTCPSOCK="360:360"
NUMFLOCK="188:206"
NUMPTY="16:16"
NUMSIGINFO="256:256"
TCPSNDBUF="1720320:2703360"
TCPRCVBUF="1720320:2703360"
OTHERSOCKBUF="1126080:2097152"
DGRAMRCVBUF="262144:262144"
NUMOTHERSOCK="360:360"
DCACHESIZE="3409920:3624960"
NUMFILE="9312:9312"
AVNUMPROC="180:180"
NUMIPTENT="200:200"
# Disk quota parameters (in form of softlimit:hardlimit)
DISKSPACE="1048576:1153024"
DISKINODES="200000:220000"
QUOTATIME="0"
# CPU fair sheduler parameter
CPUUNITS="1000"
VE_ROOT="/home/vz/root/$VEID"
VE_PRIVATE="/home/vz/private/$VEID"
OSTEMPLATE="debian-5.0-amd64-minimal"
ORIGIN_SAMPLE="vps.basic"
HOSTNAME="server.shorewall.net"
IP_ADDRESS="206.124.146.178"
NAMESERVER="206.124.146.177"
NAME="server"I really don't use this server for anything currently but I'm
planning to eventually splt the services between the two VEs.Shorewall Configuration on the HostBelow are excerpts from the configuration files as they pertain to
the OpenVZ environment./etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
net ipv4 #Internet
loc ipv4 #Local wired Zone
dmz ipv4 #DMZ
.../etc/shorewall/params:NET_IF=eth3
INT_IF=eth1
VPS_IF=venet0
.../etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
net $NET_IF dhcp,blacklist,tcpflags,optional,routefilter=0,nosmurfs,logmartions=0,proxyarp=1
loc $INT_IF dhcp,logmartians=1,routefilter=1,nets=(172.20.1.0/24),tcpflags
dmz $VPS_IF logmartians=0,routefilter=0,nets=(206.124.146.177,206.124.146.178),routeback
...This is a multi-ISP configuration so entries are required
in /etc/shorewall/rtrules:#SOURCE DEST PROVIDER PRIORITY
- 172.20.0.0/24 main 1000
- 206.124.146.177 main 1001
- 206.124.146.178 main 1001Shorewall Configuration on ServerIf you are running Debian Squeeze, Shorewall will not work in an
OpenVZ container. This is a Debian OpenVZ issue and not a Shorewall
issue.I have set up Shorewall on Server (206.124.146.178) just to have
an environment to test with. It is a quite vanilla one-interface
configuration./etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
net ipv4/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net venet0 detect dhcp,tcpflags,logmartians,nosmurfsWorking Example Using a BridgeThis is the configuration at shorewall.net during the spring of
2010. Rather than using the venet0 configuration shown above, this
configuration uses a bridge in preparation for adding IPv6 support in the
DMZ. The eth0 interface in each of the containers is statically configured
using the distributions' configuration tools
(/etc/network/interfaces on Debian and Yast on
OpenSuSE).The network diagram is shown below.The two systems shown in the green box are OpenVZ Virtual
Environments (containers).Bridge ConfigurationThe following stanza in /etc/network/interfaces on the host
configures the bridge.auto vzbr0
iface vzbr0 inet static
pre-up /usr/sbin/brctl addbr vzbr0
address 206.124.146.176
network 206.124.146.176
broadcast 206.124.146.176
netmask 255.255.255.255
post-down /usr/sbin/brctl delbr br0
OpenVZ ConfigurationIn the files below, items in bold
font show the changes from the preceeding example./etc/vz/conf (long lines folded for
clarity).## Global parameters
VIRTUOZZO=yes
LOCKDIR=/var/lib/vz/lock
DUMPDIR=/var/lib/vz/dump
VE0CPUUNITS=1000
## Logging parameters
LOGGING=yes
LOGFILE=/var/log/vzctl.log
LOG_LEVEL=0
VERBOSE=0
## Disk quota parameters
DISK_QUOTA=no
VZFASTBOOT=no
# The name of the device whose ip address will be used as source ip for VE.
# By default automatically assigned.
VE_ROUTE_SRC_DEV="eth3"
# Controls which interfaces to send ARP requests and modify APR tables on.
NEIGHBOUR_DEVS=detect
## Template parameters
TEMPLATE=/var/lib/vz/template
## Defaults for VEs
VE_ROOT=/home/vz/root/$VEID
VE_PRIVATE=/home/vz/private/$VEID
CONFIGFILE="vps.basic"
#DEF_OSTEMPLATE="fedora-core-4"
DEF_OSTEMPLATE="debian"
## Load vzwdog module
VZWDOG="no"
## IPv4 iptables kernel modules
IPTABLES="iptable_filter iptable_mangle ipt_limit ipt_multiport ipt_tos
ipt_TOS ipt_REJECT ipt_TCPMSS ipt_tcpmss ipt_ttl ipt_LOG ipt_length
ip_conntrack ip_conntrack_ftp ip_conntrack_irc ipt_conntrack
ipt_state ipt_helper iptable_nat ip_nat_ftp ip_nat_irc ipt_REDIRECT
xt_mac ipt_owner"
## Enable IPv6
IPV6="no"/etc/vz/conf/101.conf:ONBOOT="yes"
# UBC parameters (in form of barrier:limit)
KMEMSIZE="574890800:589781600"
LOCKEDPAGES="256:256"
PRIVVMPAGES="1073741824:2137483648"
SHMPAGES="21504:21504"
NUMPROC="240:240"
PHYSPAGES="0:9223372036854775807"
VMGUARPAGES="262144:9223372036854775807"
OOMGUARPAGES="26112:9223372036854775807"
NUMTCPSOCK="360:360"
NUMFLOCK="188:206"
NUMPTY="16:16"
NUMSIGINFO="256:256"
TCPSNDBUF="1720320:2703360"
TCPRCVBUF="1720320:2703360"
OTHERSOCKBUF="1126080:2097152"
DGRAMRCVBUF="262144:262144"
NUMOTHERSOCK="360:360"
DCACHESIZE="3409920:3624960"
NUMFILE="9312:9312"
AVNUMPROC="180:180"
NUMIPTENT="200:200"
# Disk quota parameters (in form of softlimit:hardlimit)
DISKSPACE="1048576:1153024"
DISKINODES="200000:220000"
QUOTATIME="0"
# CPU fair sheduler parameter
CPUUNITS="1000"
VE_ROOT="/home/vz/root/$VEID"
VE_PRIVATE="/home/vz/private/$VEID"
OSTEMPLATE="suse-11.1-x86_64"
ORIGIN_SAMPLE="vps.basic"
HOSTNAME="lists.shorewall.net"
NAMESERVER="127.0.0.1"
NAME="lists"
SEARCHDOMAIN="shorewall.net"
NETIF="ifname=eth0,mac=00:18:51:22:24:81,host_ifname=veth101.0,host_mac=00:18:51:B6:1A:F1"This VE is the mail server at shorewall.net (MX and IMAP). Note
that some of the memory parameters are set ridiculously large -- I got
tired of out-of-memory issues./etc/vz/conf/102.conf (nearly default
configuration on Debian):ONBOOT="yes"
# UBC parameters (in form of barrier:limit)
KMEMSIZE="14372700:14790164"
LOCKEDPAGES="256:256"
PRIVVMPAGES="65536:69632"
SHMPAGES="21504:21504"
NUMPROC="240:240"
PHYSPAGES="0:9223372036854775807"
VMGUARPAGES="33792:9223372036854775807"
OOMGUARPAGES="26112:9223372036854775807"
NUMTCPSOCK="360:360"
NUMFLOCK="188:206"
NUMPTY="16:16"
NUMSIGINFO="256:256"
TCPSNDBUF="1720320:2703360"
TCPRCVBUF="1720320:2703360"
OTHERSOCKBUF="1126080:2097152"
DGRAMRCVBUF="262144:262144"
NUMOTHERSOCK="360:360"
DCACHESIZE="3409920:3624960"
NUMFILE="9312:9312"
AVNUMPROC="180:180"
NUMIPTENT="200:200"
# Disk quota parameters (in form of softlimit:hardlimit)
DISKSPACE="1048576:1153024"
DISKINODES="200000:220000"
QUOTATIME="0"
# CPU fair sheduler parameter
CPUUNITS="1000"
VE_ROOT="/home/vz/root/$VEID"
VE_PRIVATE="/home/vz/private/$VEID"
OSTEMPLATE="debian-5.0-amd64-minimal"
ORIGIN_SAMPLE="vps.basic"
HOSTNAME="server.shorewall.net"
NAMESERVER="206.124.146.177"
NAME="server"
NETIF="ifname=eth0,mac=00:18:51:22:24:80,host_ifname=veth102.0,host_mac=00:18:51:B6:1A:F0"This server runs the rest of the services for shorewall.net (web
server, ftp server, rsyncd, etc.).With a bridged configuration, the VIF for a VE must be added to
the bridge when the VE starts. That is accomplished using
mount files./etc/vz/conf/101.mount:#!/bin/bash
# This script source VPS configuration files in the same order as vzctl does
# if one of these files does not exist then something is really broken
[ -f /etc/vz/vz.conf ] || exit 1
[ -f $VE_CONFFILE ] || exit 1
# source both files. Note the order, it is important
. /etc/vz/vz.conf
. $VE_CONFFILE
# Add the VIF to the bridge after VE has started
{
BRIDGE=vzbr0
DEV=veth101.0
while sleep 1; do
/sbin/ifconfig $DEV 0 >/dev/null 2>&1
if [ $? -eq 0 ]; then
/usr/sbin/brctl addif $BRIDGE $DEV
break
fi
done
} &/etc/vz/conf/102.mount:#!/bin/bash
# This script source VPS configuration files in the same order as vzctl does
# if one of these files does not exist then something is really broken
[ -f /etc/vz/vz.conf ] || exit 1
[ -f $VE_CONFFILE ] || exit 1
# source both files. Note the order, it is important
. /etc/vz/vz.conf
. $VE_CONFFILE
# Add VIF to bridge after VE has started
{
BRIDGE=vzbr0
DEV=veth102.0
while sleep 1; do
/sbin/ifconfig $DEV 0 >/dev/null 2>&1
if [ $? -eq 0 ]; then
/usr/sbin/brctl addif $BRIDGE $DEV
break
fi
done
} &Shorewall Configuration on the HostBelow are excerpts from the configuration files as they pertain to
the OpenVZ environment. Again, bold font indicates change from the prior
configuration./etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
net ipv4 #Internet
loc ipv4 #Local wired Zone
dmz ipv4 #DMZ
.../etc/shorewall/params:NET_IF=eth3
INT_IF=eth1
VPS_IF=vzbr0
.../etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
net $NET_IF dhcp,blacklist,tcpflags,optional,routefilter=0,nosmurfs,logmartions=0
loc $INT_IF dhcp,logmartians=1,routefilter=1,nets=(172.20.1.0/24),tcpflags
dmz $VPS_IF logmartians=0,routefilter=0,nets=(206.124.146.177,206.124.146.178),routeback
.../etc/shorewall/proxyarp:#ADDRESS INTERFACE EXTERNAL HAVEROUTE PERSISTENT
206.124.146.177 DMZ_IF eth2 no yes
206.124.146.178 DMZ_IF eth2 no yesThis is a multi-ISP configuration so entries are required in
/etc/shorewall/rtrules:#SOURCE DEST PROVIDER PRIORITY
- 172.20.0.0/24 main 1000
- 206.124.146.177 main 1001
- 206.124.146.178 main 1001Shorewall Configuration on ServerI have set up Shorewall on VE 101 (206.124.146.178) just to have
an environment to test with. It is a quite vanilla one-interface
configuration./etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
net ipv4/etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
net eth0 dhcp,tcpflags,logmartians,nosmurfs
shorewall-docs-xml-5.2.3/XenMyWay.xml 0000664 0000000 0000000 00000116643 13427347317 016236 0 ustar root root
Xen and the Art of ConsolidationTomEastep20062007Thomas 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 3.0 and later. If you are running
a version of Shorewall earlier than Shorewall 3.0.0 then please see the
documentation for that release.Xen Network EnvironmentXen is a
paravirtualization tool that allows you to run
multiple virtual machines on one physical machine. It is available on a
wide number of platforms and is included in recent
SUSE distributions.Xen refers to the virtual machines as
Domains. Domains are numbered with the first domain
being domain 0, the second domain 1, and so on. Domain 0
(Dom0) is special because that is the domain
created when the machine is booted. Additional domains (called
DomU's) are created using the xm
create command from within Domain 0. Additional domains can also
be created automatically at boot time by using the
xendomains service.Xen virtualizes a network interface named eth0This assumes the default Xen configuration created by
xend and assumes that the host system has a single
Ethernet interface named eth0.in each domain. In Dom0, Xen also creates a bridge (xenbr0) and a number of virtual interfaces
as shown in the following diagram.I use the term Extended Dom0 to distinguish
the bridge and virtual interfaces from Dom0 itself. That distinction is
important when we try to apply Shorewall in this environment.The bridge has a number of ports:peth0 — This is the port that connects to the physical network
interface in your system.vif0.0 — This is the bridge port that is used by traffic to/from
Domain 0.vifX.0 — This is the bridge port that is used by traffic to/from
Domain X.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).My work system.My Linux desktop (wookie, which is actually the old public
server box)Most of the Linux systems run SUSE 10.1; my
personal Linux desktop system and our Linux Laptop run
Ubuntu "Dapper Drake".The configuration described below uses a
bridged Xen Networking configuration; if you want to see how to accomplish
a similar configuration using a Routed Xen configuration then please see
this article. I am now using the
routed configuration because it results in one fewer domains to
administer.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 the
switch in my office. That switch is cabled to a second switch in my
wife's office where my wife has her desktop and networked printer (I
sure wish that there had been wireless back when I strung that CAT-5
cable halfway across the house).eth1 -- connected to our
DSL "Modem".eth2 -- connected to a
Wireless Access Point (WAP) that interfaces to our wireless
network.There are three Xen domains.Dom0 (DNS name ursa.shorewall.net) is used as a local file
server (NFS and Samba).The first DomU (Dom name firewall, DNS name gateway.shorewall.net) is
used as our main firewall and wireless gateway.The second DomU (Dom name lists, DNS name lists.shorewall.net) is used as
a public Web/FTP/Mail/DNS server.Shorewall runs in Dom0 and in the firewall domain.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. 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 three domains.
I use partitions on my hard drives for DomU storage devices.
/boot/grub/menu.lst — here is the entry
that boots Xen in Dom0.title XEN
root (hd0,1)
kernel /boot/xen.gz dom0_mem=458752 sched=bvt
module /boot/vmlinuz-xen root=/dev/hda2 vga=0x31a selinux=0 resume=/dev/hda1 splash=silent showopts
module /boot/initrd-xen/etc/modprobe.conf.localeth1 (PCI 00:09.0) and
eth2 (PCI 00:0a.0) are
delegated to the firewall DomU where they become eth3 and eth4 respectively. The SUSE 10.1 Xen
kernel compiles pciback as a module so the instructions for PCI
delegation in the Xen Users Manual can't be followed directly (see
http://wiki.xensource.com/xenwiki/Assign_hardware_to_DomU_with_PCIBack_as_module).options pciback hide=(00:09.0)(00:0a.0)
install tulip /sbin/modprobe pciback ; /sbin/modprobe --first-time --ignore-install tulip
options netloop nloopbacks=1/etc/xen/auto/01-firewall — configuration
file for the firewall domain# -*- mode: python; -*-
# configuration name:
name = "firewall"
# usable ram:
memory = 384
# kernel and initrd:
kernel = "/xen2/vmlinuz-xen"
ramdisk = "/xen2/initrd-xen"
# boot device:
root = "/dev/hdb2"
# boot to run level:
extra = "3"
# network interface:
vif = [ 'mac=aa:cc:00:00:00:02, bridge=xenbr0', 'mac=aa:cc:00:00:00:03, bridge=xenbr1' ]
# Interfaces delegated from Dom0
pci=[ '00:09.0' , '00:0a.0' ]
# storage devices:
disk = [ 'phy:hdb2,hdb2,w' ]/etc/xen/auto/02-lists — configuration file
for the lists domain# -*- mode: python; -*-
# configuration name:
name = "lists"
# usable ram:
memory = 512
# kernel and initrd:
kernel = "/xen2/vmlinuz-xen"
ramdisk = "/xen2/initrd-xen"
# boot device:
root = "/dev/hda3"
# boot to run level:
extra = "3"
# network interface:
vif = [ 'mac=aa:cc:00:00:00:01, bridge=xenbr1' ]
hostname = name
# storage devices:
disk = [ 'phy:hda3,hda3,w' ]
With all three Xen domains up and running, the system looks as
shown in the following diagram.The zones correspond to the Shorewall zones in the firewall DomU
configuration.If you want to run a simple NAT gateway in a Xen DomU, just omit
the second bridge (xenbr1), the second delegated interface, and the
second DomU from the above configuration. You can then install the
normal Shorewall two-interface sample
configuration in the DomU.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 the
firewall domU 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
domain when its eth0 device
was brought up:ethtool -K eth0 tx offUnder SUSE 10.1, I placed the following in
/etc/sysconfig/network/if-up.d/resettx (that file
is executable):#!/bin/sh
if [ $2 = eth0 ]; then
ethtool -K eth0 tx off
echo "TX Checksum reset on eth0"
fiUnder 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 SUSE 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.SUSE 10.1 includes Xen 3.0.2 which supports PCI delegation. The
network interfaces that connect to the net and wifi zones are delegated
to the firewall DomU.When Shorewall starts during bootup of Dom0, it creates the two
bridges using this /etc/shorewall/init extension
script:
for bridge in xenbr0 xenbr1; do
if [ -z "$(/sbin/brctl show 2> /dev/null | fgrep $bridge)" ]; then
/sbin/brctl addbr $bridge
/sbin/ip link set dev $bridge up
fi
done
Dom0 ConfigurationThe goals for the Shorewall configuration in Dom0 are as
follows:Allow traffic to flow unrestricted through the two bridges.
This is done by configuring the hosts connected to each bridge as a
separate zone and relying on Shorewall's implicit intra-zone ACCEPT
policy to permit traffic through the bridge.Ensure that there is no stray traffic between the zones. This
is a "belt+suspenders" measure since there should be no routing
between the bridges (because they don't have IP addresses).The configuration is a simple one:
/etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
loc ipv4
dmz ipv4/etc/shorewall/policy (Note the unusual use
of an ACCEPT all->all policy):#SOURCE DEST POLICY LOGLEVEL LIMIT
dmz all REJECT info
all dmz REJECT info
all all ACCEPT/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
loc xenbr0 192.168.1.255 dhcp,routeback
dmz xenbr1 - routeback
Firewall DomU ConfigurationIn the firewall DomU, 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 two laptops and a bridged OpenVPN server for the wireless
network in our home. Here is the firewall's view of the network:The two 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 SUSE network
configuration.
/etc/shorewall/shorewall.conf:STARTUP_ENABLED=Yes
VERBOSITY=0
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=/usr/sbin/iptables
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin
SHOREWALL_SHELL=/bin/bash
SUBSYSLOCK=
MODULESDIR=
CONFIG_PATH=/etc/shorewall:/usr/share/shorewall
RESTOREFILE=standard
IPSECFILE=zones
IP_FORWARDING=On
ADD_IP_ALIASES=No
ADD_SNAT_ALIASES=No
RETAIN_ALIASES=No
TC_ENABLED=Internal
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_TTL=60
SAVE_IPSETS=No
MAPOLDACTIONS=No
FASTACCEPT=Yes
BLACKLIST_DISPOSITION=DROP
MACLIST_TABLE=mangle
MACLIST_DISPOSITION=DROP
TCP_FLAGS_DISPOSITION=DROP/etc/shorewall/zones:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
fw firewall
net ipv4 #Internet
loc ipv4 #Local wired Zone
dmz ipv4 #DMZ
vpn ipv4 #Open VPN clients
wifi ipv4 #Local Wireless Zone/etc/shorewall/policy:#SOURCE DEST POLICY LOGLEVEL LIMIT
$FW $FW ACCEPT
$FW net ACCEPT
loc net ACCEPT
$FW vpn ACCEPT
vpn net ACCEPT
vpn loc ACCEPT
loc vpn ACCEPT
$FW loc ACCEPT
wifi all REJECT $LOG
loc $FW 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/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=eth0
DMZ_IF=eth1
EXT_IF=eth3
WIFI_IF=eth4
OMAK=<IP address at our second home>/etc/shorewall/init:echo 1 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_be_liberal/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net $EXT_IF 206.124.146.255 dhcp,logmartians,blacklist,tcpflags,nosmurfs
dmz $DMZ_IF 192.168.0.255 logmartians
loc $INT_IF 192.168.1.255 dhcp,routeback,logmartians
wifi $WIFI_IF 192.168.3.255 dhcp,maclist
vpn tun+ -
/etc/shorewall/nat:#EXTERNAL INTERFACE INTERNAL ALLINTS LOCAL
206.124.146.178 $EXT_IF 192.168.1.3 No No #Wookie
206.124.146.180 $EXT_IF 192.168.1.6 No No #Work LapTop
/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 SUBNET ADDRESS PROTO DPORT IPSEC
+$EXT_IF:192.168.1.1 0.0.0.0/0 192.168.1.254
$EXT_IF 192.168.0.0/22 206.124.146.179/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/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
/etc/shorewall/actions:#ACTION
Mirrors # Accept traffic from Shorewall Mirrors
/etc/shorewall/action.Mirrors:#TARGET SOURCE DEST PROTO PORT SPORT ORIGDEST RATE
ACCEPT $MIRRORS/etc/shorewall/rules:?SECTION NEW
###############################################################################################################################################################################
#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER
###############################################################################################################################################################################
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
#
DROP loc:!192.168.0.0/22 fw # Silently drop traffic with an HP source IP from my XP box
ACCEPT loc fw tcp 22
ACCEPT loc fw tcp time,631,8080
ACCEPT loc fw udp 161,ntp,631
ACCEPT loc:192.168.1.5 fw udp 111
DROP loc fw tcp 3185 #SUSE Meta pppd
Ping(ACCEPT) loc fw
REDIRECT loc 3128 tcp 80 - !206.124.146.177
###############################################################################################################################################################################
# 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
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 Wookie
#
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
#
# 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 dmz fw tcp 161,ssh
ACCEPT dmz fw udp 161
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
###############################################################################################################################################################################
# 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
/etc/shorewall/tcdevices#INTERFACE IN_BANDWITH OUT_BANDWIDTH
$EXT_IF 1300kbit 384kbit/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/etc/shorewall/mangle#ACTION SOURCE DEST PROTO DPORT SPORT USER TEST
CLASSIFY(1:110) 192.168.0.0/22 $EXT_IF #Our internal nets get priority
#over the server
CLASSIFY(1:130) 206.124.146.177 $EXT_IF tcp - 873 #Throttle rsync traffic to the
#Shorewall Mirrors.
The tap0 device used by the bridged OpenVPN server is bridged to
eth0 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="eth0"
#
# 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.2.3/standalone.xml 0000664 0000000 0000000 00000073105 13427347317 016640 0 ustar root root
Standalone 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 Shorewall on a standalone Linux system is very easy 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 one of its most common configurations:Linux systemSingle external IP addressConnection through Cable Modem, DSL,
ISDN, Frame Relay, dial-up... or connected to a
LAN and you simply wish to protect your Linux
system from other systems on that LAN.System 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]#Before you startI recommend that you read through the guide first to familiarize
yourself with what's involved then go back through it again making your
configuration changes.If 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 dos2unixConventionsPoints 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 only need to deal with a few of these as described in this
guide. After you have installed
Shorewall, you can find the Samples as follows:If you installed using an RPM, the samples
will be in the Samples/one-interface 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 one-interface
/usr/share/doc/packages/shorewall/Samples/one-interface
/usr/share/doc/packages/shorewall/Samples/one-interface/interfaces
/usr/share/doc/packages/shorewall/Samples/one-interface/policy
/usr/share/doc/packages/shorewall/Samples/one-interface/rules
/usr/share/doc/packages/shorewall/Samples/one-interface/zones
~#If you installed using the tarball, the samples are in the
Samples/one-interface directory
in the tarball.If
you installed using a Shorewall 4.x .deb, the samples are in /usr/share/doc/shorewall/examples/one-interface..
You do not need the shorewall-doc package to have access to the
samples.Note to Debian UsersYou will find that your /etc/shorewall directory is empty. This is
intentional. If you need configuration files other than those found in
/usr/share/doc/shorewall/examples/one-interface,
they 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 one-interface sample
configuration, only two zones are defined:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall
net ipv4Shorewall zones are defined in /etc/shorewall/zones.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 (fw in the above example) 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 policy 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 one-interface sample has the following policies:#SOURCE DEST POLICY LOGLEVEL LIMIT
$FW net ACCEPT
net all DROP info
all all REJECT infoThe above policy will:allow all connection requests from the firewall to the
Internetdrop (ignore) all connection requests from the Internet to your
firewallreject all other connection requests (Shorewall requires this
catchall policy).The word info in the LOG LEVEL column for the
last two policies indicates that packets dropped or rejected under those
policies should be logged at that
level.At this point, edit your /etc/shorewall/policy
and make any changes that you wish.External InterfaceThe firewall has a single network interface. Where Internet
connectivity is through a cable or DSL
Modem, the External Interface will be
the Ethernet adapter (eth0) that
is connected to that Modemunless 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 using
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.2.2 dev tun0 proto kernel scope link src 192.168.2.1
10.13.10.0/24 dev tun1 scope link
192.168.2.0/24 via 192.168.2.2 dev tun0
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.The Shorewall one-interface sample configuration assumes that the
external interface is eth0. 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 interface. Some hints:If your external interface is ppp0 or ippp0 or if you have a static IP address,
you can remove dhcp from the option list.IP AddressesBefore going further, we should say a few words about
Internet Protocol (IP) addresses.
Normally, your Internet Service Provider
(ISP) will assign you a single IP
address. That address can be assigned statically, by the Dynamic
Host Configuration Protocol (DHCP), through
the establishment of your dial-up connection, or during establishment of
your other type of PPP (PPPoA,
PPPoE, etc.) connection.RFC-1918 reserves several
Private IP address ranges for use
in private networks:10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255These addresses are sometimes referred to as
non-routable because the Internet backbone routers
will not forward a packet whose destination address is reserved by
RFC-1918. In some cases though,
ISPs are assigning these addresses then using
Network Address Translation-
NAT) to rewrite packet headers when
forwarding to/from the Internet.LoggingShorewall 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.In Shorewall 5.2.3, the LOAD_HELPERS_ONLY option was removed and
the behavior is the same as if LOAD_HELPERS_ONLY=Yes.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.Enabling other ConnectionsShorewall includes a collection of macros that can be used to
quickly allow or deny services. You can find a list of the macros included
in your version of Shorewall using the command ls
/usr/share/shorewall/macro.*.If you wish to enable connections from the Internet to your firewall
and you find an appropriate macro in
/usr/share/shorewall/macro.*, the general format of a
rule in /etc/shorewall/rules is:#ACTION SOURCE DEST PROTO DPORT
<macro>(ACCEPT) net $FWBe sure to add your rules after the line that reads ?SECTION NEW.You want to run a Web Server and a IMAP Server on your firewall
system:#ACTION SOURCE DEST PROTO DPORT
Web(ACCEPT) net $FW
IMAP(ACCEPT)net $FWThe Shorewall-provided macros assume that the associated service
is using it's standard port and will not work with services listening on
a non-standard port.You may also choose to code your rules directly without using the
pre-defined macros. This will be necessary in the event that there is not
a pre-defined macro that meets your requirements. In that case the general
format of a rule in /etc/shorewall/rules is:#ACTION SOURCE DEST PROTO DPORT
ACCEPT net $FW <protocol><port>You want to run a Web Server and a IMAP Server on your firewall
system:#ACTION SOURCE DEST PROTO DPORT
ACCEPT net $FW tcp 80
ACCEPT net $FW tcp 143If you don't know what port and protocol a particular application
uses, see 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 DESTINATION PROTO DPORT
SSH(ACCEPT) net $FW At this point, edit /etc/shorewall/rules to add
other connections as desired.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.You must enable startup by editing
/etc/shorewall/shorewall.conf and setting
STARTUP_ENABLED=Yes.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, traffic is enabled on those hosts that have an entry in
/etc/shorewall/stoppedrules
(/etc/shorewall/routestopped
in Shorewall 4.5.7 and earlier). A running firewall may be restarted using
the shorewall reload command. If you
want to totally remove any trace of Shorewall from your Netfilter
configuration, use shorewall
clear.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
reload; it is better to create an alternate
configuration and test it using the shorewall
try command.The firewall will start after your network interface has been
brought up. This leaves a small window between the time that the network
interface is working and when the firewall is controlling connections
through that interface. 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.
shorewall-docs-xml-5.2.3/Documentation_Index.xml 0000664 0000000 0000000 00000032243 13427347317 020446 0 ustar root root
Shorewall 5.0 DocumentationTomEastep2001-2017Thomas 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.Frequently Used ArticlesFAQsIPv4 ManpagesIPv6 ManpagesConfiguration
File BasicsBeginner
DocumentationTroubleshootingDocumentation for Earlier VersionsShorewall 4.4/4.6
DocumentationShorewall 4.0/4.2
DocumentationIndex to the HOWTOs and Other Articles6to4 and 6in4 TunnelsKVM (Kernel-mode Virtual
Machine)Shorewall on a
LaptopAccountingLinux Containers
(LXC)Shorewall
PerlActionsLinux-vserverShorewall Setup
GuideAliased
(virtual) Interfaces (e.g., eth0:0)Limiting Connection
RatesSMBAnatomy of
ShorewallLoggingSNAT
(Source Network Address
Translation)Anti-Spoofing
MeasuresMacrosSplit DNS the Easy
WayAUDIT Target
supportMAC
VerificationSquid with
ShorewallBandwidth
ControlManpagesStarting/stopping the
FirewallBlacklisting/WhitelistingManual
ChainsStatic (one-to-one)
NATBridge: Bridge/FirewallMasqueradingSupportBridge: No firewalling of
traffic between bridge portMultiple Internet Connections
from a Single FirewallTips and
HintsBuilding Shorewall from
GITMultiple Zones Through One
InterfaceTraffic
Shaping/QOS - SimpleCompiled Programs
My Shorewall
ConfigurationTraffic Shaping/QOS -
ComplexCommands
Netfilter
OverviewTransparent
ProxyConfiguration
File BasicsNetwork MappingUPnPDHCPOne-to-one NAT (Static
NAT)OpenVZDNAT
(Destination Network Address
Translation)OpenVPNUpgrade
IssuesDockerOperating
ShorewallUpgrading to Shorewall 4.4
(Upgrading Debian Lenny to Squeeze)Dynamic ZonesPacket
MarkingVPNECN Disabling by host or
subnetPacket Processing in a
Shorewall-based FirewallVPN PassthroughEvents'Ping' ManagementWhite
List CreationExtension
Scripts (User Exits)Port
ForwardingXen - Shorewall in a Bridged Xen
DomUFallback/UninstallPort InformationXen - Shorewall in Routed
Xen Dom0FAQsPort Knocking
(deprecated)FeaturesPort Knocking, Auto Blacklisting
and Other Uses of the 'Recent Match'Forwarding Traffic on the
Same InterfacePPTPFTP and ShorewallProxy ARPFool's
FirewallQuickStart
GuidesHelpers/Helper
ModulesRelease ModelInstallation/UpgradeRequirementsIPP2PRouting and
ShorewallIPSECRouting on One
InterfaceIpsetsSambaIPv6 SupportShared Shorewall/Shorewall6
ConfigurationISO 3661 Country
CodesShorewall EventsKazaa
FilteringShorewall
InitKernel
ConfigurationShorewall
Lite
shorewall-docs-xml-5.2.3/Macros.xml 0000664 0000000 0000000 00000100552 13427347317 015731 0 ustar root root
MacrosTomEastepCristianRodríguez20052016Thomas 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.Overview of Shorewall Macros?Shorewall macros allow a symbolic name to be associated with a
series of one or more iptables rules. The symbolic name may appear in the
ACTION column of an /etc/shorewall/rules
file entry and in the TARGET column of an action in which case, the
traffic matching that rules file entry will be passed to the series of
iptables rules named by the macro.Macros can be thought of as templates. When a macro is invoked in an
/etc/shorewall/rules entry, it may be qualified by a
logging specification (log level and optionally a log tag). The presence
of the log level/tag causes a modified series of rules to be generated in
which each packet/rule match within the macro causes a log message to be
generated.There are two types of Shorewall macros:Standard Macros. These macros are released as part of Shorewall.
They are defined in macro.* files in /usr/share/shorewall. Each
macro.* file has a comment at the beginning of
the file that describes what the macro does. As an example, here is
the definition of the SMB standard
macro.#
# Shorewall -- /usr/share/shorewall/macro.SMB
#
# This macro handles Microsoft SMB traffic. You need to invoke
# this macro in both directions. Beware! This rule opens a lot
# of ports, and could possibly be used to compromise your firewall
# if not used with care. You should only allow SMB traffic
# between hosts you fully trust.
#
######################################################################################
#TARGET SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER
PARAM - - udp 135,445
PARAM - - udp 137:139
PARAM - - udp 1024: 137
PARAM - - tcp 135,139,445If you wish to modify one of the standard macros, do not modify
the definition in /usr/share/shorewall. Rather, copy the
file to /etc/shorewall (or
somewhere else on your CONFIG_PATH) and modify the copy.You can see a list of the Standard Macros in your version of
Shorewall using the shorewall show macros command.
You can see the contents of the file
macro.name by typing shorewall
show macro name.User-defined Macros. These macros are created by end-users. They
are defined in macro.* files in /etc/shorewall or in another directory
listed in your CONFIG_PATH (defined in /etc/shorewall/shorewall.conf).Most Standard Macros are parameterized. That
means that you specify what you want to do (ACCEPT, DROP, REJECT, etc.)
when you invoke the macro. The SMB macro shown above is parameterized
(note PARAM in the TARGET column).When invoking a parameterized macro, you follow the name of the
macro with the action that you want to substitute for PARAM enclosed in
parentheses.Example:
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
SMB(ACCEPT) loc $FWThe above is equivalent to coding the following series of
rules:#ACTION SOURCE DEST PROTO DPORT SPORT
ACCEPT loc $FW udp 135,445
ACCEPT loc $FW udp 137:139
ACCEPT loc $FW udp 1024: 137
ACCEPT loc $FW tcp 135,139,445
Logging is covered in a following
section. The other columns are treated as follows:SOURCE and DESTIf a value other than "-" appears in both the macro body and
in the invocation of the macro, then the value in the invocation is
examined and the appropriate action is taken. If the value in the
invocation appears to be an address (IP or MAC) or the name of an
ipset, then it is placed after the value in the macro body.
Otherwise, it is placed before the value in the macro body.Example 1:
/etc/shorewall/macro.SMTP#ACTION SOURCE DEST PROTO DPORT
PARAM - loc tcp 25/etc/shorewall/rules (Shorewall 4.0):#ACTION SOURCE DEST PROTO DPORT
SMTP(DNAT):info net 192.168.1.5/etc/shorewall/rules (Shorewall 4.2.0 and later):#ACTION SOURCE DEST PROTO DPORT
SMTP(DNAT):info net 192.168.1.5This would be equivalent to coding the following directly in
/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT
DNAT:info net loc:192.168.1.5 tcp 25
Example 2:
/etc/shorewall/macro.SMTP
#ACTION SOURCE DEST PROTO DPORT
PARAM - 192.168.1.5 tcp 25/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT
SMTP(DNAT):info net locThis would be equivalent to coding the following directly in
/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT
DNAT:info net loc:192.168.1.5 tcp 25
You may also specify SOURCE or DEST in the SOURCE and DEST
columns. This allows you to define macros that work in both
directions.Example 3:
/etc/shorewall/macro.SMBBI (Note: there
is already a standard macro like this released as part of
Shorewall):#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST RATE USER
PARAM - - udp 135,445
PARAM - - udp 137:139
PARAM - - udp 1024: 137
PARAM - - tcp 135,139,445
PARAM DEST SOURCE udp 135,445
PARAM DEST SOURCE udp 137:139
PARAM DEST SOURCE udp 1024: 137
PARAM DEST SOURCE tcp 135,139,445/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
SMBBI(ACCEPT) loc $FWThis would be equivalent to coding the following directly in
/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT SPORT
ACCEPT loc $FW udp 135,445
ACCEPT loc $FW udp 137:139
ACCEPT loc $FW udp 1024: 137
ACCEPT loc $FW tcp 135,139,445
ACCEPT $FW loc udp 135,445
ACCEPT $FW loc udp 137:139
ACCEPT $FW loc udp 1024: 137
ACCEPT $FW loc tcp 135,139,445
Remaining columnsAny value in the invocation replaces the value in the rule in
the macro.Defining your own MacrosTo define a new macro:Macro names must be valid shell variable names ((must begin with
a letter and be composed of letters, digits and underscore characters)
as well as valid Netfilter chain names.Copy /usr/share/shorewall/macro.template to
/etc/shorewall/macro.MacroName (for example, if
your new macro name is Foo then copy
/usr/share/shorewall/macro.template to
/etc/shorewall/macro.Foo).Now modify the new file to define the new macro.Shorewall 5.0.0 and LaterThe columns in a macro file are the same as those in shorewall-rules(5).Shorewall 4.4.16 and LaterBeginning with Shorewall 4.4.16, the columns in macro.template are
the same as those in shorewall-rules (5). The first non-commentary line
in the template must beFORMAT 2Beginning with Shorewall 4.5.11, the preferred format is as shown
below, and the above format is deprecated.?FORMAT 2There are no restrictions regarding the ACTIONs that can be
performed in a macro.Beginning with Shorewall 4.5.10, macros may also be used as default actions.DEFAULT defwhere def is the default value for
PARAMShorewall 4.4.15 and EarlierBefore 4.4.16, columns in the macro.template file were as
follows:ACTION - ACCEPT, DROP, REJECT, DNAT, DNAT-, REDIRECT,
CONTINUE, LOG, QUEUE, PARAM or an action name. Note that a macro may
not invoke another macro.ACCEPT - allow the connection requestACCEPT+ - like ACCEPT but also excludes the connection
from any subsequent DNAT[-] or REDIRECT[-] rules.NONAT - Excludes the connection from any subsequent
DNAT[-] or REDIRECT[-] rules but doesn't generate a rule to accept
the traffic.DROP - ignore the requestREJECT - disallow the request and return an icmp
unreachable or an RST packet.DNAT - Forward the request to another address (and
optionally another port).DNAT- - Advanced users only. Like DNAT but only generates
the DNAT iptables rule and not the companion ACCEPT rule.SAME - Similar to DNAT except that the port may not be
remapped and when multiple server addresses are listed, all
requests from a given remote system go to the same
server.SAME- - Advanced users only. Like SAME but only generates
the SAME iptables rule and not the companion ACCEPT rule.REDIRECT - Redirect the request to a local port on the
firewall.REDIRECT- - Advanced users only. Like REDIRECT but only
generates the REDIRECT iptables rule and not the companion ACCEPT
rule.CONTINUE - (For experts only). Do not process any of the
following rules for this (source zone,destination zone). If The
source and/or destination If the address falls into a zone defined
later in /etc/shorewall/zones, this connection request will be
passed to the rules defined for that (those) zone(s).LOG - Simply log the packet and continue.QUEUE - Queue the packet to a user-space application such
as ftwall (http://p2pwall.sf.net).The ACTION may optionally be followed by ":" and a syslog log
level (e.g, REJECT:info or DNAT:debug). This causes the packet to be
logged at the specified level.SOURCE - Source hosts to which the rule applies. A
comma-separated list of subnets and/or hosts. Hosts may be specified
by IP or MAC address; mac addresses must begin with ~
and must use - as a separator.Alternatively, clients may be specified by interface name. For
example, eth1 specifies a client that communicates with the firewall
system through eth1. This may be optionally followed by another
colon (:) and an IP/MAC/subnet address as described
above (e.g. eth1:192.168.1.5).May also contain 'DEST' as described above.DEST - Location of Server. Same as above with the exception
that MAC addresses are not allowed.Unlike in the SOURCE column, you may specify a range of up to
256 IP addresses using the syntax <first
ip>-<last ip>.May also contain 'SOURCE' as described above.PROTO - Protocol - Must be tcp,
udp, icmp, a number, or
all.DEST PORT(S) - Destination Ports. A comma-separated list of
Port names (from /etc/services), port numbers
or port ranges; if the protocol is icmp, this column
is interpreted as the destination icmp-type(s).A port range is expressed as <low
port>:<high port>.This column is ignored if PROTOCOL = all but must be entered
if any of the following fields are supplied. In that case, it is
suggested that this field contain -.If your kernel contains multi-port match support, then only a
single Netfilter rule will be generated if in this list and in the
CLIENT PORT(S) list below:There are 15 or less ports listed.No port ranges are included.Otherwise, a separate rule will be generated for each
port.SOURCE PORT(S) - Port(s) used by the client. If omitted, any
source port is acceptable. Specified as a comma-separated list of
port names, port numbers or port ranges.If you don't want to restrict client ports but need to specify
an ADDRESS in the next column, then place "-" in this column.If your kernel contains multi-port match support, then only a
single Netfilter rule will be generated if in this list and in the
DEST PORT(S) list above:There are 15 or less ports listed.No port ranges are included.Otherwise, a separate rule will be generated for each
port.ORIGDEST (Shorewall-perl 4.2.0 and later)To use this column, you must include 'FORMAT 2' as the first
non-comment line in your macro file.If ACTION is DNAT[-] or REDIRECT[-] then if this column is
included and is different from the IP address given in the DEST
column, then connections destined for that address will be forwarded
to the IP and port specified in the DEST column.A comma-separated list of addresses may also be used. This is
most useful with the REDIRECT target where you want to redirect
traffic destined for particular set of hosts. Finally, if the list
of addresses begins with "!" (exclusion) then the rule will be
followed only if the original destination address in the connection
request does not match any of the addresses listed.For other actions, this column may be included and may contain
one or more addresses (host or network) separated by commas. Address
ranges are not allowed. When this column is supplied, rules are
generated that require that the original destination address matches
one of the listed addresses. This feature is most useful when you
want to generate a filter rule that corresponds to a DNAT- or
REDIRECT- rule. In this usage, the list of addresses should not
begin with "!".It is also possible to specify a set of addresses then exclude
part of those addresses. For example, 192.168.1.0/24!192.168.1.16/28
specifies the addresses 192.168.1.0-182.168.1.15 and
192.168.1.32-192.168.1.255. See shorewall-exclusion(5).See http://shorewall.net/PortKnocking.html
for an example of using an entry in this column with a user-defined
action rule.RATE LIMIT - You may rate-limit the rule by placing a value in
this column: <rate>/<interval>[:<burst>]where
<rate> is the number of connections per
<interval> (sec or
min) and <burst> is the
largest burst permitted. If no <burst> is
given, a value of 5 is assumed. There may be no whitespace embedded
in the specification. Example: 10/sec:20USER/GROUP - For output rules (those with the firewall as
their source), you may control connections based on the effective
UID and/or GID of the process requesting the connection. This column
can contain any of the following:[!]<user number>[:][!]<user name>[:][!]:<group number>[!]:<group name>[!]<user
number>:<group
number>[!]<user
name>:<group
number>[!]<user
inumber>:<group
name>[!]<user
name>:<group
name>[!]+<program name> (Note:
support for this form was removed from Netfilter in kernel version
2.6.14).MARK - (Added in Shorewall-4.4.2) Defines a test on the
existing packet or connection mark. The rule will match only if the
test returns true. Must be empty or '-' if the macro is to be used
within an action. [!]value[/mask][:C]!Inverts the test (not equal)valueValue of the packet or connection mark.maskA mask to be applied to the mark before testing.:CDesignates a connection mark. If omitted, the # packet
mark's value is tested.CONNLIMIT - (Added in Shorewall-4.4.2) Must be empty or '-' if
the macro is to be used within an action. [!]limit[:mask]May be used to limit the number of simultaneous connections
from each individual host to limit connections. Requires connlimit
match in your kernel and iptables. While the limit is only checked
on rules specifying CONNLIMIT, the number of current connections is
calculated over all current connections from the SOURCE host. By
default, the limit is applied to each
host but can be made to apply to networks of hosts by specifying a
mask. The mask specifies the width of a
VLSM mask to be applied to the source address; the number of current
connections is then taken over all hosts in the subnet
source-address/mask.
When ! is specified, the rule matches when the number of connection
exceeds the limit.TIME - (Added in Shorewall-4.4.2) Must be empty or '-' if the
macro is to be used within an action. <timeelement>[&...]timeelement may be:timestart=hh:mm[:ss]Defines the starting time of day.timestop=hh:mm[:ss]Defines the ending time of day.utcTimes are expressed in Greenwich Mean Time.localtzTimes are expressed in Local Civil Time
(default).weekdays=ddd[,ddd]...where ddd is one of
, ,
, ,
, or
monthdays=dd[,dd],...where dd is an ordinal day of
the monthdatestart=yyyy[-mm[-dd[hh[:mm[:ss]]]]]Defines the starting date and time.datestop=yyyy[-mm[-dd[hh[:mm[:ss]]]]]Defines the ending date and time.Omitted column entries should be entered using a dash
("-").Example:/etc/shorewall/macro.LogAndAccept LOG:info
ACCEPTTo use your macro, in /etc/shorewall/rules
you might do something like:#ACTION SOURCE DEST PROTO DPORT
LogAndAccept loc $FW tcp 22Macros and LoggingSpecifying a log level in a rule that invokes a user- or
Shorewall-defined action will cause each rule in the macro to be logged
with the specified level (and tag).The extent to which logging of macro rules occur is governed by the
following:When you invoke a macro and specify a log level, only those
rules in the macro that have no log level will be changed to log at
the level specified at the action invocation.Example:/etc/shorewall/macro.foo#ACTION SOURCE DEST PROTO DPORT
ACCEPT - - tcp 22
bar:info/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
foo:debug $FW netLogging in the invoked 'foo' macro will be as if foo had been
defined as:#ACTION SOURCE DEST PROTO DPORT
ACCEPT:debug - - tcp 22
bar:infoIf you follow the log level with "!" then logging will be at
that level for all rules recursively invoked by the macro.Example:/etc/shorewall/macro.foo#ACTION SOURCE DEST PROTO DPORT
ACCEPT - - tcp 22
bar:info/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
foo:debug! $FW netLogging in the invoked 'foo' macro will be as if foo had been
defined as:#ACTION SOURCE DEST PROTO DPORT
ACCEPT:debug - - tcp 22
bar:debugHow do I know if I should create an Action or a Macro?While actions and macros perform similar functions, in any given
case you will generally find that one is more appropriate than the
other.Embedded Perl is much more useful in an
action than it is in a macro. So if you need access to
iptables features not directly supported by Shorewall then you should
use an action.Macros are expanded in-line while each action (that doesn't
specify the inline option) is its own chain. So if there are a lot of
rules involved in your new action/macro then it is generally better to
use an action than a macro. Only the packets selected when you invoke
the action are directed to the corresponding chain. On the other hand,
if there are only one or two rules involved in what you want to do
then a macro is more efficient.In-line actions, introduced in Shorewall 4.5.10, are very similar to
macros. The advantage of in-line actions is that they may have parameters
and can use the other action
variables.
shorewall-docs-xml-5.2.3/Shorewall_and_Aliased_Interfaces.xml 0000664 0000000 0000000 00000040621 13427347317 023054 0 ustar root root
Shorewall and Aliased InterfacesTomEastep2001-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.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.BackgroundThe traditional net-tools contain a program called
ifconfig which is used to configure network devices.
ifconfig introduced the concept of aliased or
virtual interfaces. These virtual interfaces have
names of the form interface:integer (e.g., eth0:0) and ifconfig treats them more or
less like real interfaces.ifconfig[root@gateway root]# ifconfig eth0:0
eth0:0 Link encap:Ethernet HWaddr 02:00:08:3:FA:55
inet addr:206.124.146.178 Bcast:206.124.146.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:11 Base address:0x2000
[root@gateway root]# The ifconfig utility is being gradually phased out in favor of the
ip utility which is part of the
iproute package. The ip utility does not use the
concept of aliases or virtual interfaces but rather treats additional
addresses on an interface as objects in their own right. The ip utility
does provide for interaction with ifconfig in that it allows addresses to
be labeled where these labels take the form of
ipconfig virtual interfaces.ip[root@gateway root]# ip addr show dev 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:0
[root@gateway root]# One cannot type
ip addr show dev eth0:0 because
eth0:0 is a
label for a particular address rather than a device name.[root@gateway root]# ip addr show dev eth0:0
Device "eth0:0" does not exist.
[root@gateway root]#The iptables program doesn't support virtual interfaces in either
its -i or -o command options; as a
consequence, Shorewall does not allow them to be used in the
/etc/shorewall/interfaces file or anywhere else except as described in the
discussion below.Adding Addresses to InterfacesMost distributions have a facility for adding additional addresses
to interfaces. If you have already used your distribution's capability to
add your required addresses, you can skip this section.Shorewall provides facilities for automatically adding addresses to
interfaces as described in the following section. It is also easy to add
them yourself using the ip utility. The
above alias was added using:ip addr add 206.124.146.178/24 brd 206.124.146.255 dev eth0 label eth0:0You probably want to arrange to add these addresses when the device
is started rather than placing commands like the above in one of the
Shorewall extension scripts. For example, on RedHat systems, you can place
the commands in /sbin/ifup-local:#!/bin/sh
case $1 in
eth0)
/sbin/ip addr add 206.124.146.178 dev eth0 label eth0:0
;;
esacRedHat systems also allow adding such aliases from the network
administration GUI (which only works well if you have a graphical
environment on your firewall).On Debian and LEAF/Bering systems, it is as simple as adding the
command to the interface definition as follows:# Internet interface
auto eth0
iface eth0 inet static
address 206.124.146.176
netmask 255.255.255.0
gateway 206.124.146.254
up ip addr add 206.124.146.178/24 brd 206.124.146.255 dev eth0 label eth0:0So how do I handle more than one address on an interface?The answer depends on what you are trying to do with the interfaces.
In the sub-sections that follow, we'll take a look at common
scenarios.The examples in the following sub-sections assume that the local
network is 192.168.1.0/24.Separate RulesIf you need to make a rule for traffic to/from the firewall itself
that only applies to a particular IP address, simply qualify the $FW
zone with the IP address.allow SSH from net to eth0:0 above/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT
ACCEPT net $FW:206.124.146.178 tcp 22DNATSuppose that I had set up eth0:0 as above and I wanted to port
forward from that virtual interface to a web server running in my local
zone at 192.168.1.3. That is accomplished by a single rule in the
/etc/shorewall/rules file:#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST
DNAT net loc:192.168.1.3 tcp 80 - 206.124.146.178 If I wished to forward tcp port 10000 on that virtual interface to
port 22 on local host 192.168.1.3, the rule would be:#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST
DNAT net loc:192.168.1.3 tcp 80 - 206.124.146.178
DNAT net loc:192.168.1.3:22 tcp 10000 - 206.124.146.178 SNATIf you wanted to use eth0:0 as the IP address for outbound
connections from your local zone (eth1), then in
/etc/shorewall/masq:#INTERFACE SUBNET ADDRESS
eth0 192.168.1.0/24 206.124.146.178When running Shorewall 5.0.14 or later, the equivalent
/etc/shorewall/snat is:#ACTION SOURCE DEST PROTO PORT
SNAT(206.124.146.178) 0.0.0.0/0 eth0Similarly, you want SMTP traffic from local system 192.168.1.22 to
have source IP 206.124.146.178:#INTERFACE SUBNET ADDRESS PROTO DPORT
eth0 192.168.1.22 206.124.146.178 tcp 25When running Shorewall 5.0.14 or later, the equivalent
/etc/shorewall/snat is:#ACTION SOURCE DEST PROTO PORT
SNAT(206.124.146.178) 0.0.0.0/0 eth0 tcp 25Shorewall can create the alias (additional address) for you if you
set ADD_SNAT_ALIASES=Yes in
/etc/shorewall/shorewall.conf.Addresses added by ADD_SNAT_ALIASES=Yes are deleted and re-added
during shorewall restart. As a consequence,
connections using those addresses may be severed.Shorewall can create the label (virtual interface)
so that you can see the created address using ifconfig. In addition to
setting ADD_SNAT_ALIASES=Yes, you specify the virtual interface name in
the INTERFACE column as follows./etc/shorewall/masq#INTERFACE SUBNET ADDRESS
eth0:0 192.168.1.0/24 206.124.146.178When running Shorewall 5.0.14 or later, the equivalent
/etc/shorewall/snat is:#ACTION SOURCE DEST PROTO PORT
SNAT(206.124.146.178) 192.168.1.0/24 eth0Shorewall can also set up SNAT to round-robin over a range of IP
addresses. To do that, you specify a range of IP addresses in the
ADDRESS column. If you specify a label in the INTERFACE column,
Shorewall will use that label for the first address of the range and
will increment the label by one for each subsequent label./etc/shorewall/masq#INTERFACE SOURCE ADDRESS
eth0:0 192.168.1.0/24 206.124.146.178-206.124.146.180When running Shorewall 5.0.14 or later, the equivalent
/etc/shorewall/snat is:#ACTION SOURCE DEST PROTO PORT
SNAT(206.124.146.178-206.24.146.180) 192.168.1.0/24 eth0The above would create three IP addresses:eth0:0 = 206.124.146.178
eth0:1 = 206.124.146.179
eth0:2 = 206.124.146.180One-to-one NATIf you wanted to use one-to-one NAT to link eth0:0 with local address 192.168.1.3, you
would have the following in
/etc/shorewall/nat:#EXTERNAL INTERFACE INTERNAL ALL_INTERFACES LOCAL
206.124.146.178 eth0 192.168.1.3 no noShorewall can create the alias (additional address) for you if you
set ADD_IP_ALIASES=Yes in /etc/shorewall/shorewall.conf.Addresses added by ADD_IP_ALIASES=Yes are deleted and re-added
during shorewall restart. As a consequence,
connections using those addresses may be severed.Shorewall can create the label (virtual interface)
so that you can see the created address using ifconfig. In addition to
setting ADD_IP_ALIASES=Yes, you specify the virtual interface name in
the INTERFACE column as follows./etc/shorewall/nat#EXTERNAL INTERFACE INTERNAL ALL_INTERFACES LOCAL
206.124.146.178 eth0:0 192.168.1.3 no noIn either case, to create rules in
/etc/shorewall/rules that pertain only to this NAT
pair, you simply qualify the local zone with the internal IP
address.You want to allow SSH from the net to 206.124.146.178 a.k.a.
192.168.1.3.#ACTION SOURCE DEST PROTO DPORT
ACCEPT net loc:192.168.1.3 tcp 22MULTIPLE SUBNETSSometimes multiple IP addresses are used because there are
multiple subnetworks configured on a LAN segment. This technique does
not provide for any security between the subnetworks if the users of the
systems have administrative privileges because in that case, the users
can simply manipulate their system's routing table to bypass your
firewall/router. Nevertheless, there are cases where you simply want to
consider the LAN segment itself as a zone and allow your firewall/router
to route between the two subnetworks.Local interface eth1 interfaces to 192.168.1.0/24 and
192.168.20.0/24. The primary IP address of eth1 is 192.168.1.254 and
eth1:0 is 192.168.20.254. You simply want your firewall to route
between these two subnetworks.In /etc/shorewall/zones:#ZONE TYPE OPTIONS
loc ipv4In /etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
loc eth1 routebackIn /etc/shorewall/rules, simply specify
ACCEPT rules for the traffic that you want to permit.Local interface eth1 interfaces to 192.168.1.0/24 and
192.168.20.0/24. The primary IP address of eth1 is 192.168.1.254 and
eth1:0 is 192.168.20.254. You want to make these subnetworks into
separate zones and control the access between them (the users of the
systems do not have administrative privileges).In /etc/shorewall/zones:#ZONE TYPE OPTIONS
loc ipv4
loc2 ipv4In /etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
- eth1 In /etc/shorewall/hosts:#ZONE HOSTS OPTIONS
loc eth1:192.168.1.0/24
loc2 eth1:192.168.20.0/24In /etc/shorewall/rules, simply specify
ACCEPT rules for the traffic that you want to permit.For more information on handling multiple networks through a
single interface, see Routing on One
Interface.Defining a Zone-per-AddressShorewall's support for Linux
Vservers can (mis-)used to create a separate zone per alias.
Note that this results in a partitioning of the firewall
zone. In this usage, you probably want to define an ACCEPT
policy between your vserver zones and the firewall zone.
shorewall-docs-xml-5.2.3/NAT.xml 0000664 0000000 0000000 00000025302 13427347317 015126 0 ustar root root
One-to-one NATTomEastep2001-2004Thomas 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.One-to-one NATIf all you want to do is forward ports to
servers behind your firewall, you do NOT want to use one-to-one NAT.
Port forwarding can be accomplished with simple entries in the rules
file.One-to-one NAT is a way to make systems behind a firewall and
configured with private IP addresses (those reserved for private use in
RFC 1918) appear to have public IP addresses. Before you try to use this
technique, I strongly recommend that you read the Shorewall Setup Guide.The following figure represents a one-to-one NAT environment.One-to-one NAT can be used to make the systems with the 10.1.1.*
addresses appear to be on the upper (130.252.100.*) subnet. If we assume
that the interface to the upper subnet is eth0, then the following
/etc/shorewall/nat file would make the lower
left-hand system appear to have IP address 130.252.100.18 and the
right-hand one to have IP address 130.252.100.19. It should be stressed
that these entries in the /etc/shorewall/nat file do
not automatically enable traffic between the external network and the
internal host(s) — such traffic is still subject to your policies and
rules./etc/shorewall/nat#EXTERNAL INTERFACE INTERNAL ALLINTS LOCAL
130.252.100.18 eth0 10.1.1.2 no no
130.252.100.19 eth0 10.1.1.3 no noBe sure that the internal system(s) (10.1.1.2 and 10.1.1.3 in the
above example) is (are) not included in any specification in
/etc/shorewall/masq
(/etc/shorewall/snat) or
/etc/shorewall/proxyarp.The ALL INTERFACES column is used to specify
whether access to the external IP from all firewall interfaces should
undergo NAT (Yes or yes) or if only access from the interface in the
INTERFACE column should undergo NAT. If you leave this column empty,
No is assumed . Specifying
Yes in this column will not by itself allow systems on
the lower LAN to access each other using their public IP
addresses. For example, the lower left-hand system (10.1.1.2)
cannot connect to 130.252.100.19 and expect to be connected to the lower
right-hand system. See FAQ 2a.Shorewall will automatically add the external address to the
specified interface unless you specify ADD_IP_ALIASES=no
(or No) in
/etc/shorewall/shorewall.conf; If you do not set
ADD_IP_ALIASES or if you set it to Yes or
yes then you must NOT configure your own
alias(es).The contents of the LOCAL column determine whether
packets originating on the firewall itself and destined for the EXTERNAL
address are redirected to the internal ADDRESS. If this column contains
yes or Yes (and the ALL INTERFACES COLUMN
also contains Yes or yes) then such
packets are redirected; otherwise, such packets are not redirected. This
feature requires that you enabled CONFIG_IP_NF_NAT_LOCAL in your
kernel.Entries in /etc/shorewall/nat only arrange for
address translation; they do not allow traffic to pass through the
firewall in violation of your policies. In the above example, suppose that
you wish to run a web server on 10.1.1.2 (a.k.a. 130.252.100.18). You
would need the following entry in
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT SPORT ORIGDEST
ACCEPT net loc:10.1.1.2 tcp 80 - 130.252.100.18ARP cacheA word of warning is in order here. ISPs typically configure their
routers with a long ARP cache timeout. If you move a system from parallel
to your firewall to behind your firewall with one-to-one NAT, it will
probably be HOURS before that system can communicate with the
Internet.If you sniff traffic on the firewall's external interface, you can
see incoming traffic for the internal system(s) but the traffic is never
sent out the internal interface.You can determine if your ISP's gateway ARP cache is stale using
ping and tcpdump. Suppose that we suspect that the gateway router has a
stale ARP cache entry for 130.252.100.19. On the firewall, run tcpdump as
follows:tcpdump -nei eth0 icmpNow from 10.1.1.3, ping the ISP's gateway (which we will assume is
130.252.100.254):ping 130.252.100.254We can now observe the tcpdump output:13:35:12.159321 0:4:e2:20:20:33 0:0:77:95:dd:19 ip 98: 130.252.100.19 > 130.252.100.254: icmp: echo request (DF)
13:35:12.207615 0:0:77:95:dd:19 0:c0:a8:50:b2:57 ip 98: 130.252.100.254 > 130.252.100.177 : icmp: echo replyNotice that the source MAC address in the echo request is different
from the destination MAC address in the echo reply!! In this case
0:4:e2:20:20:33 was the MAC of the firewall's eth0 NIC while
0:c0:a8:50:b2:57 was the MAC address of the system on the lower right. In
other words, the gateway's ARP cache still associates 130.252.100.19 with
the NIC in that system rather than with the firewall's eth0.If you have this problem, there are a couple of things that you can
try:A reading of TCP/IP Illustrated, Vol 1 by
Stevens revealsCourtesy of Bradey Honsinger that a gratuitous ARP packet should cause
the ISP's router to refresh their ARP cache (section 4.7). A
gratuitous ARP is simply a host requesting the MAC address for its own
IP; in addition to ensuring that the IP address isn't a
duplicate...
if the host sending the gratuitous ARP has just changed its
hardware address..., this packet causes any other host...that has an
entry in its cache for the old hardware address to update its ARP
cache entry accordingly.
Which is, of course, exactly what you want to do when you switch
a host from being exposed to the Internet to behind Shorewall using
one-to-one NAT (or Proxy ARP for that matter). Happily enough, recent
versions of Redhat's iputils package include arping,
whose -U flag does just that:arping -U -I <net if> <newly proxied IP>
arping -U -I eth0 66.58.99.83 # for exampleStevens goes on to mention that not all systems respond
correctly to gratuitous ARPs, but googling for arping
-U seems to support the idea that it works most of the
time.To use arping with one-to-one NAT in the above example, you
would have to:shorewall clear
ip addr add 130.252.100.18 dev eth0 # You need to add the addresses only if Shorewall clear
ip addr add 130.252.100.19 dev eth0 # deletes them
arping -U -c 10 -I eth0 130.252.100.18
arping -U -c 10 -I eth0 130.252.100.19
ip addr del 130.252.100.18 dev eth0 # You need to delete the addresses only if you added
ip addr del 130.252.100.19 dev eth0 # them above
shorewall startYou can call your ISP and ask them to purge the stale ARP cache
entry but many either can't or won't purge individual entries.There are two distinct versions of arping
available:arping by Thomas Habets (Debian package
arping).arping as part of the iputils package by
Alexey Kuznetsov (Debian package
iputils-arping).You want the second one by Alexey Kuznetsov.
shorewall-docs-xml-5.2.3/ConnectionRate.xml 0000664 0000000 0000000 00000006776 13427347317 017435 0 ustar root root
Connection Rate LimitingTomEastep20082009Thomas 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.IntroductionShorewall supports several mechanisms for limiting connection rates.
These are described in the following sections.Rates are expressed in terms of a connections per unit
time and a burst. An
interval is calculated by dividing the unit of time
by the number of connections allowed in that unit of time
(connections/{||||week|month}[:burst]Example: 4/min:5Connections = 4Unit of time = 1 minuteInterval = 1 minute/4 = 15 seconds.Burst = 5As each connection arrives,if the burst count is > 0 the
burst count is reduced by one and the connection is
accepted. After each interval (15 seconds) that passes without a
connection arriving, the burst count is incremented
by 1 but is not allowed to exceed its initial setting (5).By default, the aggregate connection rate is limited. If the
specification is preceded by "" or
"", then the rate is limited per SOURCE or per
DESTINATION IP address respectively.Policy Rate LimitingThe LIMIT column in the /etc/shorewall/policy
file applies to TCP connections that are subject to the policy. The
limiting is applied BEFORE the connection request is passed through the
rules generated by entries in /etc/shorewall/rules.
Those connections in excess of the limit are logged and dropped.Rules Rate LimitingThe RATE LIMIT column in the
/etc/shorewall/rules file allows limiting of
ACCEPT, DNAT and Action rules.Limit ActionThe Limit Action is a
legacy mechanism that limits connections per source IP. It does not
support the notion of a burst size.
shorewall-docs-xml-5.2.3/blacklisting_support.xml 0000664 0000000 0000000 00000026550 13427347317 020754 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 blacklisting; 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-blrules (5)
for details.Example:#ACTION SOURCE DEST PROTO DPORT
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.Chain-based 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 and reload.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).Ipset-based Dynamic BlacklistingBeginning with Shorewall 5.0.8, it is possible to use an ipset to
hold blacklisted addresses. The DYNAMIC_BLACKLIST option was expanded
to:DYNAMIC_BLACKLIST={Yes|No||ipset[-only][,option[,...]][:[setname][:log_level|:log_tag]]]}When or is
specified, the shorewall blacklist command is used to
blacklist a single host or a network. The allow command
is used to remove entries from the ipset. The name of the set
(setname) and the level
(log_level), if any, at which blacklisted
traffic is to be logged may also be specified. The default set name is
SW_DBL4 and the default log level is (no logging).
If is given, then chain-based dynamic
blacklisting is disabled just as if DYNAMIC_BLACKLISTING=No had been
specified.Possible options are:src-dstNormally, only packets whose source address matches an entry
in the ipset are dropped. If is included,
then packets whose destination address matches an entry in the ipset
are also dropped.The option was added in Shorewall
5.0.13 and requires that the conntrack utility be installed on the
firewall system. When an address is blacklisted using the
blacklist command, all connections originating
from that address are disconnected. if the
option was also specified, then all connections to that address are
also disconnected.=secondsAdded in Shorewall 5.0.13. Normally, Shorewall creates the
dynamic blacklisting ipset with timeout 0 which means that entries
are permanent. If you want entries in the set that are not accessed
for a period of time to be deleted from the set, you may specify
that period using this option. Note that the
blacklist command can override the ipset's
timeout setting.Once the dynamic blacklisting ipset has been created,
changing this option setting requires a complete restart of the
firewall; shorewall restart if RESTART=restart,
otherwise shorewall stop && shorewall
startWhen ipset-based dynamic blacklisting is enabled, the contents of
the blacklist will be preserved over
stop/reboot/start
sequences if SAVE_IPSETS=Yes, SAVE_IPSETS=ipv4 or if
setname is included in the list of sets to be
saved in SAVE_IPSETS.BLACKLIST Policy and ActionBeginning with Shorewall 5.1.1, it is possible to specify BLACKLIST
in the POLICY column of shorewall-policy(5) when
ipset-based dynamic blacklisting is being used. When a packet is disposed
of via the BLACKLIST policy, the packet's sender is added to the dynamic
blacklist ipset and the packet is dropped.Also available beginning with Shorewall 5.1.1 is a BLACKLIST action
for use in the rules file, macros and filter table actions. Execute the
shorewall show action BLACKLIST command for
details.
shorewall-docs-xml-5.2.3/standalone_ru.xml 0000664 0000000 0000000 00000076564 13427347317 017362 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, тогда смотрите документацию для этого выпуска.Пример файлов конфигурации в составе Shorewall 3.0.0 и 3.0.1 был
некорректен. Первой генерируемой ошибкой была:ERROR: No Firewall Zone Defined (ОШИБКА: Не
определены зоны файервола)Исправленные файла 'зоны' ('zones') и 'интерфейсы' ('interfaces')
доступны по адресу: http://www.shorewall.net/pub/shorewall/3.0/shorewall-3.0.1/errata/one-interface/.Эта проблема исправлена в Shorewall 3.0.2.ВведениеУстановка Shorewall на отдельной Linux системе очень проста, если Вы
понимаете основы и следуете данной документации.Это руководство не пытается ознакомить Вас со всеми особенностями
Shorewall. Оно больше сфокусировано на том, что требуется для настройки
Shorewall в наиболее типичных конфигурациях:Linux системаОдин внешний(публичный) IP-адресИнтернет-соединение посредством кабельного модема,
DSL, ISDN, Frame Relay,
коммутирумой линии ... или есть соединение с LAN и
Вы просто хотите защитить Вашу Linux систему от других систем в этой
LAN.Системные требования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
версия dos2unixСоглашенияМеста, в которых рекомендуется вносить изменения, отмечены как
.PPTP/ADSLЕсли У Вас есть ADSL модем и Вы используете
PPTP для взаимодействия с сервером на этом модеме, Вы
должны сделать изменения рекоммендуемые здесьв дополнение к тем, что описаны в последующих
шагах. ADSL с
PPTP наиболее распространен в Европе, особенно в
Австрии.Концепции ShorewallКонфигурационные файлы Shorewall находятся в директории /etc/shorewall -- в случае простой установки
Вам необходимо иметь дело только с немногими из них, как описано в этом
руководстве.Замечание для пользователей
DebianЕсли Вы при установке пользовались .deb, Вы обнаружите, что
директория /etc/shorewall
пуста. Это сделано специально. Поставляемые шаблоны файлов
конфигурации Вы найдете на вашей системе в директории /usr/share/doc/shorewall/default-config.
Просто скопируйте нужные Вам файлы из этой директории в /etc/shorewall и отредактируйте
копии.Заметьте, что Вы должны скопировать /usr/share/doc/shorewall/default-config/shorewall.conf
и /usr/share/doc/shorewall/default-config/modules
в /etc/shorewall даже если Вы
не будете изменять эти файлы.После того как Вы установили
Shorewall, Вы можете найти примеры файлов настроек в следующих
местах:Если Вы при установке использовали RPM,
примеры будут находится в поддиректории Samples/one-interface/ директории с
документацией Shorewall. Если Вы не знаете где расположена директория
с документацией Shorewall, Вы можете найти примеры используя
команду:~# rpm -ql shorewall | fgrep one-interface
/usr/share/doc/packages/shorewall/Samples/one-interface
/usr/share/doc/packages/shorewall/Samples/one-interface/interfaces
/usr/share/doc/packages/shorewall/Samples/one-interface/policy
/usr/share/doc/packages/shorewall/Samples/one-interface/rules
/usr/share/doc/packages/shorewall/Samples/one-interface/zones
~#Если Вы установили Shorewall из tarball'а, примеры находятся в
директории Samples/one-interface внутри
tarball'а.Если же Вы пользовались пакетом .deb, примеры находятся в
директории /usr/share/doc/shorewall-common/examples/one-interface.По мере того как мы будем знакомится с каждым файлом, я надеюсь, что
Вы просмотрите реальный файл на вашей системе -- каждый файл содержит
детальное описание конфигурационных инструкций и значений по
умолчанию.Shorewall видит сеть, в которой он работает, как состоящую из набора
зон(zones). В случае примера конфигурации с одним
интерфейсом, только две зоны определены:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall
net 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 ZONE DESTINATION ZONE POLICY LOG LEVEL LIMIT:BURST
$FW net ACCEPT
net all DROP info
all all REJECT infoПолитики приведенные выше будут:разрешать все запросы на соединение с файервола в
Internet;отбрасывать (игнорировать) все запросы на соединение из Internet
к Вашему файерволу;отвергать все другие запросы на соединение (Shorewall требует
наличия такой политики, применимой для всех остальных
запросов).В данный момент Вы можете отредактировать ваш файл
/etc/shorewall/policy и внести изменения, какие Вы
считаете необходимыми.Внешний интерфейсФайервол имеет один сетевой интерфейс. Если соединение с Internet
осуществляется при помощи кабельного или DSL
Модема, Внешним интерфейсом будет
ethernet-адаптер (например, eth0),
который подсоединен к этому Модему, если же Вы соединены посредством протокола
Point-to-Point Protocol over Ethernet
(PPPoE) или Point-to-Point Tunneling
Protocol (PPTP), то в этом случае
Внешним интерфейсом будет PPP
интерфейс (например, ppp0). Если
Вы подсоединены через обычный модем, Вашим Внешним
интерфейсом будет также ppp0. Если Вы соединяетесь используя
ISDN, Внешним интерфейсом будет
ippp0.Пример конфигурации Shorewall для одного интерфейса подразумевает,
что внешний интерфейс - eth0. Если
Ваша конфигурация отличается, Вам необходимо изменить файл примера
/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
и т.д.) соединения.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На эти адреса иногда ссылаются как на
немаршрутизируемые потому, что магистральные
маршрутизаторы Интернет не переправляют пакеты, адреса назначения которых
зарезервированы RFC-1918. Хотя в некоторых случаях,
ISP, назначающие эти адреса, используют затем
Преобразование Сетевых Адресов (Network Address Translation -
NAT) для перезаписи заголовков пакетов при
перенаправлении в/из Интернет.Перед запуском Shorewall, Вы должны взглянуть
на IP-адрес Вашего внешнего интерфейса и, если он принадлежит одному из
указанных выше диапазонов, Вы должны удалить опцию
norfc1918 из записи в
/etc/shorewall/interfaces.Разрешение других соединенийShorewall включает коллекцию макросов, которые могут быть
использованы для быстрого разрешения или запрещения служб. Вы можете найти
список макросов включенный в Вашу версия Shorewall при помощи
команды:ls
/usr/share/shorewall/macro.*Если Вы хотите разрешить соединения из Интернет на Ваш файервол и Вы
нашли соответствующий макрос в
/etc/shorewall/macro.*, то общий формат правила в
/etc/shorewall/rules такой:#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
<macro>/ACCEPT net $FWВы хотите запустить Web-сервер и IMAP-сервер на Вашем
файерволе:#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
Web/ACCEPT net $FW
IMAP/ACCEPT net $FWВы можете также указать Ваше правило непосредственно, без
использования предопределенного макроса. Это будет необходимо в случае,
если нет предопределенного макроса соответствующего Вашим требованиям. В
этом случае общий формат правила в
/etc/shorewall/rules такой:#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
ACCEPT net $FW <protocol><port>Вы хотите запустить Web-сервер и IMAP-сервер на Вашем
файерволе:#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
ACCEPT net $FW tcp 80
ACCEPT net $FW tcp 143Если Вы не знаете какой порт и протокол использует определенное
приложение, смотрите здесь.Я не рекоммендую разрешать telnet в/из Интернет потому, что он
использует открытый текст (даже для передачи имени и пароля!). Если Вы
хотите иметь доступ к командному интерпретатору Вашего файервола из
Интернет, используйте SSH:#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
SSH/ACCEPT net $FW В этом месте, отредактируйте
/etc/shorewall/rules для добавления необходимых
соединений.Запуск и останов Вашего файерволаПроцедура установки настраивает
Вашу систему для запуска 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.Если Вы подсоединены к Вашему файерволу из Интернет, не
используйте команду shorewall stop
если Вы не добавили запись для IP-адреса, с которого
Вы подсоединены, в /etc/shorewall/routestopped.
Также, я не рекоммендую использовать shorewall
restart; лучше создать альтернативную
конфигурацию и протестировать ее при помощи команды
shorewall
try.Дополнительно рекоммендуемая литератураЯ особо рекоммендую просмотреть Вам страницу Общих Особенностей Файлов
Конфигурации -- она содержит полезные советы об особенностях
Shorewall, делающую администрирование Вашего файервола проще.История пересмотров2.02005-09-12TEБольше обновлений для 3.01.92005-09-02CRОбновление для Shorewall 3.01.82005-07-12TEИсправлена неверная ссылка на rfc1918.1.72004-02-16TEФайл /etc/shorewall/rfc1918 перемещен в
/usr/share/shorewall.1.62004-02-05TEОбновление для Shorewall 2.01.52004-01-05TEСтандартные изменения1.42003-12-30TEДобавлен срвет по обновлению
/etc/shorewall/rfc1918.1.32003-11-15TEНачальное преобразование DocBook
shorewall-docs-xml-5.2.3/VPN.xml 0000664 0000000 0000000 00000013443 13427347317 015152 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 TraversalACTIONSOURCEDESTPROTODPORTSPORTORIGDESTDNATnet: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.2.3/Shorewall-init.xml 0000664 0000000 0000000 00000023646 13427347317 017416 0 ustar root root
Shorewall InitTomEastep2010Thomas 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.IntroductionThe Shorewall init scripts released from shorewall.net and by most
distributions start Shorewall after networking. This allows Shorewall to
detect the network configuration and taylor itself accordingly. It is
possible to start Shorewall prior to networking but doing so limits the
set of Shorewall features that can be used.When Shorewall starts after networking, there is the possibility of
unwanted connections being accepted between the time that an interface
comes up and the time that Shorewall has finished starting up. Also,
Shorewall has had no means of reacting when interfaces are brought up and
down.Beginning with Shorewall 4.4.10, a new package, Shorewall
Init, is available. Shorewall Init serves two purposes:It can 'close' the firewall before the network interfaces are
brought up during boot.It can change the firewall state as the result of interfaces
being brought up or taken down.These two features can be controlled independently. Shorewall Init
can be used together with any combination of the other Shorewall packages.
Shorewall-init works on RedHat-based, SuSE-based and Debian-based
distributions.Closing the Firewall before the Network Interfaces are brought
upWhen Shorewall-init is first installed, it does nothing until you
configure it.The configuration file is /etc/default/shorewall-init
on Debian-based systems and
/etc/sysconfig/shorewall-init otherwise. There are
two settings in the file:PRODUCTSLists the Shorewall packages that you want to integrate with
Shorewall-init.Example: PRODUCTS="shorewall shorewall6"IFUPDOWNWhen set to 1, enables integration with NetworkManager and the
ifup/ifdown scripts.To close your firewall before networking starts:In the Shorewall-init configuration file, set PRODUCTS to the
firewall products installed on your system.Be sure that your current firewall script(s) (normally in
/var/lib/<product>/firewall) is(are)
compiled with the 4.4.10 compiler.Shorewall and Shorewall6 users can execute these
commands:shorewall compileshorewall6 compileShorewall-lite and Shorewall6-lite users can execute these
commands on the administrative system:shorewall export
firewall-name-or-ip-addressshorewall6 export
firewall-name-or-ip-addressThat's all that is required.Integration with NetworkManager and ifup/ifdown ScriptsTo integrate with NetworkManager and ifup/ifdown, additional steps
are required. You probably don't want to enable this feature if you run a
link status monitor like FOOLSM.In the Shorewall-init configuration file, set IFUPDOWN=1.In your Shorewall interfaces file(s), set the
option on any interfaces that must be up in
order for the firewall to start. At least one interface must have the
or option if you
perform the next optional step.Optional) -- If you have specified at least one
or interface, you
can then disable automatic firewall startup at boot time. On Debian
systems, set startup=0 in
/etc/default/product.
On other systems, use your service startup configuration tool
(chkconfig, insserv, ...) to disable startup.If your system uses Upstart as it's system initialization
daemon, you should not disable startup. Upstart is standard on
recent Ubuntu and Fedora releases and is optional on Debian.The following actions occur when an interface comes up:FIREWALL STATEINTERFACEACTIONAnyRequiredstartstoppedOptionalstartstartedOptionalenablestartedAnyrestartThe following actions occur when an interface goes down:FIREWALL STATEINTERFACEACTIONAnyRequiredstopstoppedOptionalstartstartedOptionaldisablestartedAnyrestartFor optional interfaces, the
/var/lib/product/interface.state
files are maintained to reflect the state of the interface so that they
may be used by the standard isusable script. Please
note that the action is carried out using the current compiled script; the
configuration is not recompiled.A new option has been added to shorewall.conf
and shorewall6.conf. The REQUIRE_INTERFACE option
determines the outcome when an attempt to start/restart/restore/refresh
the firewall is made and none of the optional interfaces are available.
With REQUIRE_INTERFACE=No (the default), the operation is performed. If
REQUIRE_INTERFACE=Yes, then the operation fails and the firewall is placed
in the stopped state. This option is suitable for a laptop with both
ethernet and wireless interfaces. If either come up, the firewall starts.
If neither comes up, the firewall remains in the stopped state.Similarly, if an optional interface goes down and there are no
optional interfaces remaining in the up state, then the firewall is
stopped.On Debian-based systems, during system shutdown the firewall is
opened prior to network shutdown (/etc/init.d/shorewall
stop performs a 'clear' operation rather than a 'stop'). This is
required by Debian standards. You can change this default behavior by
setting SAFESTOP=1 in /etc/default/shorewall
(/etc/default/shorewall6, ...).
shorewall-docs-xml-5.2.3/shorewall_extension_scripts.xml 0000664 0000000 0000000 00000060760 13427347317 022356 0 ustar root root
Extension Scripts (User Exits)TomEastep2001-2010Thomas 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.Extension ScriptsExtension scripts are user-provided scripts that are invoked at
various points during firewall start, restart, stop and clear. For each
script, the Shorewall compiler creates a Bourne Shell function with the
extension script as its body and calls the function at runtime.Be sure that you actually need to use an extension script to
do what you want. Shorewall has a wide range of features that cover
most requirements.DO NOT SIMPLY COPY RULES THAT YOU FIND ON THE NET INTO AN
EXTENSION SCRIPT AND EXPECT THEM TO WORK AND TO NOT BREAK SHOREWALL.
TO USE SHOREWALL EXTENSION SCRIPTS YOU MUST KNOW WHAT YOU ARE DOING
WITH RESPECT TO iptables/Netfilter AND SHOREWALL.The following scripts can be supplied:lib.private -- Intended to contain
declarations of shell functions to be called by other run-time
extension scripts. See this
article for an example of its use.compile -- Invoked by the rules compiler
early in the compilation process. Must be written in Perl.init -- invoked early in shorewall
start and shorewall restartinitdone -- invoked after Shorewall has
flushed all existing rules but before any rules have been added to the
builtin chains.start -- invoked after the firewall has
been started or restarted.started -- invoked after the firewall has
been marked as 'running'.stop -- invoked as a first step when the
firewall is being stopped.stopped -- invoked after the firewall has
been stopped.clear -- invoked after the firewall has
been cleared.tcclear -- invoked to clear traffic shaping
when CLEAR_TC=Yes in shorewall.conf.refresh -- called in place of
init when the firewall is being refreshed rather
than started or restarted.refreshed -- invoked after the firewall has
been refreshed.maclog -- invoked while mac filtering rules
are being created. It is invoked once for each interface having
'maclist' specified and it is invoked just before the logging rule is
added to the current chain (the name of that chain will be in
$CHAIN).isusable -- invoked when Shorewall is
trying to determine the usability of the network interface associated
with an optional entry in
/etc/shorewall/providers. $1 is the name of the
interface which will have been determined to be up and configured
before the script is invoked. The return value from the script
indicates whether or not the interface is usable (0 = usable, other =
unusable).Example:# Ping a gateway through the passed interface
case $1 in
eth0)
ping -c 4 -t 1 -I eth0 206.124.146.254 > /dev/null 2>&1
return
;;
eth1)
ping -c 4 -t 1 -I eth1 192.168.12.254 > /dev/null 2>&1
return
;;
*)
# No additional testing of other interfaces
return 0
;;
esacWe recommend that this script only be used with
ADMINISABSENTMINDED=Yes.The firewall state when this script is invoked is
indeterminate. So if you have ADMINISABSENTMINDED=No in shorewall.conf(8) and
output on an interface is not allowed by stoppedrules(8)
then the isuasable script must blow it's own holes in the firewall
before probing.save -- This script is invoked during
execution of the shorewall save and
shorewall-lite save commands.restored -- This script is invoked at the
completion of a successful shorewall restore and
shorewall-lite restore.findgw -- This script is invoked when Shorewall is attempting to
discover the gateway through a dynamic interface. The script is most
often used when the interface is managed by dhclient which has no
standardized location/name for its lease database. Scripts for use
with dhclient on several distributions are available at http://www.shorewall.net/pub/shorewall/contrib/findgw/scfilter -- Added in Shorewall 4.4.14.
Unlike the other scripts, this script is executed by the command-line
tools (/sbin/shorewall,
/sbin/shorewall6, etc) and can be used to
reformat the output of the show connections
command. The connection information is piped through this script so
that the script can drop information, add information or alter the
format of the information. When using Shorewall Lite or Shorewall6
Lite, the script is encapsulated in a function that is copied into the
generated auxillary configuration file. That function is invoked by
the 'show connections' command.The default script is as follows and simply pipes the output
through unaltered.#! /bin/sh
cat -postcompile -- Added in Shorewall 4.5.8.
This shell script is invoked by
/sbin/shorewall after a script has been compiled. $1 is the
path name of the compiled script.lib.cli-user -- Added in Shorewall 5.0.2.
This is actually a shell library (set of function declarations) that
can be used to augment or replace functions in the standard CLI
libraries.enabled -- Added in Shorewall 5.1.6.
Invoked when an optional interface or provider is successfully enabled
using the enable command.disabled -- Added in Shorewall 5.1.6.
Invoked when an optional interface or provider is successfully
disabled using the disable command.If your version of Shorewall doesn't have the
file that you want to use from the above list, you can simply create the
file yourself. You can also supply a script with the same name
as any of the filter chains in the firewall and the script will be invoked
after the /etc/shorewall/rules file has been processed but before the
/etc/shorewall/policy file has been processed.The following table indicate which commands invoke the various
scripts.scriptCommandsclearclearcompilecheck, compile, export, load, refresh, reload, restart,
restore,startcontinuedisabledisableenableenableinitload, refresh, reload, restart restore, startinitdonecheck, compile, export, refresh, restart, startisusablerefresh, restart, restore, startmaclogcheck, compile, export, refresh, restart, startpostcompilecompile, export, load, refresh, reload, restart, restore,
startrefreshrefreshrefreshedrefreshrestoredrestoresavesavescfiltershow connectionsstartload, reload, restart, startstartedload, reload, restart, startstopstop, clearstoppedstop, cleartcclearload, reload, restart, restore, startThere are a couple of special considerations for commands in
extension scripts:When you want to run iptables, use the
command run_iptables instead.
run_iptables will run the iptables utility passing
the arguments to run_iptables and if the command
fails, the firewall will be stopped (or restored from the last
save command, if any).
run_iptables should not be called from the
started or restored
scripts.If you wish to generate a log message, use log_rule_limit. Parameters are:Log LevelChain to insert the rule intoChain name to display in the message (this can be different
from the preceding argument — see the Port Knocking article for an
example of how to use this).Disposition to report in the message (ACCEPT, DROP,
etc)Rate Limit (if passed as "" then $LOGLIMIT is assumed — see
the LOGLIMIT option in /etc/shorewall/shorewall.conf)Log Tag ("" if none)Command (-A or -I for append or insert).The remaining arguments are passed "as is" to
iptablesMany of the extension scripts get executed for both the
shorewall start and shorewall restart commands. You can determine
which command is being executed using the contents of $COMMAND.if [ $COMMAND = start ]; then
...In addition to COMMAND, Shorewall defines three other variables
that may be used for locating Shorewall files:CONFDIR - The configuration directory. Will be /etc/.
The running product is defined in the g_product variable.SHAREDIR - The product shared directory. Will be /usr/share.
The running product is defined in the g_product variable.VARDIR - The product state directory. Defaults /var/lib/shorewall, /var/lib/shorewall6/, /var/lib/shorewall-lite, or /var/lib/shorewall6-lite depending on
which product is running, but may be overridden by an entry in
${CONFDIR}/vardir.Shell variables used in extension scripts must follow the same
rules as those in /etc/shorewall/params. See
this article.Compile-time vs Run-time ScriptsShorewall runs some extension scripts at compile-time rather than
at run-time.The following table summarizes when the various extension scripts
are run:Compile-timeRun-timecompileclearinitdonedisablemaclogenablePer-chain (including those associated with
actions)initpostcompileisusablestartstartedstopstoppedtcclearrefreshrefreshedrestoredscfilterThe contents of each run-time script is placed in a shell
function, so you can declare local variables and can use the
return command. The functions generated from the
enable and disable scripts are
passed three arguments:$1Physical name of the interface that was enabled or
disabled.$2Logical name of the interface.$3Name of the Provider, if any, associated with the
interface.As described above, the function generated from the
isusable script is passed a single argument that
names a network interface.With the exception of postcompile, compile-time extension scripts
are executed using the Perl 'eval `cat
<file>`' mechanism. Be sure that each script
returns a 'true' value; otherwise, the compiler will assume that the
script failed and will abort the compilation.Each compile-time script is implicitly prefaced with:package Shorewall::User;Most scripts will need to begin with the following
line:use Shorewall::Chains;For more
complex scripts, you may need to 'use' other Shorewall Perl modules --
browse /usr/share/shorewall/Shorewall/ to see
what's available.When a script is invoked, the $chainref scalar variable will hold a reference
to a chain table entry.$chainref->{name}
contains the name of the chain$chainref->{table} holds
the table nameTo add a rule to the chain:add_rule( $chainref, <the rule> [ , <break lists> ] );Where<the rule> is a scalar argument
holding the rule text. Do not include "-A <chain
name>"Example:add_rule( $chainref, '-j ACCEPT' );The add_rule() function accepts an optional third argument; If
that argument evaluates to true and the passed rule contains a --dports or --sports list with more than 15 ports (a port
range counts as two ports), the rule will be split into multiple rules
where each resulting rule has 15 or fewer ports in its --dports and --sports lists.To insert a rule into the chain: insert_rule( $chainref, <rulenum>, <the rule> );The
log_rule_limit() function works like it
did in the shell compiler with three exceptions:You pass the chain reference rather than the name of the
chain.The commands are 'add' and 'insert' rather than '-A' and
'-I'.There is only a single "pass as-is to iptables" argument (so
you must quote that part).Example:log_rule_limit(
'info' , #Log Level
$chainref , #Chain to add the rule to
$chainref->{name}, #Name of the chain as it will appear in the log prefix
'DROP' , #Disposition of the packet
'', #Limit
'' , #Log tag
'add', #Command
'-p tcp' #Added to the rule as-is
);Note that in the 'initdone' script, there is
no default chain ($chainref). You can
obtain a reference to a standard chain by:my $chainref = $chain_table{<table>}{<chain name>};Example:my $chainref = $chain_table{filter}{INPUT};You can also use the hash references $filter_table, $mangle_table and $nat_table to access chain references in the
three main tables.Example:my $chainref = $filter_table->{INPUT}; #Same as above with a few less keystrokes; runs faster tooFor imformation about the 'compile' extension script, see the
Manual Chains article.
shorewall-docs-xml-5.2.3/GnuCopyright.xml 0000664 0000000 0000000 00000054245 13427347317 017136 0 ustar root root
GNU Free Documentation LicenseVersion 1.2, November 2002
Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
PREAMBLEThe purpose of this License is to make a manual, textbook, or
other functional and useful document "free" in the sense of freedom: to
assure everyone the effective freedom to copy and redistribute it, with
or without modifying it, either commercially or noncommercially.
Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible for
modifications made by others.This License is a kind of "copyleft", which means that derivative
works of the document must themselves be free in the same sense. It
complements the GNU General Public License, which is a copyleft license
designed for free software.We have designed this License in order to use it for manuals for
free software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does. But this License is not limited to software manuals; it
can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or reference.APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work, in
any medium, that contains a notice placed by the copyright holder saying
it can be distributed under the terms of this License. Such a notice
grants a world-wide, royalty-free license, unlimited in duration, to use
that work under the conditions stated herein. The "Document", below,
refers to any such manual or work. Any member of the public is a
licensee, and is addressed as "you". You accept the license if you
copy, modify or distribute the work in a way requiring permission under
copyright law.A "Modified Version" of the Document means any
work containing the Document or a portion of it, either copied verbatim,
or with modifications and/or translated into another language.A "Secondary Section" is a named appendix or
a front-matter section of the Document that deals exclusively with the
relationship of the publishers or authors of the Document to the
Document's overall subject (or to related matters) and contains nothing
that could fall directly within that overall subject. (Thus, if the
Document is in part a textbook of mathematics, a Secondary Section may
not explain any mathematics.) The relationship could be a matter of
historical connection with the subject or with related matters, or of
legal, commercial, philosophical, ethical or political position
regarding them.The "Invariant Sections" are certain Secondary
Sections whose titles are designated, as being those of Invariant
Sections, in the notice that says that the Document is released under
this License. If a section does not fit the above definition of
Secondary then it is not allowed to be designated as Invariant. The
Document may contain zero Invariant Sections. If the Document does not
identify any Invariant Sections then there are none.The "Cover Texts" are certain short passages of
text that are listed, as Front-Cover Texts or Back-Cover Texts, in the
notice that says that the Document is released under this License. A
Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at
most 25 words.A "Transparent" copy of the Document means a
machine-readable copy, represented in a format whose specification is
available to the general public, that is suitable for revising the
document straightforwardly with generic text editors or (for images
composed of pixels) generic paint programs or (for drawings) some widely
available drawing editor, and that is suitable for input to text
formatters or for automatic translation to a variety of formats suitable
for input to text formatters. A copy made in an otherwise Transparent
file format whose markup, or absence of markup, has been arranged to
thwart or discourage subsequent modification by readers is not
Transparent. An image format is not Transparent if used for any
substantial amount of text. A copy that is not "Transparent" is called
"Opaque".Examples of suitable formats for Transparent copies include plain
ASCII without markup, Texinfo input format, LaTeX input format, SGML or
XML using a publicly available DTD, and standard-conforming simple HTML,
PostScript or PDF designed for human modification. Examples of
transparent image formats include PNG, XCF and JPG. Opaque formats
include proprietary formats that can be read and edited only by
proprietary word processors, SGML or XML for which the DTD and/or
processing tools are not generally available, and the machine-generated
HTML, PostScript or PDF produced by some word processors for output
purposes only.The "Title Page" means, for a printed book,
the title page itself, plus such following pages as are needed to hold,
legibly, the material this License requires to appear in the title page.
For works in formats which do not have any title page as such, "Title
Page" means the text near the most prominent appearance of the work's
title, preceding the beginning of the body of the text.A section "Entitled XYZ" means a named subunit
of the Document whose title either is precisely XYZ or contains XYZ in
parentheses following text that translates XYZ in another language.
(Here XYZ stands for a specific section name mentioned below, such as
"Acknowledgements", "Dedications", "Endorsements", or "History".) To
"Preserve the Title" of such a section when you modify the Document
means that it remains a section "Entitled XYZ" according to this
definition.The Document may include Warranty Disclaimers next to the notice
which states that this License applies to the Document. These Warranty
Disclaimers are considered to be included by reference in this License,
but only as regards disclaiming warranties: any other implication that
these Warranty Disclaimers may have is void and has no effect on the
meaning of this License.VERBATIM COPYINGYou may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies to
the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further copying
of the copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a large enough
number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above,
and you may publicly display copies.COPYING IN QUANTITYIf you publish printed copies (or copies in media that commonly
have printed covers) of the Document, numbering more than 100, and the
Document's license notice requires Cover Texts, you must enclose the
copies in covers that carry, clearly and legibly, all these Cover Texts:
Front-Cover Texts on the front cover, and Back-Cover Texts on the back
cover. Both covers must also clearly and legibly identify you as the
publisher of these copies. The front cover must present the full title
with all words of the title equally prominent and visible. You may add
other material on the covers in addition. Copying with changes limited
to the covers, as long as they preserve the title of the Document and
satisfy these conditions, can be treated as verbatim copying in other
respects.If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.If you publish or distribute Opaque copies of the Document
numbering more than 100, you must either include a machine-readable
Transparent copy along with each Opaque copy, or state in or with each
Opaque copy a computer-network location from which the general
network-using public has access to download using public-standard
network protocols a complete Transparent copy of the Document, free of
added material. If you use the latter option, you must take reasonably
prudent steps, when you begin distribution of Opaque copies in quantity,
to ensure that this Transparent copy will remain thus accessible at the
stated location until at least one year after the last time you
distribute an Opaque copy (directly or through your agents or retailers)
of that edition to the public.It is requested, but not required, that you contact the authors of
the Document well before redistributing any large number of copies, to
give them a chance to provide you with an updated version of the
Document.MODIFICATIONSYou may copy and distribute a Modified Version of the Document
under the conditions of sections 2 and 3 above, provided that you
release the Modified Version under precisely this License, with the
Modified Version filling the role of the Document, thus licensing
distribution and modification of the Modified Version to whoever
possesses a copy of it. In addition, you must do these things in the
Modified Version:Use in the Title Page (and on the covers, if any) a
title distinct from that of the Document, and from those of previous
versions (which should, if there were any, be listed in the History
section of the Document). You may use the same title as a previous
version if the original publisher of that version gives permission.
List on the Title Page, as authors, one or more
persons or entities responsible for authorship of the modifications in
the Modified Version, together with at least five of the principal
authors of the Document (all of its principal authors, if it has fewer
than five), unless they release you from this requirement.
State on the Title page the name of the publisher of
the Modified Version, as the publisher.Preserve all the copyright notices of the Document.
Add an appropriate copyright notice for your
modifications adjacent to the other copyright notices.
Include, immediately after the copyright notices, a
license notice giving the public permission to use the Modified
Version under the terms of this License, in the form shown in the
Addendum below.
Preserve in that license notice the full lists of
Invariant Sections and required Cover Texts given in the Document's
license notice.Include an unaltered copy of this License.
Preserve the section Entitled "History", Preserve its
Title, and add to it an item stating at least the title, year, new
authors, and publisher of the Modified Version as given on the Title
Page. If there is no section Entitled "History" in the Document,
create one stating the title, year, authors, and publisher of the
Document as given on its Title Page, then add an item describing the
Modified Version as stated in the previous sentence.
Preserve the network location, if any, given in the
Document for public access to a Transparent copy of the Document, and
likewise the network locations given in the Document for previous
versions it was based on. These may be placed in the "History"
section. You may omit a network location for a work that was
published at least four years before the Document itself, or if the
original publisher of the version it refers to gives permission.
For any section Entitled "Acknowledgements" or
"Dedications", Preserve the Title of the section, and preserve in the
section all the substance and tone of each of the contributor
acknowledgements and/or dedications given therein.
Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles. Section numbers or the
equivalent are not considered part of the section titles.
Delete any section Entitled "Endorsements".
Such a section may not be included in the Modified Version.
Do not retitle any existing section to be Entitled
"Endorsements" or to conflict in title with any Invariant Section.
Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant. To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.You may add a section Entitled "Endorsements", provided it
contains nothing but endorsements of your Modified Version by various
parties--for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.You may add a passage of up to five words as a Front-Cover Text,
and a passage of up to 25 words as a Back-Cover Text, to the end of the
list of Cover Texts in the Modified Version. Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or through
arrangements made by) any one entity. If the Document already includes
a cover text for the same cover, previously added by you or by
arrangement made by the same entity you are acting on behalf of, you may
not add another; but you may replace the old one, on explicit permission
from the previous publisher that added the old one.The author(s) and publisher(s) of the Document do not by this
License give permission to use their names for publicity for or to
assert or imply endorsement of any Modified Version.COMBINING DOCUMENTSYou may combine the Document with other documents released under
this License, under the terms defined in section
4 above for modified versions, provided that you include in the
combination all of the Invariant Sections of all of the original
documents, unmodified, and list them all as Invariant Sections of your
combined work in its license notice, and that you preserve all their
Warranty Disclaimers.The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy. If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by adding
at the end of it, in parentheses, the name of the original author or
publisher of that section if known, or else a unique number. Make the
same adjustment to the section titles in the list of Invariant Sections
in the license notice of the combined work.In the combination, you must combine any sections Entitled
"History" in the various original documents, forming one section
Entitled "History"; likewise combine any sections Entitled
"Acknowledgements", and any sections Entitled "Dedications". You must
delete all sections Entitled "Endorsements".COLLECTIONS OF DOCUMENTSYou may make a collection consisting of the Document and other
documents released under this License, and replace the individual copies
of this License in the various documents with a single copy that is
included in the collection, provided that you follow the rules of this
License for verbatim copying of each of the documents in all other
respects.You may extract a single document from such a collection, and
distribute it individually under this License, provided you insert a
copy of this License into the extracted document, and follow this
License in all other respects regarding verbatim copying of that
document.AGGREGATION WITH INDEPENDENT WORKSA compilation of the Document or its derivatives with other
separate and independent documents or works, in or on a volume of a
storage or distribution medium, is called an "aggregate" if the
copyright resulting from the compilation is not used to limit the legal
rights of the compilation's users beyond what the individual works
permit. When the Document is included in an aggregate, this License does
not apply to the other works in the aggregate which are not themselves
derivative works of the Document.If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one half of
the entire aggregate, the Document's Cover Texts may be placed on covers
that bracket the Document within the aggregate, or the electronic
equivalent of covers if the Document is in electronic form. Otherwise
they must appear on printed covers that bracket the whole
aggregate.TRANSLATIONTranslation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections. You may include a
translation of this License, and all the license notices in the
Document, and any Warranty Disclaimers, provided that you also include
the original English version of this License and the original versions
of those notices and disclaimers. In case of a disagreement between the
translation and the original version of this License or a notice or
disclaimer, the original version will prevail.If a section in the Document is Entitled "Acknowledgements",
"Dedications", or "History", the requirement (section 4) to Preserve its
Title (section 1) will typically require changing the actual
title.TERMINATIONYou may not copy, modify, sublicense, or distribute the Document
except as expressly provided for under this License. Any other attempt
to copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this License
will not have their licenses terminated so long as such parties remain
in full compliance.FUTURE REVISIONS OF THIS LICENSEThe Free Software Foundation may publish new, revised versions of
the GNU Free Documentation License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns. See
http://www.gnu.org/copyleft/.Each version of the License is given a distinguishing version
number. If the Document specifies that a particular numbered version of
this License "or any later version" applies to it, you have the option
of following the terms and conditions either of that specified version
or of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.ADDENDUM: How to use this License for
your documentsTo use this License in a document you have written, include a copy
of the License in the document and put the following copyright and
license notices just after the title page:
Copyright (c) YEAR YOUR NAME.
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, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover
Texts, replace the "with...Texts." line with this:
with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of free
software license, such as the GNU General Public License, to permit
their use in free software.
shorewall-docs-xml-5.2.3/shorewall_features.xml 0000664 0000000 0000000 00000021457 13427347317 020411 0 ustar root root
Shorewall 5.0 FeaturesTomEastep2001-2016Thomas 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.FeaturesUses Netfilter's connection tracking facilities for stateful
packet filtering.Can be used in a wide range of
router/firewall/gateway applications .Completely customizable using configuration files.No limit on the number of network interfaces.Allows you to partition the network into zones and gives you
complete control over the connections permitted between each pair
of zones.Multiple interfaces per zone and multiple zones per
interface permitted.Supports nested and overlapping zones.Supports centralized firewall
administration.Shorewall installed on a single administrative system. May
be a Windows PC running
Cygwin or an Apple
MacIntosh running OS X.Centrally generated firewall scripts run on the firewalls
under control of Shorewall-lite.QuickStart Guides
(HOWTOs) to help get your first firewall up and running
quicklyA GUI is available via Webmin
1.060 and later (http://www.webmin.com)Extensive documentation is
available in both Docbook XML and HTML formats.Flexible address management/routing
support (and you can use all types in the same
firewall):Masquerading/SNAT.Port Forwarding
(DNAT).One-to-one NAT.Proxy ARP.NETMAP.Multiple ISP support
(Multiple Internet Links from the same firewall/gateway)Blacklisting of individual IP addresses
and subnetworks is supported.Operational
Support.Commands to start, stop and clear the firewallSupports status monitoring with an audible alarm when an
interesting packet is detected.Wide variety of informational commands.VPN Support.IPsec, GRE,
IPIP and OpenVPN Tunnels.PPTP clients and
Servers.Support for Traffic Control/Shaping.Wide support for different GNU/Linux
Distributions.RPM and Debian packages
available.Includes automated install, upgrade
and uninstall facilities for users who can't use or choose
not to use the RPM or Debian packages.Included as a standard part of LEAF/Bering
(router/firewall on a floppy, CD or compact flash).Media Access Control (MAC) Address Verification.Traffic
Accounting.Bridge/Firewall supportIPv6 SupportWorks with a wide range of Virtualization Solutions:KVMXenLinux-VserverOpenVZVirtualBoxLXCDocker (Shorewall 5.0.6 and later)
shorewall-docs-xml-5.2.3/Shorewall-Lite.xml 0000664 0000000 0000000 00000101252 13427347317 017336 0 ustar root root
Shorewall LiteTomEastep2006-2011Thomas 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 appropriate for your
version.OverviewShorewall has the capability to compile a Shorewall configuration
and produce a runnable firewall program script. The script is a complete
program which can be placed on a system with Shorewall
Lite installed and can serve as the firewall creation script
for that system.Shorewall LiteShorewall Lite is a companion product to Shorewall and is designed
to allow you to maintain all Shorewall configuration information on a
single system within your network.You install the full Shorewall release on one system within
your network. You need not configure Shorewall there and you may
totally disable startup of Shorewall in your init scripts. For ease
of reference, we call this system the 'administrative
system'.The administrative system may be a GNU/Linux system, a Windows
system running Cygwin or
an Apple MacIntosh
running OS X. Install from a shell prompt using the install.sh script.On each system where you wish to run a Shorewall-generated
firewall, you install Shorewall Lite. For ease of reference, we will
call these systems the 'firewall systems'.The firewall systems do NOT
need to have the full Shorewall product installed but rather only
the Shorewall Lite product. Shorewall and Shorewall Lite may be
installed on the same system but that isn't encouraged.On the administrative system you create a separate 'export
directory' for each firewall system. You copy the contents of
/usr/share/shorewall/configfiles into
each export directory.Users of Debian and derivatives that install the package
from their distribution will be disappointed to find that
/usr/share/shorewall/configfiles does
not exist on their systems. They will instead need to
either:Copy the files in
/usr/share/doc/shorewall/default-config/ into each export
directory.Copy /etc/shorewall/shorewall.conf into each export
directory and remove /etc/shorewall from the CONFIG_PATH
setting in the copied files.orDownload the Shorewall tarball corresponding to their
package version.Untar and copy the files from the
configfiles sub-directory in the untarred
shorewall-... directory.After copying, you may need to change two setting in the copy
of shorewall.conf:CONFIG_PATH=/usr/share/shorewallSTARTUP_LOG=/var/log/shorewall-lite-init.logOlder versions of Shorewall included copies of shorewall.conf
with these settings already modified. This practice was discontinued
in Shorewall 4.4.20.1.Prior to Shorewall 4.5.8, the
/etc/shorewall/shorewall.conf file was used to
determine the VERBOSITY setting which determines how much output the
compiler generates. All other settings were taken from the
shorewall.conf file in the remote systems
export directory.Prior to Shorewall 4.5.8, if you want to be able to allow
non-root users to manage remote firewall systems, then the files
/etc/shorewall/params and
/etc/shorewall/shorewall.conf must be
readable by all users on the administrative system. Not all
packages secure the files that way and you may have to change the
file permissions yourself.Prior to Shorewall 4.5.14,
/etc/shorewall/params must be readable by
non-root users or each export directory must have its own params
file.On each firewall system, If you are running Debian or one of
its derivatives like Ubuntu then edit
/etc/default/shorewall-lite and set
startup=1.On the administrative system, for each firewall system you do
the following (this may be done by a non-root user who has root ssh
access to the firewall system):modify the files in the corresponding export directory
appropriately (i.e., just as you would if you were
configuring Shorewall on the firewall system itself).
It's a good idea to include the IP address of the administrative
system in the stoppedrules
file.It is important to understand that with Shorewall Lite,
the firewall's export directory on the administrative system
acts as /etc/shorewall
for that firewall. So when the Shorewall documentation gives
instructions for placing entries in files in the firewall's
/etc/shorewall, when
using Shorewall Lite you make those changes in the firewall's
export directory on the administrative system.The CONFIG_PATH variable is treated as follows:The value of CONFIG_PATH in
/etc/shorewall/shorewall.conf is
ignored when compiling for export (the -e option in given)
and when the load or
reload command is being executed (see
below).The value of CONFIG_PATH in the
shorewall.conf file in the export
directory is used to search for configuration files during
compilation of that configuration.The value of CONFIG_PATH used when the script is run
on the firewall system is
"/etc/shorewall-lite:/usr/share/shorewall-lite".Prior to Shorewall 4.5.14, the export directory should
contain a params file, even if it is
empty. Otherwise, /sbin/shorewall will
attempt to read
/etc/shorewall/params.If the remote system has a different directory layout
from the administrative system, then the export directory
should contain a copy of the remote system's shorewallrc
file (normally found in
/usr/share/shorewall/shorewallrc).cd <export directory>/sbin/shorewall load firewallThe load
command compiles a firewall script from the configuration files
in the current working directory (using shorewall
compile -e), copies that file to the remote system via
scp and starts Shorewall Lite on the remote system via
ssh.Example (firewall's DNS name is 'gateway'):/sbin/shorewall load gatewayAlthough scp and ssh are used by default, you can use
other utilities by setting RSH_COMMAND and RCP_COMMAND in
/etc/shorewall/shorewall.conf.The first time that you issue a load
command, Shorewall will use ssh to run
/usr/share/shorewall-lite/shorecap on the
remote firewall to create a capabilities file in the firewall's
administrative direction. It also uses scp to copy the
shorewallrc file from the remote firewall system. See below.If you later need to change the firewall's configuration,
change the appropriate files in the firewall's export directory
then:cd <export directory>/sbin/shorewall reload firewallThe reload
command compiles a firewall script from the configuration files in
the current working directory (using shorewall compile
-e), copies that file to the remote system via scp and
restarts Shorewall Lite on the remote system via ssh. The reload command also supports the '-c'
option.There is a shorewall-lite.conf file installed
as part of Shorewall Lite
(/etc/shorewall-lite/shorewall-lite.conf). You can
use that file on the firewall system to override some of the settings
from the shorewall.conf file in the export directory.Settings that you can override are:
You will normally never touch
/etc/shorewall-lite/shorewall-lite.conf unless you
run Debian or one of its derivatives (see above).The /sbin/shorewall-lite program included
with Shorewall Lite supports the same set of commands as the
/sbin/shorewall program in a full Shorewall
installation with the following exceptions:
On systems with only Shorewall Lite installed, I recommend that
you create a symbolic link /sbin/shorewall and
point it at /sbin/shorewall-lite. That way, you can
use shorewall as the command regardless of which
product is installed.
ln -sf shorewall-lite /sbin/shorewall
Module LoadingAs with a normal Shorewall configuration, the shorewall.conf
file can specify LOAD_HELPERS_ONLY which determines if the
modules file (LOAD_HELPERS_ONLY=No) or
helpers file (LOAD_HELPERS_ONLY=Yes) is used.
Normally, the file on the firewall system is used. If you want to
specify modules at compile time on the Administrative System, then you
must place a copy of the appropriate file
(modules or helpers) in the
firewall's configuration directory before compilation.In Shorewall 4.4.17, the EXPORTMODULES option was added to
shorewall.conf (and shorewall6.conf). When EXPORTMODULES=Yes, any
modules or helpers file
found on the CONFIG_PATH on the Administrative System during
compilation will be used.In Shorewall 5.2.3, the LOAD_HELPERS_ONLY option was removed and
the behavior is that which was formerly obtained by setting
LOAD_HELPERS_ONLY=Yes.Converting a system from Shorewall to Shorewall LiteConverting a firewall system that is currently running Shorewall
to run Shorewall Lite instead is straight-forward.On the administrative system, create an export directory for
the firewall system.Copy the contents of /etc/shorewall/ from the firewall
system to the export directory on the administrative
system.On the firewall system:Be sure that the IP address of the administrative system is
included in the firewall's export directory
stoppedrules file.shorewall stopWe recommend that you uninstall
Shorewall at this point.Install Shorewall Lite on the firewall system.If you are running Debian or one of its derivatives like
Ubuntu then edit /etc/default/shorewall-lite
and set startup=1.On the administrative system:It's a good idea to include the IP address of the
administrative system in the firewall system's stoppedrules
file.Also, edit the shorewall.conf file in
the firewall's export directory and change the CONFIG_PATH setting
to remove /etc/shorewall.
You can replace it with /usr/share/shorewall/configfiles if
you like.Example:
Before editing:CONFIG_PATH=/etc/shorewall:/usr/share/shorewallAfter editing:CONFIG_PATH=/usr/share/shorewall/configfiles:/usr/share/shorewall
Changing CONFIG_PATH will ensure that subsequent
compilations using the export directory will not include any files
from /etc/shorewall other
than shorewall.conf and
params.If you set variables in the params file, there are a couple
of issues:The params file is not processed at run
time if you set EXPORTPARAMS=No in
shorewall.conf. For run-time setting of shell
variables, use the init extension script.
Beginning with Shorewall 4.4.17, the variables set in the
params file are available in the firewall
script when EXPORTPARAMS=No.If the params file needs to set shell
variables based on the configuration of the firewall system, you
can use this trick:EXT_IP=$(ssh root@firewall "/sbin/shorewall-lite call find_first_interface_address eth0")The shorewall-lite call command allows
you to to call interactively any Shorewall function that you can
call in an extension script.After having made the above changes to the firewall's export
directory, execute the following commands.
cd <export directory>/sbin/shorewall load <firewall system>Example (firewall's DNS name is 'gateway'):/sbin/shorewall load gateway
The first time that you issue a load
command, Shorewall will use ssh to run
/usr/share/shorewall-lite/shorecap on the
remote firewall to create a capabilities file in the firewall's
administrative direction. See below.The load
command compiles a firewall script from the configuration files in
the current working directory (using shorewall compile
-e), copies that file to the remote system via
scp and starts Shorewall Lite on the remote
system via ssh.If you later need to change the firewall's configuration,
change the appropriate files in the firewall's export directory
then:cd <export directory>/sbin/shorewall reload firewallThe reload
command compiles a firewall script from the configuration files in
the current working directory (using shorewall compile
-e), copies that file to the remote system via
scp and restarts Shorewall Lite on the remote
system via ssh.If the kernel/iptables configuration on the firewall later
changes and you need to create a new
capabilities file, do the following on the
firewall system:/usr/share/shorewall-lite/shorecap > capabilitiesscp capabilities <admin system>:<this system's config dir>Or simply use the -c option the next time that you use the
reload command (e.g., shorewall reload
-c gateway).RestrictionsWhile compiled Shorewall programs (as are used in Shorewall Lite)
are useful in many cases, there are some important restrictions that you
should be aware of before attempting to use them.All extension scripts used are copied into the program (with
the exception of those
executed at compile-time by the compiler). The ramifications
of this are:If you update an extension script, the compiled program
will not use the updated script.The params file is only processed at
compile time if you set EXPORTPARAMS=No in
shorewall.conf. For run-time setting of
shell variables, use the init extension
script. Although the default setting is EXPORTPARAMS=Yes for
compatibility, the recommended setting is EXPORTPARAMS=No.
Beginning with Shorewall 4.4.17, the variables set in the
params file are available in the firewall
script when EXPORTPARAMS=No.If the params file needs to set shell
variables based on the configuration of the firewall system, you
can use this trick:EXT_IP=$(ssh root@firewall "/sbin/shorewall-lite call find_first_interface_address eth0")The shorewall-lite call command allows
you to to call interactively any Shorewall function that you can
call in an extension script.You must install Shorewall Lite on the system where you want
to run the script. You then install the compiled program in
/usr/share/shorewall-lite/firewall and use the /sbin/shorewall-lite
program included with Shorewall Lite to control the firewall just as
if the full Shorewall distribution was installed.Beginning with Shorewall 4.4.9, the compiler detects bridges
and sets the bridge and routeback options explicitly. That can't
happen when the compilation no longer occurs on the firewall
system.The "shorewall compile" commandA compiled script is produced using the compile
command:
-eIndicates that the program is to be "exported" to another
system. When this flag is set, neither the "detectnets" interface
option nor DYNAMIC_ZONES=Yes in shorewall.conf are allowed. The
created program may be run on a system that has only Shorewall
Lite installedWhen this flag is given, Shorewall does not probe the
current system to determine the kernel/iptables features that it
supports. It rather reads those capabilities from
/etc/shorewall/capabilities. See below for
details.Also, when is specified you should have
a copy of the remote firewall's shorewallrc
file in the the directory specified by <directory
name>.<directory name>specifies a directory to be searched for configuration files
before those directories listed in the CONFIG_PATH variable in
shorewall.conf.When -e <directory-name> is
included, only the SHOREWALL_SHELL and VERBOSITY settings from
/etc/shorewall/shorewall.conf are used and
these apply only to the compiler itself. The settings used by the
compiled firewall script are determined by the contents of
<directory name>/shorewall.conf.Beginning with Shorewall 4.5.7.2,
/etc/shorewall/shorewall.conf is not read
if there is a shorewall.conf file in the
specified configuration directory.<path name>specifies the name of the script to be created. If not
given, ${VARDIR}/firewall is assumed (by default, ${VARDIR} is
/var/lib/shorewall/)
The compile command can be used to stage a new compiled strict that
can be activated later usingshorewall restart -fThe /etc/shorewall/capabilities file and the shorecap
programAs mentioned above, the
/etc/shorewall/capabilities file specifies that
kernel/iptables capabilities of the target system. Here is a sample
file:
As you can see, the file contains a simple list of shell variable
assignments — the variables correspond to the capabilities listed by the
shorewall show capabilities command and they appear in
the same order as the output of that command.To aid in creating this file, Shorewall Lite includes a
shorecap program. The program is installed in the
/usr/share/shorewall-lite/
directory and may be run as follows:
The IPTABLES and MODULESDIR options have their usual Shorewall default
values.The capabilities file may then be copied to a
system with Shorewall installed and used when compiling firewall programs
to run on the remote system.The capabilities file may also be creating
using /sbin/shorewall-lite:
shorewall-lite show -f capabilities >
capabilities
Note that unlike the shorecap program, the
show capabilities command shows the kernel's current
capabilities; it does not attempt to load additional kernel
modules.Running compiled programs directlyCompiled firewall programs are complete shell programs that support
the following command line forms:
The options have the same meanings as when they are passed to
/sbin/shorewall itself. The default VERBOSITY level
is the level specified in the shorewall.conf file
used when the program was compiled.
shorewall-docs-xml-5.2.3/ISO-3661.xml 0000664 0000000 0000000 00000040371 13427347317 015536 0 ustar root root
ISO 3661 Country Codes recognized by ShorewallTomEastep2012Thomas 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.IntroductionBeginning with Shorewall 4.5.4, Shorewall allows matching packet
SOURCE and/or DEST IP addresses by their corresponding country. That is
done by specifying a comma-separated list of up to 15 ISO-3661 2-character
Country Codes enclosed in square brackets ('[...]') and prefixed by a
caret ('^'). When a single country code is given, the square brackets can
be omitted.Example - Drop email from the Anonymous Proxy and Satellite Provider
networks./etc/shorewall/rules: #ACTION SOURCE DEST PROTO DPORT
?SECTION NEW
DROP:info net:^[A1,A2] dmz tcp 25
Using this feature requires the GeoIP Match
capability in your iptables and kernel. As of this writing, that
capability requires installing xtables-addons 1.33
or later and creating a
country-code database.The Shorewall compiler uses the geoip country-code database to
determine the valid set of two-character alphanumeric country codes. The
location of that database is currently hard-coded in xtables-addons as
/usr/share/xt_geoip/. Within that directory are two
sub-directories:LE -- contains the little-endian databaseBE -- contains the big-endian databaseTo accomodate both big-endian and little-endian machines as well as
any future ability to install the database at another location, Shorewall
supports a GEOIPDIR option in shorewall.conf (5) and shorewall6.conf (5). The
default value of that option is
/usr/share/xt_geoip/LE.The country codes at the time of this writing are shown in the
following two sections.IPv4 A1 => "Anonymous Proxy" ,
A2 => "Satellite Provider" ,
AD => "Andorra" ,
AE => "United Arab Emirates" ,
AF => "Afghanistan" ,
AG => "Antigua and Barbuda" ,
AI => "Anguilla" ,
AL => "Albania" ,
AM => "Armenia" ,
AN => "Netherlands Antilles" ,
AO => "Angola" ,
AP => "Asia/Pacific Region" ,
AQ => "Antarctica" ,
AR => "Argentina" ,
AS => "American Samoa" ,
AT => "Austria" ,
AU => "Australia" ,
AW => "Aruba" ,
AX => "Aland Islands" ,
AZ => "Azerbaijan" ,
BA => "Bosnia and Herzegovina" ,
BB => "Barbados" ,
BD => "Bangladesh" ,
BE => "Belgium" ,
BF => "Burkina Faso" ,
BG => "Bulgaria" ,
BH => "Bahrain" ,
BI => "Burundi" ,
BJ => "Benin" ,
BM => "Bermuda" ,
BN => "Brunei Darussalam" ,
BO => "Bolivia" ,
BR => "Brazil" ,
BS => "Bahamas" ,
BT => "Bhutan" ,
BV => "Bouvet Island" ,
BW => "Botswana" ,
BY => "Belarus" ,
BZ => "Belize" ,
CA => "Canada" ,
CC => "Cocos (Keeling) Islands" ,
CD => "Congo, The Democratic Republic of the" ,
CF => "Central African Republic" ,
CG => "Congo" ,
CH => "Switzerland" ,
CI => "Cote D'Ivoire" ,
CK => "Cook Islands" ,
CL => "Chile" ,
CM => "Cameroon" ,
CN => "China" ,
CO => "Colombia" ,
CR => "Costa Rica" ,
CU => "Cuba" ,
CV => "Cape Verde" ,
CX => "Christmas Island" ,
CY => "Cyprus" ,
CZ => "Czech Republic" ,
DE => "Germany" ,
DJ => "Djibouti" ,
DK => "Denmark" ,
DM => "Dominica" ,
DO => "Dominican Republic" ,
DZ => "Algeria" ,
EC => "Ecuador" ,
EE => "Estonia" ,
EG => "Egypt" ,
EH => "Western Sahara" ,
ER => "Eritrea" ,
ES => "Spain" ,
ET => "Ethiopia" ,
EU => "Europe" ,
FI => "Finland" ,
FJ => "Fiji" ,
FK => "Falkland Islands (Malvinas)" ,
FM => "Micronesia, Federated States of" ,
FO => "Faroe Islands" ,
FR => "France" ,
GA => "Gabon" ,
GB => "United Kingdom" ,
GD => "Grenada" ,
GE => "Georgia" ,
GF => "French Guiana" ,
GG => "Guernsey" ,
GH => "Ghana" ,
GI => "Gibraltar" ,
GL => "Greenland" ,
GM => "Gambia" ,
GN => "Guinea" ,
GP => "Guadeloupe" ,
GQ => "Equatorial Guinea" ,
GR => "Greece" ,
GS => "South Georgia and the South Sandwich Islands" ,
GT => "Guatemala" ,
GU => "Guam" ,
GW => "Guinea-Bissau" ,
GY => "Guyana" ,
HK => "Hong Kong" ,
HN => "Honduras" ,
HR => "Croatia" ,
HT => "Haiti" ,
HU => "Hungary" ,
ID => "Indonesia" ,
IE => "Ireland" ,
IL => "Israel" ,
IM => "Isle of Man" ,
IN => "India" ,
IO => "British Indian Ocean Territory" ,
IQ => "Iraq" ,
IR => "Iran, Islamic Republic of" ,
IS => "Iceland" ,
IT => "Italy" ,
JE => "Jersey" ,
JM => "Jamaica" ,
JO => "Jordan" ,
JP => "Japan" ,
KE => "Kenya" ,
KG => "Kyrgyzstan" ,
KH => "Cambodia" ,
KI => "Kiribati" ,
KM => "Comoros" ,
KN => "Saint Kitts and Nevis" ,
KP => "Korea, Democratic People's Republic of" ,
KR => "Korea, Republic of" ,
KW => "Kuwait" ,
KY => "Cayman Islands" ,
KZ => "Kazakhstan" ,
LA => "Lao People's Democratic Republic" ,
LB => "Lebanon" ,
LC => "Saint Lucia" ,
LI => "Liechtenstein" ,
LK => "Sri Lanka" ,
LR => "Liberia" ,
LS => "Lesotho" ,
LT => "Lithuania" ,
LU => "Luxembourg" ,
LV => "Latvia" ,
LY => "Libyan Arab Jamahiriya" ,
MA => "Morocco" ,
MC => "Monaco" ,
MD => "Moldova, Republic of" ,
ME => "Montenegro" ,
MG => "Madagascar" ,
MH => "Marshall Islands" ,
MK => "Macedonia" ,
ML => "Mali" ,
MM => "Myanmar" ,
MN => "Mongolia" ,
MO => "Macau" ,
MP => "Northern Mariana Islands" ,
MQ => "Martinique" ,
MR => "Mauritania" ,
MS => "Montserrat" ,
MT => "Malta" ,
MU => "Mauritius" ,
MV => "Maldives" ,
MW => "Malawi" ,
MX => "Mexico" ,
MY => "Malaysia" ,
MZ => "Mozambique" ,
NA => "Namibia" ,
NC => "New Caledonia" ,
NE => "Niger" ,
NF => "Norfolk Island" ,
NG => "Nigeria" ,
NI => "Nicaragua" ,
NL => "Netherlands" ,
NO => "Norway" ,
NP => "Nepal" ,
NR => "Nauru" ,
NU => "Niue" ,
NZ => "New Zealand" ,
OM => "Oman" ,
PA => "Panama" ,
PE => "Peru" ,
PF => "French Polynesia" ,
PG => "Papua New Guinea" ,
PH => "Philippines" ,
PK => "Pakistan" ,
PL => "Poland" ,
PM => "Saint Pierre and Miquelon" ,
PR => "Puerto Rico" ,
PS => "Palestinian Territory, Occupied" ,
PT => "Portugal" ,
PW => "Palau" ,
PY => "Paraguay" ,
QA => "Qatar" ,
RE => "Reunion" ,
RO => "Romania" ,
RS => "Serbia" ,
RU => "Russian Federation" ,
RW => "Rwanda" ,
SA => "Saudi Arabia" ,
SB => "Solomon Islands" ,
SC => "Seychelles" ,
SD => "Sudan" ,
SE => "Sweden" ,
SG => "Singapore" ,
SH => "Saint Helena" ,
SI => "Slovenia" ,
SJ => "Svalbard and Jan Mayen" ,
SK => "Slovakia" ,
SL => "Sierra Leone" ,
SM => "San Marino" ,
SN => "Senegal" ,
SO => "Somalia" ,
SR => "Suriname" ,
ST => "Sao Tome and Principe" ,
SV => "El Salvador" ,
SY => "Syrian Arab Republic" ,
SZ => "Swaziland" ,
TC => "Turks and Caicos Islands" ,
TD => "Chad" ,
TF => "French Southern Territories" ,
TG => "Togo" ,
TH => "Thailand" ,
TJ => "Tajikistan" ,
TK => "Tokelau" ,
TL => "Timor-Leste" ,
TM => "Turkmenistan" ,
TN => "Tunisia" ,
TO => "Tonga" ,
TR => "Turkey" ,
TT => "Trinidad and Tobago" ,
TV => "Tuvalu" ,
TW => "Taiwan" ,
TZ => "Tanzania, United Republic of" ,
UA => "Ukraine" ,
UG => "Uganda" ,
UM => "United States Minor Outlying Islands" ,
US => "United States" ,
UY => "Uruguay" ,
UZ => "Uzbekistan" ,
VA => "Holy See (Vatican City State)" ,
VC => "Saint Vincent and the Grenadines" ,
VE => "Venezuela" ,
VG => "Virgin Islands, British" ,
VI => "Virgin Islands, U.S." ,
VN => "Vietnam" ,
VU => "Vanuatu" ,
WF => "Wallis and Futuna" ,
WS => "Samoa" ,
YE => "Yemen" ,
YT => "Mayotte" ,
ZA => "South Africa" ,
ZM => "Zambia" ,
ZW => "Zimbabwe" ,
IPv6 AD => "Andorra" ,
AE => "United Arab Emirates" ,
AF => "Afghanistan" ,
AL => "Albania" ,
AM => "Armenia" ,
AO => "Angola" ,
AP => "Asia/Pacific Region" ,
AR => "Argentina" ,
AS => "American Samoa" ,
AT => "Austria" ,
AU => "Australia" ,
AW => "Aruba" ,
AZ => "Azerbaijan" ,
BA => "Bosnia and Herzegovina" ,
BD => "Bangladesh" ,
BE => "Belgium" ,
BF => "Burkina Faso" ,
BG => "Bulgaria" ,
BH => "Bahrain" ,
BI => "Burundi" ,
BJ => "Benin" ,
BM => "Bermuda" ,
BN => "Brunei Darussalam" ,
BO => "Bolivia" ,
BR => "Brazil" ,
BS => "Bahamas" ,
BT => "Bhutan" ,
BW => "Botswana" ,
BY => "Belarus" ,
BZ => "Belize" ,
CA => "Canada" ,
CD => "Congo, The Democratic Republic of the" ,
CH => "Switzerland" ,
CI => "Cote D'Ivoire" ,
CK => "Cook Islands" ,
CL => "Chile" ,
CM => "Cameroon" ,
CN => "China" ,
CO => "Colombia" ,
CR => "Costa Rica" ,
CU => "Cuba" ,
CW => "" ,
CY => "Cyprus" ,
CZ => "Czech Republic" ,
DE => "Germany" ,
DJ => "Djibouti" ,
DK => "Denmark" ,
DO => "Dominican Republic" ,
DZ => "Algeria" ,
EC => "Ecuador" ,
EE => "Estonia" ,
EG => "Egypt" ,
ES => "Spain" ,
EU => "Europe" ,
FI => "Finland" ,
FJ => "Fiji" ,
FM => "Micronesia, Federated States of" ,
FO => "Faroe Islands" ,
FR => "France" ,
GB => "United Kingdom" ,
GD => "Grenada" ,
GE => "Georgia" ,
GG => "Guernsey" ,
GH => "Ghana" ,
GI => "Gibraltar" ,
GL => "Greenland" ,
GM => "Gambia" ,
GP => "Guadeloupe" ,
GR => "Greece" ,
GT => "Guatemala" ,
GU => "Guam" ,
GY => "Guyana" ,
HK => "Hong Kong" ,
HN => "Honduras" ,
HR => "Croatia" ,
HT => "Haiti" ,
HU => "Hungary" ,
ID => "Indonesia" ,
IE => "Ireland" ,
IL => "Israel" ,
IM => "Isle of Man" ,
IN => "India" ,
IQ => "Iraq" ,
IR => "Iran, Islamic Republic of" ,
IS => "Iceland" ,
IT => "Italy" ,
JE => "Jersey" ,
JM => "Jamaica" ,
JO => "Jordan" ,
JP => "Japan" ,
KE => "Kenya" ,
KG => "Kyrgyzstan" ,
KH => "Cambodia" ,
KN => "Saint Kitts and Nevis" ,
KR => "Korea, Republic of" ,
KW => "Kuwait" ,
KY => "Cayman Islands" ,
KZ => "Kazakhstan" ,
LA => "Lao People's Democratic Republic" ,
LB => "Lebanon" ,
LI => "Liechtenstein" ,
LK => "Sri Lanka" ,
LS => "Lesotho" ,
LT => "Lithuania" ,
LU => "Luxembourg" ,
LV => "Latvia" ,
LY => "Libyan Arab Jamahiriya" ,
MA => "Morocco" ,
MC => "Monaco" ,
MD => "Moldova, Republic of" ,
ME => "Montenegro" ,
MG => "Madagascar" ,
MH => "Marshall Islands" ,
MK => "Macedonia" ,
ML => "Mali" ,
MM => "Myanmar" ,
MN => "Mongolia" ,
MO => "Macau" ,
MT => "Malta" ,
MU => "Mauritius" ,
MV => "Maldives" ,
MW => "Malawi" ,
MX => "Mexico" ,
MY => "Malaysia" ,
MZ => "Mozambique" ,
NA => "Namibia" ,
NC => "New Caledonia" ,
NF => "Norfolk Island" ,
NG => "Nigeria" ,
NI => "Nicaragua" ,
NL => "Netherlands" ,
NO => "Norway" ,
NP => "Nepal" ,
NR => "Nauru" ,
NU => "Niue" ,
NZ => "New Zealand" ,
OM => "Oman" ,
PA => "Panama" ,
PE => "Peru" ,
PF => "French Polynesia" ,
PG => "Papua New Guinea" ,
PH => "Philippines" ,
PK => "Pakistan" ,
PL => "Poland" ,
PR => "Puerto Rico" ,
PS => "Palestinian Territory" ,
PT => "Portugal" ,
PW => "Palau" ,
PY => "Paraguay" ,
QA => "Qatar" ,
RO => "Romania" ,
RS => "Serbia" ,
RU => "Russian Federation" ,
RW => "Rwanda" ,
SA => "Saudi Arabia" ,
SB => "Solomon Islands" ,
SC => "Seychelles" ,
SD => "Sudan" ,
SE => "Sweden" ,
SG => "Singapore" ,
SI => "Slovenia" ,
SK => "Slovakia" ,
SL => "Sierra Leone" ,
SM => "San Marino" ,
SN => "Senegal" ,
SO => "Somalia" ,
ST => "Sao Tome and Principe" ,
SV => "El Salvador" ,
SY => "Syrian Arab Republic" ,
SZ => "Swaziland" ,
TH => "Thailand" ,
TK => "Tokelau" ,
TN => "Tunisia" ,
TO => "Tonga" ,
TR => "Turkey" ,
TT => "Trinidad and Tobago" ,
TV => "Tuvalu" ,
TW => "Taiwan" ,
TZ => "Tanzania, United Republic of" ,
UA => "Ukraine" ,
UG => "Uganda" ,
US => "United States" ,
UY => "Uruguay" ,
UZ => "Uzbekistan" ,
VA => "Holy See (Vatican City State)" ,
VE => "Venezuela" ,
VI => "Virgin Islands, U.S." ,
VN => "Vietnam" ,
VU => "Vanuatu" ,
WS => "Samoa" ,
YE => "Yemen" ,
ZA => "South Africa" ,
ZM => "Zambia" ,
ZW => "Zimbabwe" ,
shorewall-docs-xml-5.2.3/netmap.xml 0000664 0000000 0000000 00000040763 13427347317 016000 0 ustar root root
Network MappingTomEastep2004-200520072011Thomas 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.Why use Network MappingNetwork Mapping is most often used to resolve IP address conflicts.
Suppose that two organizations, A and B, need to be linked and that both
organizations have allocated the 192.168.1.0/24 subnetwork. There is a
need to connect the two networks so that all systems in A can access the
192.168.1.0/24 network in B and vice versa without any
re-addressing.SolutionShorewall NETMAP support is designed to supply a solution. The basic
situation is as shown in the following diagram.While the link between the two firewalls is shown here as a VPN, it
could be any type of interconnection that allows routing of RFC 1918 traffic.The systems in the top cloud will access the 192.168.1.0/24 subnet
in the lower cloud using addresses in another unused /24. Similarly, the
systems in the bottom cloud will access the 192.168.1.0/24 subnet in the
upper cloud using a second unused /24.In order to apply this solution:You must be running Shorewall 2.0.1 Beta 2 or later.Your kernel must have NETMAP support. 2.6 Kernels have NETMAP
support without patching while 2.4 kernels must be patched using
Patch-O-Matic from netfilter.org.NETMAP support must be enabled in your kernel
(CONFIG_IP_NF_TARGET_NETMAP=m or CONFIG_IP_NF_TARGET_NETMAP=y).Your iptables must have NETMAP support. NETMAP support is
available in iptables 1.2.9 and later.Network mapping is defined using the
/etc/shorewall/netmap file. Columns in this file
are:TYPEMust be DNAT or SNAT.If DNAT, traffic entering INTERFACE and addressed to NET1 has
its destination address rewritten to the corresponding address in
NET2.If SNAT, traffic leaving INTERFACE with a source address in
NET1 has its source address rewritten to the corresponding address
in NET2.NET1Must be expressed in CIDR format (e.g., 192.168.1.0/24).
Beginning with Shorewall 4.4.24, exclusion is
supported.INTERFACEA firewall interface. This interface must have been defined in
/etc/shorewall/interfaces.NET2A second network expressed in CIDR format.NET3 (Optional) -
network-addressAdded in Shorewall 4.4.11. If specified, qualifies INTERFACE.
It specifies a SOURCE network for DNAT rules and a DESTINATON
network for SNAT rules.PROTO (Optional - Added in Shorewall
4.4.23.2) -
protocol-number-or-nameOnly packets specifying this protocol will have their IP
header modified.DPORT (Optional - Added in Shorewall
4.4.23.2) -
port-number-or-name-listDestination Ports. A comma-separated list of Port names (from
services(5)), port numbers or port
ranges; if the protocol is icmp, this column is interpreted as the
destination icmp-type(s). ICMP types may be specified as a numeric
type, a numberic type and code separated by a slash (e.g., 3/4), or
a typename. See http://www.shorewall.net/configuration_file_basics.htm#ICMP.If the protocol is ipp2p,
this column is interpreted as an ipp2p option without the leading
"--" (example bit for bit-torrent).
If no PORT is given, ipp2p is
assumed.An entry in this field requires that the PROTO column specify
icmp (1), tcp (6), udp (17), sctp (132) or udplite (136). Use '-' if
any of the following field is supplied.SPORT (Optional - Added in Shorewall
4.4.23.2) -
port-number-or-name-listSource port(s). If omitted, any source port is acceptable.
Specified as a comma-separated list of port names, port numbers or
port ranges.An entry in this field requires that the PROTO column specify
tcp (6), udp (17), sctp (132) or udplite (136). Use '-' if any of
the following fields is supplied.Referring to the figure above, lets suppose that systems in the top
cloud are going to access the 192.168.1.0/24 network in the bottom cloud
using addresses in 10.10.10.0/24 and that systems in the bottom could will
access 192.168.1.0/24 in the top could using addresses in
10.10.11.0.You must arrange for routing as follows:Traffic from the top cloud to 10.10.10.0/24 must be routed
to eth0 on firewall 1.Firewall 1 must route traffic to 10.10.10.0/24 through
firewall 2.Traffic from the bottom cloud to 10.10.11.0/24 must be
routed to eth0 on firewall 2.Firewall 2 must route traffic to 10.10.11.0/24 through
firewall 1.If you are running Shorewall 4.4.22 or EarlierThe entries in
/etc/shorewall/netmap in
firewall1 would be as follows:#TYPE NET1 INTERFACE NET2
SNAT 192.168.1.0/24 vpn 10.10.11.0/24 #RULE 1A
DNAT 10.10.11.0/24 vpn 192.168.1.0/24 #RULE 1BThe entry in /etc/shorewall/netmap in
firewall2 would be:#TYPE NET1 INTERFACE NET2
DNAT 10.10.10.0/24 vpn 192.168.1.0/24 #RULE 2A
SNAT 192.168.1.0/24 vpn 10.10.10.0/24 #RULE 2B192.168.1.4 in the top cloud connects to 192.168.1.27 in the
bottom cloudIn order to make this connection, the client attempts a
connection to 10.10.10.27. The following table shows how the source
and destination IP addresses are modified as requests are sent and
replies are returned. The RULE column refers to the above
/etc/shorewall/netmap entries and gives the rule
which transforms the source and destination IP addresses to those
shown on the next line. FROMTOSOURCE IP ADDRESSDESTINATION IP ADDRESSRULE192.168.1.4 in upper cloudFirewall 1192.168.1.410.10.10.271AFirewall 1Firewall 210.10.11.410.10.10.272AFirewall 2192.168.1.27 in lower cloud10.10.11.4192.168.1.27192.168.1.27 in the lower cloudFirewall 2192.168.1.2710.10.11.42BFirewall 2Firewall 110.10.10.2710.10.11.41BFirewall 1192.168.1.4 in upper cloud10.10.10.27192.168.1.4See the OpenVPN documentation
for a solution contributed by Nicola Moretti for resolving duplicate
networks in a roadwarrior VPN environment.If you are running Shorewall 4.4.23 or LaterBeginning with Shorewall 4.4.23, you can
bridge two duplicate networks with one router, provided that your kernel
and iptables include Rawpost Table Support. That
support is used to implement Stateless NAT which allows for performing
DNAT in the rawpost table POSTROUTING and OUTPUT chains and for
performing SNAT in the raw table PREROUTING chain. Using this support,
only firewall1 requires /etc/shorewall/netmap. Two
additional entries are added.#TYPE NET1 INTERFACE NET2
SNAT 192.168.1.0/24 vpn 10.10.11.0/24
DNAT 10.10.11.0/24 vpn 192.168.1.0/24
SNAT:P 192.168.1.0/24 vpn 10.10.10.0/24
DNAT:T 10.10.10.0/24 vpn 192.168.1.0/24The last two entries define Stateless NAT
by specifying a chain designator (:P for PREROUTING and :T for
POSTROUTING respectively). See shorewall-netmap (5) for
details.IPv6Beginning with Shorewall6 4.4.24, IPv6 support for Netmap is
included. This provides a way to use private IPv6 addresses internally and
still have access to the IPv6 internet.IPv6 netmap is stateless which means that
there are no Netfilter helpers for applications that need them. As a
consequence, applications that require a helper (FTP, IRC, etc.) may
experience issues.For IPv6, the chain designator (:P for PREROUTING or :T for
POSTROUTING) is required in the TYPE column. Normally SNAT rules are
placed in the POSTROUTING chain while DNAT rules are placed in
PREROUTING.To use IPv6 Netmap, your kernel and iptables must include
Rawpost Table Support.IPv6 Netmap has been verified at shorewall.net using the
configuration shown below.IPv6 support is supplied from Hurricane Electric; the IPv6 address
block is 2001:470:b:227::/64.Because of the limitations of IPv6 NETMAP (no Netfilter helpers),
the servers in the DMZ have public addresses in the block
2001:470:b:227::/112. The local LAN uses the private network
fd00:470:b:227::/64 with the hosts autoconfigured using radvd. This block
is allocated from the range (fc00::/7) reserved forUnique Local
Addresses.The /etc/shorewall6/netmap file is as follows:#TYPE NET1 INTERFACE NET2 NET3 PROTO DEST SOURCE
# PORT(S) PORT(S)
SNAT:T fd00:470:b:227::/64 HE_IF 2001:470:b:227::/64
DNAT:P 2001:470:b:227::/64!2001:470:b:227::/112\
HE_IF fd00:470:b:227::/64
HE_IF is the logical name for interface sit1. On output, the private
address block is mapped to the public block. Because autoconfiguration is
used, none of the local addresses falls into the range
fd00:470:b:227::/112. That range can therefore be excluded from
DNAT.While the site local network that was used is very similar to the
public network (only the first word is different), that isn't a
requirement. We could have just as well used
fd00:bad:dead:beef::/64The MacBook Pro running OS X Lion refused to autoconfigure when
radvd advertised a site-local network
(fec0:470:b:227/64) but worked fine with the unique-local network
(fd00:470:b:227::/64). Note that site-local addresses were deprecated in
RFC3879.This whole scheme isn't quite as useful as it might appear. Many
IPv6-enabled applications (web browsers, for example) are smart enough
to recognize unique local addresses and will only use IPv6 to
communicate with other such local addresses.
shorewall-docs-xml-5.2.3/IPSEC-2.6.xml 0000664 0000000 0000000 00000075317 13427347317 015665 0 ustar root root
IPsecTomEastepRobertoSanchez20042005200620092016Thomas M. Eastep2007Roberto C. SanchezPermission 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 does not configure IPsec for
you -- it rather configures netfilter to accommodate your IPsec
configuration.The information in this article is only applicable if you plan to
have IPsec end-points on the same system where Shorewall is used.While this article shows configuration of
IPsec using ipsec-tools, Shorewall
configuration is exactly the same when using OpenSwanor any of the other Swan derivatives.When running a Linux kernel prior to 2.6.20, the Netfilter+IPsec and
policy match support are broken when used with a bridge device. The
problem was corrected in Kernel 2.6.20 as a result of the removal of
deferred FORWARD/OUTPUT processing of traffic destined for a bridge. See
the "Shorewall-perl and
Bridged Firewalls" article.Shorwall and Kernel 2.6 IPsecThis is not a HOWTO for Kernel 2.6
IPsec -- for that, please see http://www.ipsec-howto.org/.The 2.6 Linux Kernel introduced new facilities for defining
encrypted communication between hosts in a network. The network
administrator defines a set of Security Policies
which are stored in the kernel as a Security Policy
Database (SPD). Security policies determine which traffic is
subject to encryption. Security Associations are
created between pairs of hosts in the network (one SA for traffic in each
direction); these SAs define how traffic is to be encrypted. Outgoing
traffic that is to be encrypted according to the contents of the SPD
requires an appropriate SA to exist. SAs may be created manually using
setkey(8) but most often, they are created by a
cooperative process involving the ISAKMP protocol and a daemon included in
your IPsec package (StrongSwan, LibreSwan, ipsec-tools/Racoon, etc.) .
Incoming traffic is verified against the SPD to ensure that no unencrypted
traffic is accepted in violation of the administrator's policies.There are three ways in which IPsec traffic can interact with
Shorewall policies and rules:Traffic that is encrypted on the firewall system. The traffic
passes through Netfilter twice -- first as unencrypted then
encrypted.Traffic that is decrypted on the firewall system. The traffic
passes through Netfilter twice -- first as encrypted then as
unencrypted.Encrypted traffic that is passed through the firewall system.
The traffic passes through Netfilter once.In cases 1 and 2, the encrypted traffic is handled by entries in
/etc/shorewall/tunnels (don't be mislead by the name
of the file -- transport mode encrypted traffic is
also handled by entries in that file). The unencrypted traffic is handled
by normal rules and policies.Under the 2.4 Linux Kernel, the association of unencrypted traffic
and zones was made easy by the presence of IPsec pseudo-interfaces with
names of the form ipsecN (e.g.
ipsec0). Outgoing unencrypted
traffic (case 1.) was sent through an ipsecN device while incoming unencrypted
traffic (case 2) arrived from an ipsecN device. The 2.6 kernel-based
implementation does away with these pseudo-interfaces. Outgoing traffic
that is going to be encrypted and incoming traffic that has been decrypted
must be matched against policies in the SPD and/or the appropriate
SA.Shorewall provides support for policy matching in three ways:In /etc/shorewall/masq
(/etc/shorewall/snat when running Shorewall
5.0.14 or later), traffic that will later be encrypted is exempted
from MASQUERADE/SNAT using existing entries. If you want to
MASQUERADE/SNAT outgoing traffic that will later be encrypted, you
must include the appropriate indication in the IPSEC column in that
file.The/etc/shorewall/zones
file allows you to associate zones with traffic that will be encrypted
or that has been decrypted.A new option (ipsec) has been
provided for entries in /etc/shorewall/hosts.
When an entry has this option specified, traffic to/from the hosts
described in the entry is assumed to be encrypted.In summary, Shorewall provides the facilities to replace the use of
IPsec pseudo-interfaces in zone and MASQUERADE/SNAT definition.There are two cases to consider:Encrypted communication is used to/from all hosts in a
zone.The value ipsec is placed in
the TYPE column of the /etc/shorewall/zones entry
for the zone.By default, encrypted communication is not used to communicate
with the hosts in a zone.The value ipv4 is placed in the
TYPE column of the /etc/shorewall/zones entry for
the zone and the new ipsec option is
specified in /etc/shorewall/hosts for any hosts
requiring secure communication.For simple zones such as are shown in the following examples, the
two techniques are equivalent and are used interchangeably.It is redundant to have ipsec in
the TYPE column of the /etc/shorewall/zones entry
for a zone and to also have the ipsec
option in /etc/shorewall/hosts entries for that
zone.Finally, the OPTIONS, IN OPTIONS and OUT OPTIONS columns in
/etc/shorewall/zones can be used to match the zone to a particular (set
of) SA(s) used to encrypt and decrypt traffic to/from the zone and the
security policies that select which traffic to encrypt/decrypt.This article provides guidance regarding configuring Shorewall to
use with IPsec. For configuring IPsec itself, consult your IPsec
product's documentation.IPsec Gateway on the Firewall SystemSuppose that we have the following situation:We want systems in the 192.168.1.0/24 sub-network to be able to
communicate with systems in the 10.0.0.0/8 network. We assume that on both
systems A and B, eth0 is the Internet interface.To make this work, we need to do two things:Open the firewall so that the IPsec tunnel can be established
(allow the ESP protocol and UDP Port 500).Allow traffic through the tunnel.Opening the firewall for the IPsec tunnel is accomplished by adding
an entry to the /etc/shorewall/tunnels file.In /etc/shorewall/tunnels on system A, we need
the following
/etc/shorewall/tunnels —
System A:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsec net 134.28.54.2/etc/shorewall/tunnels —
System B:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsec net 206.162.148.9
If either of the endpoints is behind a NAT gateway then the
tunnels file entry on the other
endpoint should specify a tunnel type of ipsecnat rather than ipsec and
the GATEWAY address should specify the external address of the NAT
gateway.You need to define a zone for the remote subnet or include it in
your local zone. In this example, we'll assume that you have created a
zone called vpn to represent the remote subnet.
/etc/shorewall/zones —
Systems A and B:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
net ipv4
vpn ipv4
Remember the assumption that both systems A and B have eth0 as their
Internet interface.You must define the vpn zone using the
/etc/shorewall/hosts file. The hosts file entries
below assume that you want the remote gateway to be part of the vpn zone —
If you don't wish the remote gateway included, simply omit its IP address
from the HOSTS column.
/etc/shorewall/hosts — System A#ZONE HOSTS OPTIONS
vpn eth0:10.0.0.0/8,134.28.54.2 ipsec/etc/shorewall/hosts — System B#ZONE HOSTS OPTIONS
vpn eth0:192.168.1.0/24,206.162.148.9 ipsec
If you want to keep things simple, you can simply not restrict the
set of addresses in the ipsec zones:
#ZONE HOSTS OPTIONS
vpn eth0:0.0.0.0/0 ipsec
Assuming that you want to give each local network free access to the
remote network and vice versa, you would need the following
/etc/shorewall/policy entries on each system:
#SOURCE DEST POLICY LEVEL BURST:LIMIT
loc vpn ACCEPT
vpn loc ACCEPT
If you need access from each firewall to hosts in the other network,
then you could add:
#SOURCE DEST POLICY LEVEL BURST:LIMIT
$FW vpn ACCEPT
If you need access between the firewall's, you should describe the
access in your /etc/shorewall/rules file. For example, to allow SSH access
from System B, add this rule on system A:
#ACTION SOURCE DEST PROTO POLICY
ACCEPT vpn:134.28.54.2 $FW
If you have hosts that access the Internet through an IPsec
tunnel, then it is a good idea to set the MSS value for traffic from
those hosts explicitly in the /etc/shorewall/zones
file. For example, if hosts in the vpn
zone access the Internet through an ESP tunnel then the following entry
would be appropriate:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
vpn ipsec mode=tunnel mss=1400You should also set FASTACCEPT=No in shorewall.conf to ensure that
both the SYN and SYN,ACK packets have their MSS field adjusted.Note that CLAMPMSS=Yes in shorewall.conf
isn't effective with the 2.6 native IPsec implementation because there
is no separate IPsec device with a lower mtu as there was under the 2.4
and earlier kernels.Mobile System (Road Warrior)Suppose that you have a laptop system (B) that you take with you
when you travel and you want to be able to establish a secure connection
back to your local network.Road Warrior VPNYou need to define a zone for the laptop or include it in your
local zone. In this example, we'll assume that you have created a zone
called vpn to represent the remote host.
/etc/shorewall/zones — System A#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
net ipv4
vpn ipsec
loc ipv4
In this instance, the mobile system (B) has IP address 134.28.54.2
but that cannot be determined in advance. In the
/etc/shorewall/tunnels file on system A, the
following entry should be made:
#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsec net 0.0.0.0/0 vpn
the GATEWAY_ZONE column contains the name of the zone
corresponding to peer subnetworks. This indicates that the gateway
system itself comprises the peer subnetwork; in other words, the
remote gateway is a standalone system.The VPN zone is defined using the /etc/shorewall/hosts
file:
/etc/shorewall/hosts — System A:#ZONE HOSTS OPTIONS
vpn eth0:0.0.0.0/0
You will need to configure your through the tunnel
policy as shown under the first example above.On the laptop:
/etc/shorewall/zones - System B:#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
vpn ipsec
net ipv4
loc ipv4/etc/shorewall/tunnels - System B:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsec net 206.162.148.9 vpn/etc/shorewall/hosts - System B:#ZONE HOSTS OPTIONS
vpn eth0:0.0.0.0/0
Mobile System (Road Warrior) with Layer 2 Tunneling Protocol
(L2TP)This section is based on the previous section. Please make sure that
you read it thoroughly and understand it. The setup described in this
section is more complex because you are including an additional layer of
tunneling. Again, make sure that you have read the previous section and it
is highly recommended to have the IPsec-only configuration working
first.Additionally, this section assumes that you are running IPsec,
xl2tpd and pppd on the same system that is running shorewall. However,
configuration of these additional services is beyond the scope of this
document.Getting layer 2 tunneling to work is an endeavour unto itself.
However, if you succeed it can be very convenient. Reasons why you might
want configure layer 2 tunneling protocol (L2TP):You want to give your road warrior an address that is in the
same segment as the other hosts on your network.Your road warriors are using a legacy operating system (such as
MS Windows or Mac OS X) and you do not want them to have to install
third party software in order to connect to the VPN (both MS Windows
and Mac OS X include VPN clients which natively support L2TP over
IPsec, but not plain IPsec).You like a challenge.Since the target for a VPN including L2TP will (almost) never be a
road warrior running Linux, I will not include the client side of the
configuration.The first thing that needs to be done is to create a new zone called
l2tp to represent the tunneled layer 2 traffic.
/etc/shorewall/zones — System A#ZONE TYPE OPTIONS IN_OPTIONS OUT_OPTIONS
et ipv4
vpn ipsec
l2tp ipv4
loc ipv4
Since the L2TP will require the use of pppd, you will end up with
one or more ppp interfaces (each representing an individual road warrior
connection) for which you will need to account. This can be done by
modifying the interfaces file. (Modify with additional options as
needed.)
/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
net eth0 detect routefilter
loc eth1 192.168.1.255
l2tp ppp+ -
The next thing that must be done is to adjust the policy so that the
traffic can go where it needs to go.First, you need to decide if you want for hosts in your local zone
to be able to connect to your road warriors. You may or may not want to
allow this. For example, one reason you might want to allow this is so
that your support personnel can use ssh, VNC or remote desktop to fix a
problem on the road warrior's laptop.Second, you need to decide if you want the road warrior to have
access to hosts on the local network. You generally want to allow this.
For example, if you have DNS servers on your local network that you want
the road warrior to use. Or perhaps the road warrior needs to mount NFS
shares or needs to access intranet sites which are not visible from the
public Internet.Finally, you need to decide if you want the road warriors to be able
to access the public Internet. You probably want to do this, unless you
are trying to create a situation where when the road warrior connects to
the VPN, it is no longer possible to send traffic from the road warrior's
machine to the public Internet. Please note that this not really a strong
security measure. The road warrior could trivially modify the routing
table on the remote machine to have only traffic destined for systems on
the VPN local network go through the secure channel. The rest of the
traffic would simply travel over an Ethernet or wireless interface
directly to the public Internet. In fact, this latter situation is
dangerous, as a simple mistake could easily create a situation where the
road warrior's machine is acting as a router between your local network
and the public Internet, which you certainly do not want to happen. In
short, it is best to allow the road warrior to connect to the public
Internet by default.
/etc/shorewall/policy:#SOURCE DEST POLICY LOGLEVEL LIMIT
$FW all ACCEPT
loc net ACCEPT
loc l2tp ACCEPT # Allows local machines to connect to road warriors
l2tp loc ACCEPT # Allows road warriors to connect to local machines
l2tp net ACCEPT # Allows road warriors to connect to the Internet
net all DROP info
# The FOLLOWING POLICY MUST BE LAST
all all REJECT info
The final step is to modify your rules file. There are three
important components. First, you must allow the l2tp traffic to reach the
xl2tpd process running on the firewall machine. Second, you must add rules
to open up ports on the firewall to the road warrior for services which
are running on the firewall. For example, if you are running a webserver
on the firewall that must be accessible to road warriors. The reason for
the second step is that the policy does not by default allow unrestricted
access to the firewall itself. Finally, you should protect an exploit
where an attacker can exploit your LT2P server due to a hole in the way
that L2TP interacts with UDP connection tracking.
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT SPORT
?SECTION ESTABLISHED
# Prevent IPsec bypass by hosts behind a NAT gateway
L2TP(REJECT) net $FW
REJECT $FW net udp - 1701
?SECTION NEW
# l2tp over the IPsec VPN
ACCEPT vpn $FW udp 1701
# webserver that can only be accessed internally
HTTP(ACCEPT) loc $FW
HTTP(ACCEPT) l2tp $FW
HTTPS(ACCEPT) loc $FW
HTTPS(ACCEPT) l2tp $FW
Transport ModeIn today's wireless world, it is often the case that individual
hosts in a network need to establish secure connections with the other
hosts in that network. In that case, IPsec transport mode is an
appropriate solution.Shorewall configuration goes as follows:
/etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
net eth0 routefilter,dhcp,tcpflags/etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY
# ZONE
ipsec net 192.168.20.0/24 loc/etc/shorewall/zones:#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
loc ipsec mode=transport
net ipv4/etc/shorewall/hosts:#ZONE HOST(S) OPTIONS
loc eth0:192.168.20.0/24It is worth noting that although loc is a
sub-zone of net, because loc
is an IPsec-only zone it does not need to be defined before
net in
/etc/shorewall/zones./etc/shorewall/policy:#SOURCE DEST POLICY LOGLEVEL LIMIT
$FW all ACCEPT
loc $FW ACCEPT
net loc NONE
loc net NONE
net all DROP info
# The FOLLOWING POLICY MUST BE LAST
all all REJECT infoSince there are no cases where net<->loc traffic should
occur, NONE policies are used.
IPCOMPIf your IPsec tunnel or transport mode connection fails to work with
Shorewall started and you see log messages like the following when you try
to use the connection, the problem is that ip compression is being
used.Feb 18 23:43:52 vpngw kernel: Shorewall:vpn2fw:REJECT:IN=eth2 OUT= MAC=00:e0:81:32:b3:5e:00:18:de:12:e5:15:08:00
SRC=172.29.59.58 DST=172.29.59.254 LEN=85 TOS=0x00 PREC=0x00 TTL=64 ID=25600 DF PROTO=4The solution is to
add an IPCOMP tunnel to /etc/shorewall/tunnels as follows:#TYPE ZONE GATEWAY GATEWAY
# ZONE
ipip vpn 0.0.0.0/0The
above assumes that the name of your IPsec vpn zone is
vpn.Note that this protocol 4 (IPIP) traffic appears to originate in
the vpn zone, but it's source IP address is that of the remote gateway.
As a consequence, that address must be included in the definition of the
remote zone. If you haven't done that, the traffic will be dropped in
the INPUT chain.Using SNAT to Force Traffic over an IPsec TunnelCases can arise where you need to use an IPsec tunnel to access a
remote network, but you have no control over the associated security
polices. In such cases, the resulting tunnel is accessible from your
firewall but not from your local networks.Let's take an example:Remote gateway 192.0.2.26Remote subnet 172.22.4.0/24Your public IP address is 192.0.2.199Your Internet-facing interface is eth0Your local network is 192.168.219.0/24You want to access 172.22.4.0/24 from 192.168.219.0/24The IPsec tunnel is configured between 172.22.4.0/24 and
192.0.2.199You need to configure as follows./etc/shorewall/zones:#ZONE TYPE OPTIONS
...
vpn ip # Note that the zone cannot be declared as type ipsec
.../etc/shorewall/interfaces:#ZONE INTERFACE OPTIONS
net eth0 nets=(!172.22.4.0/24),... # You must exclude the remote network from the net zone/etc/shorewall/hosts:#ZONE HOSTS OPTIONS
vpn eth0:172.22.4.0/24 mss=1380,destonly
vpn eth0:0.0.0.0/0 mss=1380,ipsec/etc/shorewall/snat:SNAT(192.0.2.199) 192.168.219.0/24 eth0:172.22.4.0/24/etc/shorewall/tunnels:#TYPE ZONE GATEWAY GATEWAY_ZONE
ipsec net 192.0.2.26 vpn
shorewall-docs-xml-5.2.3/Shorewall-5.xml 0000664 0000000 0000000 00000052532 13427347317 016613 0 ustar root root
Shorewall 5TomEastep2015201620172018Thomas 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.IntroductionThere are currently three principle groups of changes that
distinguish Shorewall 5 from Shorewall 4:Cruft Removal - over the years, as new ways to accomplish
various tasks are added to Shorewall, support for the old way of doing
things has generally been retained but deprecated. Shorewall 5 drops
support for those deprecated features.Changes to CLI commands - In order to make command names more
accurately reflect what the associated commands do, a number of
commands have been renamed or the function that they perform has been
changed.CLI unification - Beginning with Shorewall 5.1.0, there is a
single CLI program (/sbin/shorewall or
/usr/sbin/shorewall depending on your
distribution).Each of these groups is described in more detail in the sections
that follow.Cruft RemovalRemoval of superseded features makes the code cleaner and easier to
extend while also reducing compilation and execution time. The following
subsections detail the features that are no longer supported in Shorewall
5.Scripts Compiled with Shorewall 4.4.7 or EarlierShorewall 5 cannot correctly run scripts compiled with Shorewall
4.4.7 or earlier releases. Such scripts must be recompiled with 4.4.8 or
later prior to upgrading to Shorewall 5.WorkaroundsOver the years, a number of workarounds have been added to
Shorewall to work around defects in other products. In current
distributions, those defects have been corrected, and in 4.6.11, a
WORKAROUNDS configuration option was added to disable those workarounds.
In Shorewall 5, the WORKAROUNDS setting is still available in the
shorewall[6].conf files but:Its default setting has been changed to No.All workarounds for old distributions have been
eliminated.If there is a need to add new workarounds in the future, those
workarounds will be enabled by WORKAROUNDS=Yes.Removal of Configuration OptionsA number of configuration options have been eliminated in
Shorewall 5. The following options have been eliminated and the
functionality that they enabled is been removed:EXPORTPARAMSIPSECFILELEGACY_FASTSTARTCHAIN_SCRIPTS (Removed in Shorewall 5.1).MODULE_SUFFIX (Removed in Shorewall 5.1.7). Shorewall can now
locate modules independent of their suffix (extension).INLINE_MATCHES (Removed in Shorewall 5.2). Inline matches are
now separated from column-oriented input by two adjacent semicolons
(";;").MAPOLDACTIONS (Removed in Shorewall 5.2). A compilation warning is issued when any of these options are
encountered in the .conf file, and the shorewall[6]
update command will remove them from the configuration
file.These options have been eliminated because they have been
superseded by newer options.LOGRATE and LOGBURST (superseded by LOGLIMIT)WIDE_TC_MARKS (superseded by TC_BITS)HIGH_ROUTE_MARKS (superseded by PROVIDER_OFFSET)BLACKLISTNEWONLY (superseded by BLACKLIST)A fatal compilation error is emitted if any of these options are
present in the .conf file, and the shorewall[6]
update command will replace these options with equivalent
setting of the options that supersede them.Obsolete Configuration FilesSupport has been removed for the 'blacklist', 'tcrules',
'routestopped', 'notrack', 'tos' and 'masq' files.The update command is available to convert the
'tcrules' and 'tos' files to the equivalent 'mangle' file, to convert
the 'blacklist' file into an equivalent 'blrules' file, and to convert
the 'masq' file to the equivalent 'snat' file.As in Shorewall 4.6.12, the update command
converts the 'routestopped' file into the equivalent 'stoppedrules' file
and converts a 'notrack' file to the equivalent 'conntrack' file.Note that in Shorewall 5.2, the update command Macro and Action FormatsOriginally, macro and action files had formats that were different
from that of the rules file,Format-1 action files had the following columns:TARGETSOURCEDESTPROTODEST PORT(S)SOURCE PORT(S)RATEUSER/GROUPMARKFormat-1 macro files were similar but did not support the MARK
column.Format-2 macro and action files have these columns:TARGETSOURCEDESTPROTODPORTSPORTORIGDESTRATEUSER/GROUPMARKCONNLIMITTIMEHEADERS (Only valid for IPv6)SWITCHHELPERNotice that the first five columns of both sets are the same
(although the port-valued column names have changed, the contents are
the same).In Shorewall 5, support for format-1 macros and actions has been
dropped and all macros and actions will be processed as if ?FORMAT 2
were included before the first entry. Given that the vast majority of
actions and macros only use the first five columns, this change will be
of no concern to most users, but will cause compilation errors if
columns beyold the fifth one are populated.COMMENT, FORMAT and SECTION LinesCOMMENT, FORMAT and SECTION Lines now require the leading question
mark ("?"). In earlier releases, the question mark was optional. The
shorewall[6] update -D command in Shorewall 4.6 will
insert the question marks for you.CLI Command ChangesA number of commands have been renamed and/or now perform a
different function.restartThe restart command now does a true restart and
is equivalent to a stop followed by a
start.loadThe function performed by the Shorewall-4 load
command is now performed by the remote-start
command.reloadIn Shorewall 5, the reload command now performs
the same function as the restart command did in
Shorewall 4. The action taken by the Shorewall-4
reload command is now performed by the
remote-restart command.For those that can't get used to the idea of using
reload in place of restart, a
RESTART option has been added to shorewall[6].conf. The option defaults
to 'restart' but if set to 'reload', then the restart
command does what it did in earlier releases.Beginning with Shorewall 5.0.1 and Shorewall 4.6.13.2, the
update command will set RESTART=reload to maintain compatibility with
earlier releases. Shorewall 5.0.0 created the setting
LEGACY_RESTART=No which was equivalent to RESTART=restart. Under
Shorewall 5.0.1 and later, update will convert LEGACY_RESTART to the
equivalent RESTART setting.refreshGiven the availability of ipset-based blacklisting, the
refresh command was eliminated in Shorewall
5.2.Some users may have been using refresh as a
lightweight form of reload. The most common of these
uses seem to be for reloading traffic shaping after an interface has
gone down and come back up. The best way to handle this situation under
5.2 is to make the interface 'optional' in your
/etc/shorewall[6]/interfaces file, then either:Install Shorewall-init and enable IFUPDOWN; orUse the reenable command when the interface
comes back up in place of the refresh
command.CLI UnificationPrior to Shorewall 5.1, there were four separate CLI
programs:/sbin/shorewall or
/usr/sbin/shorewall depending on your
distribution. Packaged with Shorewall and used to control
Shorewall./sbin/shorewall6 or
/usr/sbin/shorewall6 depending on your
distribution. Packaged with Shorewall6 and used to control
Shorewall6./sbin/shorewall-lite or
/usr/sbin/shorewall-lite depending on your
distribution. Packaged with Shorewall-lite and used to control
Shorewall-lite./sbin/shorewall6-lite or
/usr/sbin/shorewall6-lite depending on your
distribution. Packaged with Shorewall6-lite and used to control
Shorewall6-lite.Each of these programs had their own (largely duplicated)
manpage.Beginning with Shorewall 5.1, there is a single CLI program
(/sbin/shorewall or
/usr/sbin/shorewall) packaged with Shorewall-core.
The Shorewall6, Shorewall-lite and Shorewall6-lite packages create a
symbolic link to that program; the links are named shorewall6,
shorewall-lite and shorewall6-lite respectively. These symbolic links are
for backward compatibility only; all four products can be managed using
the single CLI program itself. The manpages shorewall6(8),
shorewall-lite(8) and shorewall6-lite(8) are skeletal and refer the reader
to shorewall(8).Upgrading to Shorewall 5For detailed upgrade information, please consult the 'Migration
Issues' section of the release notes for the version that you are
upgrading to.It is strongly recommended that you first upgrade your
installation to a 4.6 release that supports the option
to the update command; 4.6.13.2 or later is
preferred.Once you are on that release, execute the shorewall update
-A command (and shorewall6 update -A if you
also have Shorewall6).Finally, add ?FORMAT 2 to each of your macro and action files and be
sure that the check command does not produce errors -- if it does, you can
shuffle the columns around to make them work on both Shorewall 4 and
Shorewall 5.These steps can also be taken after you upgrade, but your firewall
likely won't start or work correctly until you do.The update command in Shorewall 5 has many fewer
options. The , ,
, and options
have been removed -- the updates triggered by those options are now
performed unconditionally. The and options have been retained - both enable checking for issues that
could result if INLINE_MATCHES were to be set to Yes. The -i option was
removed in Shorewall 5.2, given that the INLINE_MATCHES option was also
removed.CHAIN_SCRIPTS RemovalPrior to the availability of ?[BEGIN] PERL .... ?END PERL, the
only way to create Perl code to insert rules into a chain was to use a
per-Chain script with the same name as the chain. The most common use of
these scripts was with Actions where an action A would have an empty
action.A file and then a file named A that contained Perl code. This was
a hack, at best, and has been deprecated since embedded Perl has been
available in action files.In Shorewall 5.1, the compiler notices that action.A is empty and
looks for a file named A on the CONFIG_PATH. If that file is found, the
compiler raises a fatal error: ERROR: File action.A is empty and file A exists - the two must be combined as described in the Migration Considerations section of the Shorewall release notesTo resolve this issue, one of two approaches can be taken
depending on what the script A does.If script A is simply inserting rules with ip[6]tables matches
and/or targets that Shorewall doesn't directly support, they can
probably be coded in the action.A file using the IP[6]TABLES action
and/or inline matches. For example, the following script
DNSDDOSuse Shorewall::Chains;
add_rule $chainref, q(-m string --algo bm --from 30 --to 31 --hex-string "|010000010000000000000000020001|" -j DROP);
add_rule $chainref, q(-m string --algo bm --from 30 --to 31 --hex-string "|000000010000000000000000020001|" -j DROP);
add_rule $chainref, q(-j ACCEPT);
1;can be coded in action.DNSDDOS as:DROP - - ;; -m string --algo bm --from 30 --to 31 --hex-string "|010000010000000000000000020001|"
DROP - - ;; -m string --algo bm --from 30 --to 31 --hex-string "|000000010000000000000000020001|"
ACCEPT - -The other approach is to simply convert A into embedded Perl
in action.A. Consider this SSHKnock
script:use Shorewall::Chains;
if ( $level ) {
log_rule_limit( $level,
$chainref,
'SSHKnock',
'ACCEPT',
'',
$tag,
'add',
'-p tcp --dport 22 -m recent --rcheck --name SSH ' );
log_rule_limit( $level,
$chainref,
'SSHKnock',
'DROP',
'',
$tag,
'add',
'-p tcp --dport ! 22 ' );
}
add_rule( $chainref, '-p tcp --dport 22 -m recent --rcheck --seconds 60 --name SSH -j ACCEPT' );
add_rule( $chainref, '-p tcp --dport 632 -m recent --name SSH --remove -j DROP' );
add_rule( $chainref, '-p tcp --dport 633 -m recent --name SSH --set -j DROP' );
add_rule( $chainref, '-p tcp --dport 634 -m recent --name SSH --remove -j DROP' );
1;Because this script uses the implicit $level and $tag
variables, it must remain in Perl. This mostly involves simply
moving the SSHKnock script into
action.SSHKnock, but requires some additional
code in action.SSHKnock as shown in bold font below:?begin perluse Shorewall::Config;
use Shorewall::Chains;
my $chainref = get_action_chain;
my ( $level, $tag ) = get_action_logging;
if ( $level ) {
log_rule_limit( $level,
$chainref,
'SSHKnock',
'ACCEPT',
'',
$tag,
'add',
'-p tcp --dport 22 -m recent --rcheck --name SSH ' );
log_rule_limit( $level,
$chainref,
'SSHKnock',
'DROP',
'',
$tag,
'add',
'-p tcp --dport ! 22 ' );
}
add_rule( $chainref, '-p tcp --dport 22 -m recent --rcheck --seconds 60 --name SSH -j ACCEPT' );
add_rule( $chainref, '-p tcp --dport 632 -m recent --name SSH --remove -j DROP' );
add_rule( $chainref, '-p tcp --dport 633 -m recent --name SSH --set -j DROP' );
add_rule( $chainref, '-p tcp --dport 634 -m recent --name SSH --remove -j DROP' );
1;
?end perl
shorewall-docs-xml-5.2.3/useful_links.xml 0000664 0000000 0000000 00000013303 13427347317 017205 0 ustar root root
Useful Links2003-20132019Thomas 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.NIST Guide on Firewalls and Firewall
Policy - http://csrc.nist.gov/publications/nistpubs/800-41-Rev1/sp800-41-rev1.pdfPPPPPPPS ( or, Paul's Principles for Practical Provision of
Packet Processing with Shorewall ) http://linuxman.wikispaces.com/PPPPPPSNetfilter Site: http://www.netfilter.org/Linux Advanced Routing and Traffic Control
Howto: http://lartc.org/Clustering Shorewall: http://linuxman.wikispaces.com/Clustering+ShorewallIproute Downloads: https://www.kernel.org/pub/linux/utils/net/iproute2/LEAF Site: http://leaf.sourceforge.netBering uClibc LEAF Distribution: http://leaf.sourceforge.net/bering-uclibc/Iptables Tutorial: https://www.frozentux.net/documents/iptables-tutorial/Debian apt-get sources for Shorewall: http://people.connexer.com/~roberto/debian/About the Shorewall Author: http://www.shorewall.net/shoreline.htmTom's 2005 LinuxFest NW Presentation - "Shorewall and Native
IPsec" : http://www.shorewall.net/LinuxFest2005.pdfTom's 2006 LinuxFest NW Presentation - "OpenVPN" : http://www.shorewall.net/LinuxFest2006.pdfTom's 2007 LinuxFest NW Presentation - "Xen and the Art of
Consolidation" : http://www.shorewall.net/Linuxfest-2007.pdfTom's 2008 LinuxFest NW Presentation - "Kernel-mode Virtual
Machine (KVM)" : http://www.shorewall.net/Linuxfest-2008.pdfTom's 2009 LinuxFest NW Presentation - "Introduction to IPv6"
: http://www.shorewall.net/LinuxFestNW-2009.pdfTom's 2010 LinuxFest NW Presentation - "Managing Multiple
Internet Connections with Shorewall" : http://www.shorewall.net/LinuxFestNW-2010.pdfTom's 2011 LinuxFest NW Presentation - "LXC - Linux
Containers" : http://www.shorewall.net/LinuxFest2011.pdfTom's 2013 SeaGL Presentation - "AN INTRODUCTION TO LINUX
POLICY ROUTING" : http://www.shorewall.net/SeaGL2013.pdf
shorewall-docs-xml-5.2.3/Dynamic.xml 0000664 0000000 0000000 00000015220 13427347317 016066 0 ustar root root
Dynamic ZonesTomEastep20092013Thomas 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.OverviewThere is sometimes a need to be able to define a zone whose members
are unknown at compile-time. For example, you may wish to require
authentication of internal users before allowing them access to the
internet. When a user is authenticated, the user's IP address is added to
the zone of users permitted web access.Shorewall provides basic support for defining such zones. This
support is based on ipset. Most current
distributions have ipset, but you may need to install the xtables-addons
package.Dynamic ZonesPrior to Shorewall 4.5.9, when multiple records for a zone appear in
/etc/shorewall/hosts, Shorewall would create a
separate ipset for each interface. This meant that an add or delete
command was required for each of the interface, when the address involved
was reachable via multiple interfaces.Beginning with Shoreawll 4.5.9, it is possible to have a single
ipset shared among all interfaces. This also simplifies management of
dynamic zone contents for dynamic zones associated with only a single
interface.The earlier implementation described below is still available in
these later releases.Defining a Dynamic ZoneA dynamic zone is defined by specifying the dynamic_shared option in the zones file and using
the dynamic keyword in the hosts
list./etc/shorewall/zones:#NAME TYPE OPTIONS
net ipv4
rsyncok:loc ipv4 dynamic_shared/etc/shorewall/interfaces:#ZONE INTERFACE BROADCAST OPTIONS
loc eth0 - …
loc eth1 - …/etc/shorewall/hosts:#ZONE HOSTS OPTIONS
rsyncok eth0:dynamic
rsyncok eth1:dynamicWhen the dynamic_shared option is
specified, a single ipset is created; the ipset has the same name as the
zone.In the above example, rsyncok is
a sub-zone of the single zone loc.
Making a dynamic zone a sub-zone of multiple other zones is also
supported.Adding a Host to a Dynamic Zone.Adding a host to a dynamic zone is accomplished by adding the
host's IP address to the appropriate ipset. Shorewall provldes a command
for doing that:
shorewall addzone
address ...
Example:
shorewall add rsyncok 70.90.191.124
Deleting a Host from a Dynamic ZoneDeleting a host from a dynamic zone is accomplished by removing
the host's IP address from the appropriate ipset. Shorewall provldes a
command for doing that:
shorewall deletezoneaddress
...
Example:
shorewall delete rsyncok 70.19.191.124
The command can only be used when the ipset involved is of type
iphash. For other ipset types, the ipset command must
be used directly.Listing the Contents of a Dynamic ZoneThe shorewall show command may be used to list the current
contents of a dynamic zone.
shorewall show dynamiczone
Example:
shorewall show dynamic rsyncok
rsyncok:
70.90.191.122
70.90.191.124
Dynamic Zone Contents and Shorewall stop/start/restartWhen SAVE_IPSETS=Yes in shorewall.conf, the contents of a dynamic
zone survive shorewall stop/shorewall start and
shorewall restart. During shorewall
stop, the contents of the ipsets are saved in the file
${VARDIR}/ipsets.save (usually
/var/lib/shorewall/ipsets.save). During
shorewall start, the contents of that file are restored
to the sets. During both shorewall start and
shorewall restart, any new ipsets required as a result
of a configuration change are added.
shorewall-docs-xml-5.2.3/ports.xml 0000664 0000000 0000000 00000053016 13427347317 015656 0 ustar root root
Ports Required for Various Services/ApplicationsTomEastepCristian Rodriguez R.2001-Thomas 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.In addition to those applications described in the
/etc/shorewall/rules documentation, here are some other
services/applications that you may need to configure your firewall to
accommodate.This article applies to Shorewall 3.0 and
later. If you are running a version of Shorewall earlier than Shorewall
3.0.0 then please see the documentation for that releaseImportant NotesShorewall distribution contains a library of user-defined macros
that allow for easily allowing or blocking a particular application.
ls /usr/share/shorewall/macro.*
for the list of macros in your distribution. If you find what you need,
you simply use the macro in a rule. For example, to allow DNS queries
from the dmz zone to the net zone:#ACTION SOURCE DEST
DNS(ACCEPT) dmz netIn the rules that are shown in this document, the ACTION is shown
as ACCEPT. You may need to use DNAT (see FAQ
30) or you may want DROP or REJECT if you are trying to block
the application.Example: You want to port forward FTP from the net to your server
at 192.168.1.4 in your DMZ. The FTP section below gives you:#ACTION SOURCE DEST PROTO DPORT
FTP(ACCEPT) <source><destination>You would code your rule as follows:#ACTION SOURCE DESTINATION PROTO DPORT
FTP(DNAT) net dmz:192.168.1.4 Auth (identd)It is now the 21st
Century ; don't use identd in production
anymore.#ACTION SOURCE DESTINATION PROTO DPORT
Auth(ACCEPT) <source><destination>BitTorrentThis information is valid only for Shorewall 3.2 or later.This rule assumes that your
BitTorrent client listens on the default
port(s)#ACTION SOURCE DESTINATION PROTO DPORT
BitTorrent(ACCEPT)<source><destination>DNS#ACTION SOURCE DESTINATION PROTO DPORT
DNS(ACCEPT) <source><destination>Note that if you are setting up a DNS server that supports recursive
resolution, the server is the <destination> for
resolution requests (from clients) and is also the
<source> of recursive resolution requests
(usually to other servers in the 'net' zone). So for example, if you have
a public DNS server in your DMZ that supports recursive resolution for
local clients then you would need:#ACTION SOURCE DESTINATION PROTO DPORT
DNS(ACCEPT) all dmz
DNS(ACCEPT) dmz net Recursive Resolution means that if the server itself can't resolve
the name presented to it, the server will attempt to resolve the name
with the help of other servers.EmuleThis information is valid only for Shorewall 3.2 or later.In contrast to how the rest of this article is organized, for emule
I will give you the rules necessary to run emule on a single machine in
your loc network (since that's what 99.99% of you want to do). Assume
that:The internal machine running emule has IP address
192.168.1.4.You use Masquerading or SNAT for the local network.The zones are named as they are in the two- and three-interface
QuickStart guides).Your loc->net policy is ACCEPT/etc/shorewall/rules:#ACTION SOURCE DESTINATION PROTO DPORT
Edonkey(DNAT) net loc:192.168.1.4
#if you wish to enable the Emule webserver, add this rule too.
DNAT net loc:192.168.1.4 tcp 4711FTP#ACTION SOURCE DESTINATION PROTO DPORT
FTP(ACCEPT) <source><destination>Look here for much more
information.GnutellaThe internal machine running a Gnutella Client has IP address
192.168.1.4.You use Masquerading or SNAT for the local network.The zones are named as they are in the two- and three-interface
QuickStart guides).Your loc->net policy is ACCEPT#ACTION SOURCE DESTINATION PROTO DPORT
Gnutella(DNAT) net loc:192.168.1.4ICQ/AIM#ACTION SOURCE DESTINATION PROTO DPORT
ICQ(ACCEPT) <source> netIMAPWhen accessing your mail from the Internet, use onlyIMAP over
SSL.This information is valid only for Shorewall 3.2 or later.#ACTION SOURCE DESTINATION PROTO DPORT
IMAP(ACCEPT) <source><destination> # Unsecure IMAP
IMAPS(ACCEPT) <source> <destination> # IMAP over SSL.IPsec#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT <source> <destination> 50
ACCEPT <source> <destination> 51
ACCEPT <source> <destination> udp 500
ACCEPT <destination><source> 50
ACCEPT <destination><source> 51
ACCEPT <destination><source> udp 500Lots more information here and
here.LDAPThis information is valid only for Shorewall 3.2 or later.#ACTION SOURCE DESTINATION PROTO DPORT
LDAP(ACCEPT) <source> <destination> #Insecure LDAP
LDAPS(ACCEPT) <source> <destination> # LDAP over SSLMy\SQLThis information is valid only for Shorewall 3.2 or later.Allowing access from untrusted hosts to your
MySQL server represents a severe security risk.DO NOT USE THIS if you don't know
how to deal with the consequences, you have been warned.#ACTION SOURCE DESTINATION PROTO DPORT
MySQL(ACCEPT) <source> <destination>NFS#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT <z1>:<list of client IPs> <z2>:a.b.c.d tcp 111
ACCEPT <z1>:<list of client IPs> <z2>:a.b.c.d udpFor more NFS information, see http://lists.shorewall.net/~kb/.NTP (Network Time Protocol)#ACTION SOURCE DESTINATION PROTO DPORT
NTP(ACCEPT) <source><destination>PCAnywhere#ACTION SOURCE DESTINATION PROTO DPORT
PCA(ACCEPT) <source><destination>POP3If Possible , Avoid this protocol
, use IMAP instead.This information is valid only for Shorewall 3.2 or later#ACTION SOURCE DESTINATION PROTO DPORT
POP3(ACCEPT) <source><destination> # Secure
POP3S(ACCEPT) <source> <destination> #Unsecure Pop3PPTP#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT <source><destination> 47
ACCEPT <source><destination> tcp 1723Lots more information here and here.rdate#ACTION SOURCE DESTINATION PROTO DPORT
Rdate(ACCEPT) <source><destination>rsync#ACTION SOURCE DESTINATION PROTO DPORT
Rsync(ACCEPT) <source><destination>SiproxdThis assumes siproxd is running on the
firewall and is using the default ports.#ACTION SOURCE DESTINATION PROTO DPORT
REDIRECT loc 5060 udp 5060
ACCEPT net fw udp 5060
ACCEPT net fw udp 7070:7089SSH/SFTP#ACTION SOURCE DESTINATION PROTO DPORT
SSH(ACCEPT)<source><destination>SMB/NMB (Samba/Windows Browsing/File
Sharing)#ACTION SOURCE DESTINATION PROTO DPORT
SMB(ACCEPT) <source> <destination>
SMB(ACCEPT) <destination><source>Also, see this page.SMTPThis information is valid only for Shorewall 3.2 or later.#ACTION SOURCE DESTINATION PROTO DPORT
SMTP(ACCEPT) <source><destination> #Insecure SMTP
SMTPS(ACCEPT) <source><destination> #SMTP over SSL (TLS)SNMP#ACTION SOURCE DESTINATION PROTO DPORT
SNMP(ACCEPT) <source><destination>SVNThis information is valid only for Shorewall 3.2 or later.This rule is for Subversion running in svnserve mode only.#ACTION SOURCE DESTINATION PROTO DPORT
SVN(ACCEPT) <source><destination>TelnetThe telnet protocol is very
insecure, don't use it.#ACTION SOURCE DESTINATION PROTO DPORT
Telnet(ACCEPT) <source><destination>TFTPYou must have TFTP connection tracking support in your kernel. If
modularized, the modules are ip_conntrack_tftp (and ip_nat_tftp if any form of NAT is involved) These
modules may be loaded using entries in
/etc/shorewall/modules. The ip_conntrack_tftp module must be loaded first. Note
that the /etc/shorewall/modules file released with
recent Shorewall versions contains entries for these modules.#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT <source><destination> udp 69Traceroute#ACTION SOURCE DESTINATION PROTO DPORT
Trcrt(ACCEPT) <source><destination> #Good for 10 hopsUDP traceroute uses ports 33434 through 33434+<max number of
hops>-1. Note that for the firewall to respond with a TTL expired ICMP
reply, you will need to allow ICMP 11 outbound from the firewall. The
standard Shorewall sample configurations all set this up for you
automatically since those sample configurations enable all ICMP packet
types originating on the firewall itself.#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT fw net icmp
ACCEPT fw loc icmp
ACCEPT fw ...Usenet (NNTP)#ACTION SOURCE DESTINATION PROTO DPORT
NNTP(ACCEPT) <source><destination>
NNTPS(ACCEPT) <source> <destination> # secure NNTPTCP Port 119VNCThis information is valid only for Shorewall 3.2 or later.Vncviewer to Vncserver -- TCP port 5900 + <display
number>.the following rule handles VNC traffic for VNC displays 0 -
9.#ACTION SOURCE DESTINATION PROTO DPORT
VNC(ACCEPT) <source><destination>Vncserver to Vncviewer in listen mode -- TCP port 5500.#ACTION SOURCE DESTINATION PROTO DPORT
VNCL(ACCEPT) <source><destination>VonageThe standard Shorewall loc->net ACCEPT policy is all that is
required for Vonage IP phone service to work,
provided that you have loaded the tftp helper modules (add the following
entries to /etc/shorewall/modules if they are not there already):Web AccessThis information is valid for Shorewall 3.2 or later.#ACTION SOURCE DESTINATION PROTO DPORT
HTTP(ACCEPT) <source><destination> #Insecure HTTP
HTTPS(ACCEPT) <source> <destination> #Secure HTTPWebmin#ACTION SOURCE DESTINATION PROTO DPORT
Webmin(ACCEPT) <source><destination>Webmin
use TCP port 10000.Whois#ACTION SOURCE DESTINATION PROTO DPORT
Whois(ACCEPT) <source><destination>X/XDMCPAssume that the Chooser and/or X Server are running at
<chooser> and the Display Manager/X
applications are running at <apps>.#ACTION SOURCE DESTINATION PROTO DPORT
ACCEPT <chooser> <apps> udp 177 #XDMCP
ACCEPT <apps> <chooser> tcp 6000:6009 #X Displays 0-9Other Source of Port InformationDidn't find what you are looking for -- have you looked in your own
/etc/services file?Still looking? Try http://www.networkice.com/advice/Exploits/Ports
shorewall-docs-xml-5.2.3/troubleshoot.xml 0000664 0000000 0000000 00000054260 13427347317 017242 0 ustar root root
Shorewall Troubleshooting GuideTomEastep2001-2007, 2014Thomas 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 start and shorewall restart
ErrorsIf the error is detected by the Shorewall compiler, it should be
fairly obvious where the problem was found. Each error message includes
the configuration file name and line number where the error was detected
and often gives the particular item in error. The item is either enclosed
in parentheses or is at the end following a colon (":").Example:gateway:~/test # shorewall restart .
Compiling...
ERROR: Invalid ICMP Type (0/400) : /root/test/rules (line 19)
gateway:~/test # In this case, line 19 in the rules file
specified an invalid ICMP Type (0/400).Additional information about the error can be obtained using the
'debug' keyword (Shorewall 4.4.19 and earlier) or using the (-T)
option.Example (4.4.19 and earlier):gateway:~/test # shorewall debug restart
Compiling...
ERROR: Invalid ICMP Type (0/400) : /root/test/rules (line 19) at /usr/share/shorewall/Shorewall/Config.pm line 338
Shorewall::Config::fatal_error('Invalid ICMP Type (0/400)') called at /usr/share/shorewall/Shorewall/Chains.pm line 885
Shorewall::Chains::validate_icmp('0/400') called at /usr/share/shorewall/Shorewall/Chains.pm line 949
Shorewall::Chains::do_proto('icmp', '0/400', '-') called at /usr/share/shorewall/Shorewall/Rules.pm line 1055
Shorewall::Rules::process_rule1('ACCEPT', 'loc', 'net', 'icmp', '0/400', '-', '-', '-', '-', ...) called at /usr/share/shorewall/Shorewall/Rules.pm line 1290
Shorewall::Rules::process_rule('ACCEPT', 'loc', 'net', 'icmp', '0/400', '-', '-', '-', '-', ...) called at /usr/share/shorewall/Shorewall/Rules.pm line 1336
Shorewall::Rules::process_rules() called at /usr/share/shorewall/Shorewall/Compiler.pm line 799
Shorewall::Compiler::compiler('/var/lib/shorewall/.restart', '/root/test', 0, 4) called at /usr/share/shorewall/compiler.pl line 86
gateway:~/test # Example (4.4.20 and later):gateway:~/test # shorewall restart -T
Compiling...
ERROR: Invalid ICMP Type (0/400) : /root/test/rules (line 19) at /usr/share/shorewall/Shorewall/Config.pm line 338
Shorewall::Config::fatal_error('Invalid ICMP Type (0/400)') called at /usr/share/shorewall/Shorewall/Chains.pm line 885
Shorewall::Chains::validate_icmp('0/400') called at /usr/share/shorewall/Shorewall/Chains.pm line 949
Shorewall::Chains::do_proto('icmp', '0/400', '-') called at /usr/share/shorewall/Shorewall/Rules.pm line 1055
Shorewall::Rules::process_rule1('ACCEPT', 'loc', 'net', 'icmp', '0/400', '-', '-', '-', '-', ...) called at /usr/share/shorewall/Shorewall/Rules.pm line 1290
Shorewall::Rules::process_rule('ACCEPT', 'loc', 'net', 'icmp', '0/400', '-', '-', '-', '-', ...) called at /usr/share/shorewall/Shorewall/Rules.pm line 1336
Shorewall::Rules::process_rules() called at /usr/share/shorewall/Shorewall/Compiler.pm line 799
Shorewall::Compiler::compiler('/var/lib/shorewall/.restart', '/root/test', 0, 4) called at /usr/share/shorewall/compiler.pl line 86
gateway:~/test # This information is useful to Shorewall support if you need to
file a problem report.The end of the compile phase is signaled by a message such as the
following:Shorewall configuration compiled to /var/lib/shorewall/.restartErrors
occurring past that point are said to occur at
run-time because they occur during the running of
the compiled firewall script (/var/lib/shorewall/.restart in the case of
the above message).One common run-time failure is that the iptables-restore program
encounters an error. This will produce an error such as the
following:...
Restarting Shorewall....
iptables-restore v1.3.6: No chain/target/match by that name
Error occurred at line: 83
Try `iptables-restore -h' or 'iptables-restore --help' for more information.
ERROR: iptables-restore Failed. Input is in /var/lib/shorewall/.iptables-restore-input
Restoring Shorewall...
Shorewall restored from /var/lib/shorewall/restore
Terminated
gateway:~/test # A look at /var/lib/shorewall/restore at line
83 might show something like the following:-A reject -p tcp -j REJECT --reject-with tcp-resetIn
this case, the user had compiled his own kernel and had forgotten to
include REJECT target support (see kernel.htm).You may also include the word debug
as the first argument to the /sbin/shorewall and
/sbin/shorewall-lite commands.shorewall debug restartIn
most cases, debug is a synonym for
trace. The exceptions are:debug is ignored by the
Shorewall compiler.debug causes altered behavior
of generated scripts. These scripts normally use
iptables-restore to install the Netfilter ruleset but with
debug, the commands normally passed
to iptables-restore in its input file are passed
individually to iptables. This is a diagnostic aid
which allows identifying the individual command that is causing
iptables-restore to fail; it should be used when
iptables-restore fails when executing a COMMIT
command.The debug feature is strictly for
problem analysis. When debug is
used:The firewall is made 'wide open' before the rules are
applied.The stoppedrules (routestopped) file is
not consulted.The rules are applied in the canonical
iptables-restore order. So if you need critical
hosts to be always available during start/restart, you may not be
able to use debug.In other run-time failure cases:Make a note of the error message that you see.shorewall debug start 2>
/tmp/traceLook at the /tmp/trace file and see if
that helps you determine what the problem is. Be sure you find the
place in the log where the error message you saw is generated -- you
should find the message near the end of the log.If you still can't determine what's wrong then see the support page.Your Network EnvironmentMany times when people have problems with Shorewall, the problem is
actually an ill-conceived network setup. Here are several popular
snafus:Port Forwarding where client and server are in the same subnet.
See FAQ 2.Trying to test net->loc DNAT rules from inside your firewall.
You must test these rules from outside your firewall.Multiple interfaces connected to the same HUB or Switch. Given
the way that the Linux kernel respond to ARP who-has
requests, this type of setup does NOT work the
way that you expect it to. 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.New Device Doesn't Work?If you have just added a new device such as VOIP and it doesn't
work, be sure that you have assigned it an IP address in your local
network and that its default gateway has been set to the IP address of
your internal interface. For many of these devices, the simplest solution
is to run a DHCP server; running it on your firewall is fine — be sure to
set the dhcp option on your internal
interface in /etc/shorewall/interfaces.Connection ProblemsOne very important thing to remember is that not all connection
problems are Shorewall configuration problems. If the connection that is
giving you problems is to or from the firewall system or if it doesn't
rely on NAT or Proxy ARP then you can often eliminate Shorewall using a
simple test:/sbin/shorewall clearTry the connection. If it works then the problem is in your
Shorewall configuration; if the connection still doesn't work then the
problem is not with Shorewall or the way that it is configured.Be sure to /sbin/shorewall start after the
test.If you still suspect Shorewall and the appropriate policy for the
connection that you are trying to make is ACCEPT, please DO NOT ADD
ADDITIONAL ACCEPT RULES TRYING TO MAKE IT WORK. Such additional rules will
NEVER make it work, they add clutter to your rule set and they represent a
big security hole in the event that you forget to remove them
later.I also recommend against setting all of your policies to ACCEPT in
an effort to make something work. That robs you of one of your best
diagnostic tools - the Shorewall messages that Netfilter
will generate when you try to connect in a way that isn't permitted by
your rule set.Check your log (/sbin/shorewall show
log). If you don't see Shorewall messages, then your
problem is probably NOT a Shorewall problem. If you DO see packet
messages, it may be an indication that you are missing one or more rules
-- see FAQ 17.While you are troubleshooting, it is a good idea to clear LOGLIMIT
in
/etc/shorewall/shorewall.conf:LOGLIMIT=This way, you will see all
of the log messages being generated (be sure to restart shorewall after
clearing thIs variable).Log MessageJun 27 15:37:56 gateway kernel: Shorewall:all2all:REJECT:IN=eth2
OUT=eth1 SRC=192.168.2.2
DST=192.168.1.3 LEN=67 TOS=0x00
PREC=0x00 TTL=63 ID=5805 DF
PROTO=UDP SPT=1803 DPT=53 LEN=47Let's look at the important parts of this message:all2all:REJECT - This packet was REJECTed out of the all2all
chain -- the packet was rejected under the
all->all REJECT policy (see FAQ 17).IN=eth2 - the packet entered the firewall via eth2OUT=eth1 - if accepted, the packet would be sent on
eth1SRC=192.168.2.2 - the packet was sent by 192.168.2.2DST=192.168.1.3 - the packet is destined for
192.168.1.3PROTO=UDP - UDP ProtocolDPT=53 - DNSIn this case, 192.168.2.2 was in the dmz zone and
192.168.1.3 is in the loc zone. I was missing the
rule:#ACTION SOURCE DEST PROTO DEST
# PORT(S)
ACCEPT dmz loc udp 53Ping ProblemsEither can't ping when you think you should be able to or are able
to ping when you think that you shouldn't be allowed? Shorewall's
Ping Management is described
here. Here are a couple of tips:Remember that Shorewall doesn't automatically allow ICMP type 8
(ping) requests to be sent between zones. If you want
pings to be allowed between zones, you need a rule of the form:#ACTION SOURCE DEST PROTO DEST
# PORT(S)
Ping(ACCEPT)<source zone><destination zone>The ramifications of this can be subtle. For example, if you
have the following in /etc/shorewall/nat:#EXTERNAL INTERFACE INTERNAL
10.1.1.2 eth0 130.252.100.18and you ping 130.252.100.18, unless you have allowed icmp type 8
between the zone containing the system you are pinging from and the
zone containing 10.1.1.2, the ping requests will be dropped.Ping requests are subject to logging under your policies. So
ping floods can cause an equally big flood of log messages. To
eliminate these, as the last rule in your /etc/shorewall/rules file
add:#ACTION SOURCE DEST PROTO DEST
# PORT(S)
Ping(DROP)net allSome 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.Other GotchasSeeing rejected/dropped packets logged out of the INPUT or
FORWARD chains? This means that:your zone definitions are screwed up and the host that is
sending the packets or the destination host isn't in any zone
(using an /etc/shorewall/hosts
file are you?); orthe source and destination hosts are both connected to the
same interface and you don't have a policy or rule for the source
zone to or from the destination zone or you haven't set the
routeback option for the
interface in /etc/shorewall/interfaces.You have connected two firewall interfaces (from different
zones) to the same hub or switch.If you specify routefilter for an interface, that
interface must be up prior to starting the firewall.Is your routing correct? For example, internal systems usually
need to be configured with their default gateway set to the IP address
of their nearest firewall interface. One often overlooked aspect of
routing is that in order for two hosts to communicate, the routing
between them must be set up in both
directions. So when setting up routing between A and B, be
sure to verify that the route from B
back to A is defined and
correct.Do you have your kernel properly configured? Click here to see kernel configuration
information.Still Having Problems?See the Shorewall Support
Page.
shorewall-docs-xml-5.2.3/Anti-Spoofing.xml 0000664 0000000 0000000 00000011102 13427347317 017152 0 ustar root root
Countering Spoofing AttemptsTomEastep2012Thomas 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.IntroductionSpoofing is the practice of sending packets
with a forged source address in an attempt to circumvent security
measures. Shorewall supports a variety of measures to counter spoofing
attacks.The routefilter Interface OptionThis shorewall-interfaces (5) option was
the first measure implemented and uses
/proc/sys/net/ipv4/conf/*/rp_filter. Many
distributions set this option by default for all ip interfaces. The option
works by determining the reverse path (the route from the packets
destination to its source); it that route does not go out through the
interface that received the packet, then the packet is declared to be a
martian and is dropped. A kernel log message is generated if the
interface's option is set
(/proc/sys/net/ipv4/conf/*/log_martians).While this option is simple to configure, it has a couple of
disadvantages:It is not supported by IPv6.It does not use packet marks so it doesn't work with some Multi-ISP configurations.The log messages produces are obscure and confusing.Hairpin FilteringSpoofing can be used to exploit Netfilter's connection tracking to
open arbitrary firewall ports. Attacks of this type establish a connection
to a server that uses separate control and data connections such as an FTP
server. It then sends a packet addressed to itself and from the server.
Such packets are sent back out the same interface that received them
(hairpin). In cases where the
option can't be used, Shorewall 4.4.20 and
later will set up hairpinning traps (see the SFILTER_DISPOSITION and
SFILTER_LOG_LEVEL options in shorewall.conf (5)).This automatic hairpin trapping is disabled on interfaces with the
option.The rpfilter Interface OptionA new iptables/ip6tables match (rpfilter) was added in kernel 3.4.4.
This match performs reverse path evaluation similar to
but without the disadvantages:It is supported by both IPv4 and IPv6.It uses packet marks so it works with all Multi-ISP configurations.It produces standard Shorewall/Netfilter log messages controlled
by the RPFILTER_LOG_LEVEL option in shorewall.conf (5)).Both the disposition and auditing can be controlled using the
RPFILTER_DISPOSITION option in shorewall.conf (5)).
shorewall-docs-xml-5.2.3/ProxyARP.xml 0000664 0000000 0000000 00000035103 13427347317 016170 0 ustar root root
Proxy ARPTomEastep2001-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.OverviewProxy ARP (RFC 1027) is a way to make a machine physically located
on one network appear to be logically part of a different physical network
connected to the same router/firewall. Typically it allows us to hide a
machine with a public IP address on a private network behind a router, and
still have the machine appear to be on the public network "in front of"
the router. The router "proxys" ARP requests and all network traffic to
and from the hidden machine to make this fiction possible.Consider a router with two interface cards, one connected to a
public network PUBNET and one connected to a private network PRIVNET. We
want to hide a server machine on the PRIVNET network but have it
accessible from the PUBNET network. The IP address of the server machine
lies in the PUBNET network, even though we are placing the machine on the
PRIVNET network behind the router.By enabling proxy ARP on the router, any machine on the PUBNET
network that issues an ARP "who has" request for the server's MAC address
will get a proxy ARP reply from the router containing the router's MAC
address. This tells machines on the PUBNET network that they should be
sending packets destined for the server via the router. The router
forwards the packets from the machines on the PUBNET network to the server
on the PRIVNET network.Similarly, when the server on the PRIVNET network issues a "who has"
request for any machines on the PUBNET network, the router provides its
own MAC address via proxy ARP. This tells the server to send packets for
machines on the PUBNET network via the router. The router forwards the
packets from the server on the PRIVNET network to the machines on the
PUBNET network.The proxy ARP provided by the router allows the server on the
PRIVNETnetwork to appear to be on the PUBNET network. It lets the router
pass ARP requests and other network packets in both directions between the
server machine and the PUBNET network, making the server machine appear to
be connected to the PUBNET network even though it is on the PRIVNET
network hidden behind the router.Before you try to use this technique, I strongly recommend that you
read the Shorewall Setup
Guide.ExampleThe following figure represents a Proxy ARP environment.Proxy ARP can be used to make the systems with addresses
130.252.100.18 and 130.252.100.19 appear to be on the upper
(130.252.100.*) subnet. Assuming that the upper firewall interface is eth0
and the lower interface is eth1, this is accomplished using the following
entries in /etc/shorewall/proxyarp:#ADDRESS INTERFACE EXTERNAL HAVEROUTE PERSISTENT
130.252.100.18 eth1 eth0 no yes
130.252.100.19 eth1 eth0 no yes Be sure that the internal systems
(130.242.100.18 and 130.252.100.19 in the above example) are not included
in any specification in /etc/shorewall/masq
(/etc/shorewall/snat on Shorewall 5.0.14 or later) or
/etc/shorewall/nat.I've used an RFC1918 IP address for eth1 - that IP address is
largely irrelevant (see below).The lower systems (130.252.100.18 and 130.252.100.19) should have their subnet mask and default gateway configured
exactly the same way that the Firewall system's eth0 is configured. In
other words, they should be configured just like they would be if they
were parallel to the firewall rather than behind it.Do not add the Proxy ARP'ed address(es) (130.252.100.18 and
130.252.100.19 in the above example) to the external interface (eth0 in
this example) of the firewall.It should be stressed that entries in the proxyarp file do not
automatically enable traffic between the external network and the
internal host(s) — such traffic is still subject to your policies and
rules.While the address given to the firewall interface is largely
irrelevant, one approach you can take is to make that address the same as
the address of your external interface!In the diagram above, eth1
has been given the address 130.252.100.17, the same as
eth0. Note though that the VLSM is 32 so there is no
network associated with this address. This is the approach that I take with my DMZ.To permit Internet hosts to connect to the local systems, you use
ACCEPT rules. For example, if you run a web server on 130.252.100.19 which
you have configured to be in the loc zone
then you would need this entry in /etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
ACCEPT net loc:130.252.100.19 tcp 80Your distribution's network configuration GUI may not be capable
of configuring a device in this way. It may complain about the duplicate
address or it may configure the address incorrectly. Here is what the
above configuration should look like when viewed using
ip (the line "inet 130.252.100.17/32 scope global
eth1" is the most important):gateway:~# ip addr ls eth1
3: eth1: <BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:a0:cc:d1:db:12 brd ff:ff:ff:ff:ff:ff
inet 130.252.100.17/32 scope global eth1
gateway:~#Note in particular that there is no broadcast address. Here is an
ifcfg-eth-id-00:a0:cc:d1:db:12 file from SUSE that
produces this result (Note: SUSE ties the configuration file to the card
by embedding the card's MAC address in the file name):BOOTPROTO='static'
BROADCAST='130.252.100.17'
IPADDR='130.252.100.17'
MTU=''
NETMASK='255.255.255.255'
NETWORK='130.252.100.17'
REMOTE_IPADDR=''
STARTMODE='onboot'
UNIQUE='8otl.IPwRm6bNMRD'
_nm_name='bus-pci-0000:00:04.0'Here is an excerpt from a Debian /etc/network/interfaces file that
does the same thing:...
auto eth1
iface eth1 inet static
address 130.252.100.17
netmask 255.255.255.255
broadcast 0.0.0.0
...ARP cacheA word of warning is in order here. ISPs typically configure their
routers with a long ARP cache timeout. If you move a system from parallel
to your firewall to behind your firewall with Proxy ARP, it will probably
be HOURS before that system can
communicate with the Internet.If you sniff traffic on the firewall's external interface, you can
see incoming traffic for the internal system(s) but the traffic is never
sent out the internal interface.You can determine if your ISP's gateway ARP cache is stale using
ping and tcpdump. Suppose that we suspect that the gateway router has a
stale ARP cache entry for 130.252.100.19. On the firewall, run tcpdump as
follows:tcpdump -nei eth0 icmpNow from 130.252.100.19, ping the ISP's gateway (which we will
assume is 130.252.100.254):ping 130.252.100.254We can now observe the tcpdump output:13:35:12.159321 0:4:e2:20:20:33 0:0:77:95:dd:19 ip 98: 130.252.100.19 > 130.252.100.254: icmp: echo request (DF)
13:35:12.207615 0:0:77:95:dd:19 0:c0:a8:50:b2:57 ip 98: 130.252.100.254 > 130.252.100.19 : icmp: echo replyNotice that the source MAC address in the echo request is different
from the destination MAC address in the echo reply!! In this case
0:4:e2:20:20:33 was the MAC of the firewall's eth0 NIC while
0:c0:a8:50:b2:57 was the MAC address of the system on the lower left. In
other words, the gateway's ARP cache still associates 130.252.100.19 with
the NIC in that system rather than with the firewall's eth0.If you have this problem, there are a couple of things that you can
try:A reading of TCP/IP Illustrated, Vol 1 by
Stevens revealsCourtesy of Bradey Honsinger that a gratuitous ARP packet should cause
the ISP's router to refresh their ARP cache (section 4.7). A
gratuitous ARP is simply a host requesting the MAC address for its own
IP; in addition to ensuring that the IP address isn't a
duplicate...
if the host sending the gratuitous ARP has just changed its
hardware address..., this packet causes any other host...that has an
entry in its cache for the old hardware address to update its ARP
cache entry accordingly.
Which is, of course, exactly what you want to do when you switch
a host from being exposed to the Internet to behind Shorewall using
proxy ARP (or one-to-one NAT for that matter). Happily enough, recent
versions of Redhat's iputils package include arping,
whose -U flag does just that:arping -U -I <net if> <newly proxied IP>
arping -U -I eth0 66.58.99.83 # for exampleStevens goes on to mention that not all systems respond
correctly to gratuitous ARPs, but googling for arping
-U seems to support the idea that it works most of the
time.To use arping with Proxy ARP in the above example, you would
have to:shorewall clear
ip addr add 130.252.100.18 dev eth0
ip addr add 130.252.100.19 dev eth0
arping -U -c 10 -I eth0 130.252.100.18
arping -U -c 10 -I eth0 130.252.100.19
ip addr del 130.252.100.18 dev eth0
ip addr del 130.252.100.19 dev eth0
shorewall startYou can call your ISP and ask them to purge the stale ARP cache
entry but many either can't or won't purge individual entries.There are two distinct versions of arping
available:arping by Thomas Habets (Debian package
arping).arping as part of the iputils package by
Alexey Kuznetsov (Debian package
iputils-arping).You want the second one by Alexey Kuznetsov.IPv6 - Proxy NDPThe IPv6 analog of Proxy ARP is Proxy NDP (Neighbor Discovery
Protocol). Beginning with Shorewall 4.4.16, Shorewall6 supports Proxy NDP
in a manner similar to Proxy ARP support in Shorewall:The configuration file is /etc/shorewall6/proxyndp (see shorewall6-proxyndp
(5)).The ADDRESS column of that file contains an IPv6 address.It should be noted that IPv6 implements a "strong host model"
whereas Linux IPv4 implements a "weak host model". In the strong model, IP
addresses are associated with interfaces; in the weak model, they are
associated with the host. This is relevant with respect to Proxy NDP in
that a multi-homed Linux IPv6 host will only respond to neighbor
discoverey requests for IPv6 addresses configured on the interface
receiving the request. So if eth0 has address 2001:470:b:227::44/128 and
eth1 has address 2001:470:b:227::1/64 then in order for eth1 to respond to
neighbor discoverey requests for 2001:470:b:227::44, the following entry
in /etc/shorewall6/proxyndp is required:#ADDRESS INTERFACE EXTERNAL HAVEROUTE PERSISTENT
2001:470:b:227::44 - eth1 YesA practical application is shown in the Linux Vserver article.
shorewall-docs-xml-5.2.3/GenericTunnels.xml 0000664 0000000 0000000 00000010563 13427347317 017434 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.2.3/starting_and_stopping_shorewall.xml 0000664 0000000 0000000 00000066540 13427347317 023175 0 ustar root root
Operating Shorewall and Shorewall LiteTomEastep2004200520062007Thomas 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./sbin/shorewall and /sbin/shorewall-lite/sbin/shorewall is the program that you use to
interact with Shorewall. Normally the root user's PATH includes
/sbin and the program can be run from a shell prompt
by simply typing shorewall followed by a
command.In some releases of KDE, the default configuration of the
konsole program is brain dead with
respect to the "Root Console". It executes the command "su" where it
should execute "su -"; the latter will cause a login shell to be created
which will in turn set PATH properly. You can correct this problem as
follows:Click on "Settings" on the toolbar and select "Configure
Konsole"Select the "Session" tab.Click on "Root Console"Change the Execute command from "su" to "su -"Click on "Save Session"Click on "Ok"To see a list of supported commands, use the help
command:shorewall helpTo get further information about a particular command, use the
man command:man shorewallThe program /sbin/shorewall-lite
performs a similar role with Shorewall-lite.For a more complete description of the files and directories
involved in Shorewall and Shorewall-lite, see the Shorewall Anatomy article.Starting, Stopping and ClearingAs explained in the Introduction, Shorewall is not something
that runs all of the time in your system. Nevertheless, for integrating
Shorewall into your initialization scripts it is useful to speak of
starting Shorewall and
stopping Shorewall.Shorewall is started using the shorewall
start command. Once the start command completes
successfully, Netfilter is configured as described in your Shorewall
configuration files. If there is an error during shorewall
start, then if you have a saved
configuration then that configuration is restored.
Otherwise, an implicit shorewall stop is
executed.shorewall start is implemented as a
compile and go; that is, the configuration is
compiled and if there are no compilation errors then the resulting
compiled script is executed. If there are compilation errors, the
command is aborted and the state of the firewall is not
altered.Shorewall is stopped using the shorewall stop
command.The shorewall stop command does not remove
all Netfilter rules and open your firewall for all traffic to pass.
It rather places your firewall in a safe state defined by the
contents of your /etc/shorewall/stoppedrules
file and the setting of ADMINISABSENTMINDED in /etc/shorewall/shorewall.conf.If you want to remove all Netfilter rules and open your firewall
for all traffic to pass, use the shorewall clear
command.If you change your configuration and want to install the
changes, use the shorewall reload command.For additional information, see the Shorewall
State Diagram section./etc/init.d/shorewall and /etc/init.d/shorewall-liteBecause of the different requirements of distribution packaging
systems, the behavior of /etc/init.d/shorewall and
/etc/init.d/shorewall-lite is not consistent between
distributions. As an example, when using the distribution Shorewall
packages on Debian and
Ubuntu systems, running
/etc/init.d/shorewall stop will actually execute the
command /sbin/shorewall clear rather than
/sbin/shorewall stop! So don't expect the meaning of
start, stop,
restart, etc. to be consistent between
/sbin/shorewall (or
/sbin/shorewall-lite) and your init scripts unless
you got your Shorewall package from shorewall.net.Update:
In Shorewall 4.4.0 and later, the tarballs from shorewall.net
follow the Debian convention when installed on a Debian or Ubuntu
system. Beginning with Shorewall 4.4.10, you can revert to the prior
behavior by setting SAFESTOP=1 in
/etc/default/shorewall,
/etc/default/shorewall6, etc.
Tracing Command Execution and other Debugging AidsShorewall includes features for tracing and debugging. Commands
involving the compiler can have the word trace inserted immediately after the
command.Example:shorewall trace check -rThis produces a large amount of diagnostic output to standard out
during the compilation step. If entered on a command that doesn't invoke
the compiler, trace is ignored.Commands that invoke a compiled fireawll script can have the word
debug inserted immediately after the command.Example:shorewall debug restartdebug causes altered behavior of
scripts generated by the Shorewall compiler. These scripts normally use
ip[6]tables-restore to install the Netfilter ruleset, but with debug, the
commands normally passed to iptables-restore in its input file are passed
individually to ip[6]tables. This is a diagnostic aid which allows
identifying the individual command that is causing ip[6]tables-restore to
fail; it should be used when ip[6]tables-restore fails when executing a
COMMIT command.The debug feature is strictly for problem analysis. When debug is
used:The firewall is made 'wide open' before the rules are
applied.The stoppedrules file is not
consulted.The rules are applied in the canonical ip[6]tables-restore
order. So if you need critical hosts to be always available during
start/restart, you may not be able to use debug.Having Shorewall Start Automatically at Boot TimeThe .rpm, .deb and .tgz all try to configure your startup scripts so
that Shorewall will start automatically at boot time. If you are using the
install.sh script from the .tgz and it cannot determine
how to configure automatic startup, a message to that effect will be
displayed. You will need to consult your distribution's documentation to
see how to integrate the /etc/init.d/shorewall script
into the distribution's startup mechanism.Shorewall startup is disabled by default. Once you have
configured your firewall, you can enable startup by editing
/etc/shorewall/shorewall.conf and setting
STARTUP_ENABLED=Yes.. Note: Users of the .deb package must rather
edit /etc/default/shorewall and set
startup=1.If you use dialup or some flavor of PPP where your IP
address can change arbitrarily, you may want to start the firewall
in your /etc/ppp/ip-up.local script. I
recommend just placing /sbin/shorewall
restart in that script.Saving a Working Configuration for Error Recovery and Fast
StartupOnce you have Shorewall working the way that you want it to, you can
use shorewall save to save the
commands necessary to recreate that configuration in a restore
script.In its simplest form, the save command is just:shorewall saveThat command creates the default restore script,
/var/lib/shorewall/restore. The default may be
changed using the RESTOREFILE option in /etc/shorewall/shorewall.conf.
A different file name may also be specified in the save
command:shorewall save <filename>Where <filename> is a simple file name
(no slashes).Once created, the default restore script serves several useful
purposes:If you change your configuration and there is an error when you
try to restart Shorewall, the restore script will be run to restore
your firewall to working order.Bootup is faster (although with Shorewall-perl, the difference
is minimal). The -f option of the start command (e.g.,
shorewall -f start) causes Shorewall to look for
the default restore script and if it exists, the script is run. When
using Shorewall-shell, this is much faster than starting Shorewall
using the normal mechanism of reading the configuration files and
running iptables dozens or even hundreds of
times.The default is to not use -f. If you wish to change the default,
you must set the OPTIONS shell variable in either
/etc/default/shorewall or
/etc/sysconfig/shorewall (if your distribution
provides neither of these files, you must create one or the
other).Update: In Shorewall 4.4.20, a
new LEGACY_FASTSTART option was added to /etc/shorewall/shorewall.conf.
When LEGACY_FASTSTART=No, the compiled script that did the last
successful start or restart will be used.The shorewall restore command can be used at
any time to quickly configure the firewall.shorewall restore [ <filename> ]If no <filename> is given, the
default restore script is used. Otherwise, the script
/var/lib/shorewall/<filename> is
used.The ability to have multiple restore scripts means that you can save
different Shorewall firewall configurations and switch between them
quickly using the restore command.Restore scripts may be removed using the shorewall
forget command:shorewall forget [ <filename> ]If no <filename> is given, the default
restore script is removed. Otherwise,
/var/lib/shorewall/<filename> is removed (of
course, you can also use the Linux rm command from the
shell prompt to remove these files).Additional Configuration DirectoriesThe CONFIG_PATH setting in
/etc/shorewall/shorewall.conf determines where
Shorewall looks for configuration files. The default setting is
CONFIG_PATH=/etc/shorewall:/usr/share/shorewall which means that
/etc/shorewall is searched first
and if the file is not found then /usr/share/shorewall is searched. You can
change the value of CONFIG_PATH to cause additional directories to be
searched but CONFIG_PATH should always include both
/etc/shorewall and /usr/share/shorewall.When an alternate configuration directory is specified as described
in the next section, that directory
is searched before those directories listed in
CONFIG_PATH.Example - Search /etc/shorewall, /etc/shorewall/actiondir and /usr/share/shorewall in that order:CONFIG_PATH=/etc/shorewall:/etc/shorewall/actiondir:/usr/share/shorewallThe above is the setting that I once used to allow me to place all
of my user-defined 'action.' files in /etc/shorewall/actiondir.Alternate Configuration DirectoriesAs explained above, Shorewall
normally looks for configuration files in the directories specified by the
CONFIG_PATH option in /etc/shorewall/shorewall.conf. The
shorewall start, shorewall restart,
shorewall check, and shorewall try
commands allow you to specify an additional directory for
Shorewall to check before looking in the directories listed in
CONFIG_PATH.shorewall {start|restart|check} <configuration-directory>shorewall try <configuration-directory> [ <timeout> ]If a <configuration-directory> is
specified, each time that Shorewall is going to read a file, it will first
look in the <configuration-directory> . If the
file is present in the
<configuration-directory>, that file will be
used; otherwise, the directories in the CONFIG_PATH will be searched. When
changing the configuration of a production firewall, I recommend the
following:If you haven't saved the current working configuration, do so
using shorewall save.mkdir /etc/testcd /etc/test<copy any files that you need to change from /etc/shorewall
to . and change them here>shorewall check ./<correct any errors found by check and check again>shorewall restart ./If the restart fails, your configuration will be
restored to its state at the last shorewall
save.When the new configuration works then just:cp -f * /etc/shorewallcdrm -rf /etc/testshorewall saveShorewall requires that the file
/etc/shorewall/shorewall.conf to always exist.
Certain global settings are always obtained from that file. If you
create alternative configuration directories, do not remove
/etc/shorewall/shorewall.conf.CommandsThe general form of a command is:
shorewall [ <options> ] <command> [
<command options> ] [ <argument> ... ]Available options are:-c <directory>Specifies an alternate
configuration directory. Use of this option is
deprecated.-fSpecifies fast restart. See the start
command below.-nPrevents the command from changing the firewall system's
routing configuration.-qReduces the verbosity level (see VERBOSITY setting in shorewall.conf). May
be repeated (e.g., "-qq") with each instance reducing the
verbosity level by one.-vIncreases the verbosity level (see VERBOSITY setting in
shorewall.conf). May
be repeated (e.g., "-vv") with each instance increasing the
verbosity level by one.-xCauses all iptables -L commands to display actual packet and
byte counts.-tAll progress messages are timestamped with the date and
time.In addition, the -q and -v
options may be repeated to make the output less or more verbose
respectively. The default level of verbosity is determined by the
setting of the VERBOSITY option in
/etc/shorewall/shorewall.conf.For Shorewall Lite, the general command form is:shorewall-lite [ <options> ] <command> [
<command options> ] [ <argument> ... ]where the options are the same as with Shorewall.The complete documentation for each command may be found in the
shorewall and shorewall-lite man
pages.
Shorewall State DiagramThe Shorewall State Diagram is depicted below./sbin/shorewall CommandResulting /var/lib/shorewall/firewall
CommandEffect if the Command Succeedsshorewall startfirewall startThe system filters packets based on your current Shorewall
Configurationshorewall stopfirewall stopOnly traffic allowed by ACCEPT entries in
/etc/shorewall/stoppedrules is passed to/from/through the
firewall. If ADMINISABSENTMINDED=Yes in
/etc/shorewall/shorewall.conf then in addition, all existing
connections are retained and all connection requests from the
firewall are accepted.shorewall reloadfirewall reloadVery similar to start, replacing the existing ruleset with
one that reflects the current configuration file contents.shorewall restartfirewall restartLogically equivalent to firewall stop;firewall
startshorewall addfirewall addAdds a host or subnet to a dynamic zoneshorewall deletefirewall deleteDeletes a host or subnet from a dynamic zoneshorewall refreshfirewall refreshReloads rules dealing with static blacklisting, traffic
control and ECN.shorewall resetfirewall resetResets traffic countersshorewall clearfirewall clearRemoves all Shorewall rules, chains, addresses, routes and
ARP entries.shorewall tryfirewall -c <new configuration> restart If
unsuccessful then firewall start (standard configuration) If
timeout then firewall restart (standard configuration)The only time that a program other than
/usr/share/shorewall[-lite[/firewall performs a state
transition itself is when the shorewall[-lite] restore
command is executed. In that case, the
/var/lib/shorewall[-lite]/restore program sets the
state to "Started".With any command that involves compilation, there is no state
transition while the compiler is running. If compilation fails, the state
remains unchanged.Also, shorewall start, shorewall
reload and shorewall restart involve
compilation followed by execution of the compiled script. So it is the
compiled script that performs the state transition in these commands
rather than /usr/share/shorewall/firewall.The compiled script is placed in /var/lib/shorewall and is named either
.start, .reload or .restart
depending on the command.
shorewall-docs-xml-5.2.3/Manpages6.xml 0000664 0000000 0000000 00000015530 13427347317 016327 0 ustar root root
Shorewall6 5.0 ManpagesTomEastep2007-2014Thomas 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 Shorewall6 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.blrules
- shorewall6 Blacklist file.conntrack - Specify
helpers for connections or exempt certain traffic from netfilter
connection tracking.exclusion -
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.maclist
- Define MAC verification.mangle -
Supersedes tcrules and describes packet/connection marking.masq -
Define Masquerade/SNATmodules
- Specify which kernel modules to load.nat -
(added in Shorewall 4.6.4) Specify 1:1 NATnesting
- How to define nested zones.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.proxyndp - Defines
Proxy NDPrtrules
- 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 - Attached
an SELinux context to a packet.stoppedrules -
Specify connections to be permitted when Shorewall6 is in the stopped
state (Added in Shoreall 4.5.8).tcclasses - Define
htb classes for traffic shaping.tcdevices - Specify
speed of devices for traffic shaping.tcinterfaces -
Specify interfaces for simplified traffic shaping.tcpri -
Classify traffic for simplified traffic shaping.tunnels
- Define VPN connections with endpoints on the firewall.shorewall6.conf - Specify
values for global Shorewall6 options.shorewall6-lite.conf
- Specify values for global Shorewall6 Lite options.vardir -
Redefine the directory where Shorewall6 keeps its state
information.vardir-lite -
Redefine the directory where Shorewall6 Lite keeps its state
information.zones -
Declare Shorewall6 zones.
Section 8 — Administrative Commands
shorewall6 -
/sbin/shorewall6 command syntax and semantics.shorewall6-lite -
/sbin/shorewall6-lite command syntax and semantics.
shorewall-docs-xml-5.2.3/Install.xml 0000664 0000000 0000000 00000143431 13427347317 016116 0 ustar root root
Shorewall Installation and UpgradeTomEastep2001-200620092012Thomas 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 installing or upgrading to a version of Shorewall
earlier than Shorewall 4.3.5 then please see the documentation for that
release.Before attempting installation, I strongly urge you to read and
print a copy of the Shorewall
QuickStart Guide for the configuration that most closely matches
your own. This article only tells you how to install the product on your
system. The QuickStart Guides describe how to configure the
product.Before upgrading, be sure to review the Upgrade Issues.Shorewall RPMs are signed. To avoid warnings such as the
followingwarning: shorewall-3.2.1-1.noarch.rpm: V3 DSA signature: NOKEY, key ID 6c562ac4download the Shorewall GPG
key and run this command:rpm --import shorewall.gpg.keyInstall using RPMTo install Shorewall using the RPM:Be sure that you have the correct RPM
package!The standard RPM package from shorewall.net and the mirrors is
known to work with SUSE, Power PPC, Trustix and TurboLinux. There is
also an RPM package provided by Simon Matter that is tailored for
RedHat/Fedora
and another package from Jack Coates that is customized for Mandriva. All of these
are available from the download
page.If you try to install the wrong package, it probably won't
work.Install the RPMsrpm -ivh <shorewall rpm>Some users are in the habit of using the rpm
-U command for installing packages as well as for updating
them. If you use that command when installing the Shorewall RPM then
you will have to manually enable Shorewall startup at boot time by
running chkconfig, insserv or
whatever utility you use to manipulate you init symbolic
links.Shorewall is dependent on the iproute package. Unfortunately,
some distributions call this package iproute2 which will cause the
installation of Shorewall to fail with the diagnostic:error: failed dependencies:iproute is needed by shorewall-3.2.x-1This problem should not occur if you are using the correct RPM
package (see 1., above) but may be worked around by using the
--nodeps option of rpm.rpm -ivh --nodeps <rpms>Example:rpm -ivh shorewall-4.3.5-0base.noarch.rpmInstall using tarballVersions 4.5.2 and LaterShorewall 4.5.2 introduced a change in the philosopy used by the
Shorewall installers. 4.5.2 introduced the concept of
shorewallrc files. These files define the
parameters to the install process. During the first installation using
Shorewall-core 4.5.2 or later, a
shorewallrc file named ${HOME}/.shorewallrc will be installed. That file
will provide the default parameters for installing other Shorewall
components of the same or later version.Note that you must install Shorewall-core
before installing any other Shorewall package.Each of the Shorewall packages contains a set of
distribution-specific shorewallrc files:shorewallrc.apple (OS X)shorewallrc.archlinuxshorewallrc.cygwin (Cygwin running on Windows)shorewallrc.debian (Debian and derivatives)shoreallrc.default (Generic Linux)shorewallrc.redhat (Fedora, RHEL and derivatives)shorewallrc.slackwareshorewallrc.suse (SLES and OpenSuSE)shorewallrc.openwrt (OpenWRT)When installing 4.5.2 or later for the first time, a special
procedure must be followed:Select the shorewallrc file that is closest to your
needs.Review the settings in the file.If you want to change something then you have two
choices:Copy the file to shorewallrc and edit the copy to meet
your needs; orIf the system has Bash (/bin/bash) 4.0 or later installed,
you can run ./configure (see below). If you are installing
4.5.2.1 or later and your system has Perl installed, you can use
the Perl version (./configure.pl)../install.shIf you don't need to change the file, then simply:./install.sh
shorewallrcfile-that-meets-your-needsExample: ./install.sh
shorewallrc.debianThe shorewall-core install.sh script will store the shorewallrc
file in ~/.shorewallrc where it will provide the defaults for future
installations of all Shorewall products. Other packages/versions can be
installed by simply typing./install.shSettings in a shorewallrc fileA shorewallrc file contains a number of lines of the form
option=value.
Because some of the installers are shared between Shorewall products,
the files assume the definition of the symbol PRODUCT. $PRODUCT will
contain the name of a Shorewall product (shorewall-core, shorewall,
shorewall6, shorewall-lite, shorewall6-lite or shorewall-init).Valid values for option are:HOSTSelects the shorewallrc file to use for default settings.
Valid values are:appleOS XarchlinuxArchlinuxcygwinCygwin running under WindowsdebianDebian and derivatives (Ubuntu, Kbuntu, etc)defaultGeneric LinuxredhatFedora, RHEL and derivatives (CentOS, Foobar,
etc)slackwareSlackware LinuxsuseSLES and OpenSuSeopenwrtOpenWRT (Shorewall 5.0.2 and later)PREFIXTop-level directory under which most Shorewall components
are installed. All standard shorewallrc files define this as
\usr.SHAREDIRThe directory where most Shorewall components are
installed. In all of the standard shorewallrc file, this option
has the value ${PREFIX}/share.LIBEXECDIRDirectory where internal executables are stored. In the
standard shorewallrc files, the default is either ${PREFIX}/share or ${PREFIX}/libexecPERLLIBDIRDirectory where the Shorewall Perl modules are installed.
They will be installed in this directory under the sub-directory
Shorewall. Default is distribution-specific.CONFDIRDirectory where subsystem configuration data is stored.
Default is /etc in all
shorewallrc file.SBINDIRDirectory where CLI programs will be installed. Default in
all shorewallrc files is /sbin.MANDIRDirectory under which manpages are to be installed.
Default is distribution dependent.INITDIRDirectory under which SysV init scripts are installed.
Default is distribution dependent.INITSOURCEFile in the package that is to be installed as the SysV
init script for the product.INITFILEThe name of the SysV init script when installed under
$INITDIR. May be empty, in which case no SysV init script will
be installed. This is usually the case on systems that run
systemd and on systems like Cygwin or OS X where Shorewall can't
act as a firewall.AUXINITSOURCE and AUXINITFILEAnalogs of INITSOURCE and INITFILE for distributions, like
Slackware, that have a master SysV init script and multiple
subordinate scripts.SYSTEMDThe directory under which the product's .service file is
to be installed. Should only be specified on systems running
systemd.SERVICEFILEAdded in Shorewall 4.5.20. When SYSTEMD is specified, this
variable names the file to be installed as the product's
.service file. If not specified, $PRODUCT.service is
assumed.SYSCONFDIRThe directory where package SysV init configuration files
are to be installed. /etc/default on Debian and derivatives
and /etc/sysconfig
otherwiseSYSCONFFILEThe file in the Shorewall package that should be installed
as ${SYSCONFDIR}/$PRODUCTANNOTATEDValue is either empty or non-empty. Non-empty indicates
that files in ${CONFDIR}/${PRODUCT} should be annotated with
manpage documentation.SPARSEValue is either empty or non-empty. When non-empty, only
${PRODUCT}.conf will be installed in
${CONFDIR}/${PRODUCT}VARLIBAdded in Shorewall 4.5.8. Directory where subsystem state
data is to be stored. Default is /var/lib.VARDIRShorewall 4.5.7 and earlier: Directory where subsystem
state data is to be stored. Default is /var/lib.Shorewall 4.5.8 and later: Default is /var/lib/$PRODUCT.From Shorewall 4.5.2 through 4.5.7, there were two
interpretations of VARDIR. In the shorewallrc file, it referred to
the directory where all Shorewall product state would be stored
(default /var/lib). But in the code
and in shorewall-vardir(5), it referred to the directory where an
individual products state would be stored (e.g., /var/lib/shorewall).In Shorewall 4.5.8, the variable VARLIB was added to
shorewallrc. In that release, the shorewallrc files packaged with
the Shorewall products were changed to include these two
lines:VARLIB=/var/libVARDIR defaults to '${VARLIB}/${PRODUCT}' if VARLIB is
specified and VARDIR isn't.The consumers of shorewallrc were changed so that if there is
no VARLIB setting, then VARLIB is set to $VARDIR and $VARDIR is set
to ${VARLIB}/${PRODUCT}. This allows existing
shorewallrc files to be used unchanged.configure ScriptThe configure script requires Bash 4.0 or later. Beginning
with Shorewall 4.5.2.1, a Perl version (configure.pl) of the script
is included for use by packagers that have to deal with systems with
earlier versions of Bash. The configure.pl script works identically
to the Bash version.The configure script creates a file named
shorewallrc in the current working directory.
This file is the default input file to the
install.sh scripts. It is run as follows:./configure[.pl] [
option=value ]
...The possible values for option are the same as those shown above
in the shorewallrc file. They may be specified in either upper or
lower case and may optionally be prefixed by '--'. To facilitate use
with the rpm %configure script, the following options are
supported:vendorAlias for host.sharedstatedirShorewall 4.5.2 - 4.5.7 Alias for vardir.Shorewall 4.5.8 and later. Alias for varlib.datadirAlias for sharedir.Note that %configure may generate option/value pairs that are
incompatible with the configure script. The current
%configure macro is:%configure \
CFLAGS="${CFLAGS:-%optflags}" ; export CFLAGS ; \
CXXFLAGS="${CXXFLAGS:-%optflags}" ; export CXXFLAGS ; \
FFLAGS="${FFLAGS:-%optflags}" ; export FFLAGS ; \
./configure --host=%{_host} --build=%{_build} \\\
--target=%{_target_platform} \\\
--program-prefix=%{?_program_prefix} \\\
--prefix=%{_prefix} \\\
--exec-prefix=%{_exec_prefix} \\\
--bindir=%{_bindir} \\\
--sbindir=%{_sbindir} \\\
--sysconfdir=%{_sysconfdir} \\\
--datadir=%{_datadir} \\\
--includedir=%{_includedir} \\\
--libdir=%{_libdir} \\\
--libexecdir=%{_libexecdir} \\\
--localstatedir=%{_localstatedir} \\\
--sharedstatedir=%{_sharedstatedir} \\\
--mandir=%{_mandir} \\\
--infodir=%{_infodir}
On Fedora 16, this expands to: CFLAGS="${CFLAGS:--O2 -g -march=i386 -mtune=i686}" ; export CFLAGS ;
CXXFLAGS="${CXXFLAGS:--O2 -g -march=i386 -mtune=i686}" ; export CXXFLAGS ;
FFLAGS="${FFLAGS:--O2 -g -march=i386 -mtune=i686}" ; export FFLAGS ;
./configure --host=i686-pc-linux-gnu --build=i686-pc-linux-gnu \
--program-prefix= \
--prefix=/usr \
--exec-prefix=/usr \
--bindir=/usr/bin \
--sbindir=/usr/sbin \
--sysconfdir=/etc \
--datadir=/usr/share \
--includedir=/usr/include \
--libdir=/usr/lib \
--libexecdir=/usr/libexec \
--localstatedir=/var \
--sharedstatedir=/var/lib \
--mandir=/usr/share/man \
--infodir=/usr/share/info
The value of --host does not
map to any of the valid HOST values in shorewallrc. So to use
%configure on a Fedora system, you want to invoke it as
follows:%configure --vendor=redhatTo reset the value of a setting in shorewallrc.$host, give it a
null value. For example, if you are installing on a RHEL derivative
that doesn't run systemd, use this command:./configure --vendor=redhat --systemd=Install for Packaging.If you build your own packages, then you will want to install
the Shorewall products into it's own directory tree. This is done by
adding DESTDIR to the installer's environment. For example, to install
a product for Debian into the /tmp/package directory:DESTDIR=/tmp/package ./install.sh shorewallrc.debianWhen DESTDIR is specified, the installers treat $DESTDIR as the
root of the filesystem tree. In other words, the created installation
is only runnable if one chroots to $DESTDIR. Please note that the
uninstall.sh scripts cannot uninstall a configuration installed with
non-empty DESTDIR.Install into a SandboxWhen DESTDIR is used, the resulting configuration is not
runnable, because all configuration pathnames are relative to
$DESTDIR. Beginning with Shorewall 4.6.4, you can create runnable
configurations separate from your main configuration. Here is a sample
shorewallrc file: INSTALL_DIR=/usr/local/shorewall-custom
HOST=suse
PREFIX=${INSTALL_DIR}
SHAREDIR=${INSTALL_DIR}/share
LIBEXECDIR=${INSTALL_DIR}/lib
PERLLIBDIR=${INSTALL_DIR}/lib/perl5
CONFDIR=${INSTALL_DIR}/etc
SBINDIR=${INSTALL_DIR}/usr/sbin
MANDIR=${SHAREDIR}/man/
INITDIR=${INSTALL_DIR}/etc/init.d
INITSOURCE=init.suse.sh
INITFILE=${PRODUCT}
AUXINITSOURCE=
AUXINITFILE=
SYSTEMD=${INSTALL_DIR}/etc/systemd
SERVICEFILE=${PRODUCT}.service
SYSCONFFILE=sysconfig
SYSCONFDIR=${INSTALL_DIR}/etc/sysconfig
SPARSE=
ANNOTATED=
VARLIB=${INSTALL_DIR}/var/lib
VARDIR=${VARLIB}/${PRODUCT}
SANDBOX=YesThe above shorewallrc creates a runnable configuration in
/usr/local/shorewall-custom. It is triggered by adding SANDBOX to the
shorewallrc file -- any non-empty value for that variable will prevent
the installer from replacing the current main configuraiton.Versions 4.5.1 and EarlierBeginning with Shorewall-4.5.0, the Shorewall packages depend on
Shorewall-core. So the first step is to install that package:unpack the tarballs:tar -jxf shorewall-core-4.5.0.tar.bz2cd to the shorewall directory (the version is encoded in the
directory name as in shorewall-core-4.5.0).Type:./install.sh To install Shorewall using the tarball and install script:unpack the tarballs:tar -jxf shorewall-4.5.0.tar.bz2cd to the shorewall directory (the version is encoded in the
directory name as in shorewall-4.3.5).Type:./install.sh or if you are installing Shorewall or Shorewall6 version 4.4.8
or later, you may type:./install.sh -sThe -s option suppresses
installation of all files in /etc/shorewall except
shorewall.conf. You can copy any other files
you need from one of the Samples or from /usr/share/shorewall/configfiles/.If the install script was unable to configure Shorewall to be
started automatically at boot, see these
instructions.Beginning with shorewall 4.4.20.1, the installer also supports a
(annotated) option. Beginning with that release, the
standard configuration files (including samples) may be annotated with
the contents of the associated manpage. The option
enables that behavior. The default remains that the configuration files
do not include documentation.Executables in /usr and Perl ModulesDistributions have different philosophies about the proper file
hierarchy. Two issures are particularly contentious:Executable files in
/usr/share/shorewall*. These include;getparamscompiler.plwait4ifupshorecapifupdownPerl Modules in
/usr/share/shorewall/Shorewall.To allow distributions to designate alternate locations for
these files, the installers (install.sh) from 4.4.19 onward support
the following environmental variables:LIBEXECDetermines where in /usr getparams, compiler.pl,
wait4ifup, shorecap and ifupdown are installed. Shorewall and
Shorewall6 must be installed with the same value of LIBEXEC. The
listed executables are installed in
/usr/${LIBEXEC}/shorewall*. The default
value of LIBEXEC is 'share'. LIBEXEC is recognized by all
installers and uninstallers.Beginning with Shorewall 4.4.20, you can specify an
absolute path name for LIBEXEC, in which case the listed
executables will be installed in ${LIBEXEC}/shorewall*.Beginning with Shorewall 4.5.1, you must specify an
absolute pathname for LIBEXEC.PERLLIBDetermines where in /usr the
Shorewall Perl modules are installed. Shorewall and Shorewall6
must be installed with the same value of PERLLIB. The modules
are installed in /usr/${PERLLIB}/Shorewall.
The default value of PERLLIB is 'share/shorewall'. PERLLIB is
only recognized by the Shorewall and Shorewall6
installers.Beginning with Shorewall 4.4.20, you can specify an
absolute path name for PERLLIB, in which case the Shorewall Perl
modules will be installed in ${PERLLIB}/Shorewall/.Beginning with Shorewall 4.5.1, you must specify an
absolute pathname for PERLLIB.MANDIRDetermines where the man pages are installed. Default is
distribution-dependent as shown below.Default Install LocationsThe default install locations are distribution dependent as
shown in the following sections. These are the locations that are
chosen by the install.sh scripts.All DistributionsCOMPONENTLOCATIONman pages/usr/share/man/ (may ve overridden using
MANDIR)Shorewall Perl Modules/usr/share/shorewall/ (may be overridden using
PERLLIB)Executable helper scripts (compiler.pl, getparams,
wait4ifup)/usr/share/shorewall/ (may be overridden using
LIBEXEC)ifupdown.sh (from Shorewall-init)/usr/share/shorewall-init/ (may be overridden using
LIBEXEC)DebianCOMPONENTLOCATIONCLI programs/sbin/productDistribution-specific configuration file/etc/default/productInit Scripts/etc/init.d/productifupdown scripts from Shorewall-init/etc/network/if-up.d/shorewall,
/etc/network/if-post-down.d/shorewallppp ifupdown scripts from Shorewall-init/etc/ppp/ip-up.d/shorewall,
/etc/ppp/ip-down.d/shorewall /etc/ppp/ipv6-up.d/shorewall
/etc/ppp/ipv6-down.d/shorewallRedhat and DerivativesCOMPONENTLOCATIONCLI programs/sbin/productDistribution-specific configuration file/etc/sysconfig/productInit Scripts/etc/rc.d/init.d/productifupdown scripts from Shorewall-init/sbin/ifup-local, /sbin/ifdown-localppp ifupdown scripts from Shorewall-init/etc/ppp/ip-up.local, /etc/ppp/ip-down.localSuSECOMPONENTLOCATIONCLI programs/sbin/productDistribution-specific configuration file/etc/sysconfig/productInit Scripts/etc/init.d/productifupdown scripts from Shorewall-init/etc/sysconfig/network/if-up.d/shorewall,
/etc/sysconfig/network/if-down.d/shorewallppp ifupdown scripts from Shorewall-init/etc/ppp/ip-up.d/shorewall,
/etc/ppp/ip-down.d/shorewall /etc/ppp/ipv6-up.d/shorewall
/etc/ppp/ipv6-down.d/shorewallCygwinCOMPONENTLOCATIONCLI programs/bin/productDistribution-specific configuration fileN/AInit ScriptsN/Aifupdown scripts from Shorewall-initN/Appp ifupdown scripts from Shorewall-initN/AOS XCOMPONENTLOCATIONCLI programs/sbin/productDistribution-specific configuration fileN/AInit ScriptsN/Aifupdown scripts from Shorewall-initN/Appp ifupdown scripts from Shorewall-initN/AInstall the .debOnce you have installed the .deb packages and before you attempt
to configure Shorewall, please heed the advice of Lorenzo Martignoni,
former Shorewall Debian Maintainer:For more information about Shorewall usage on Debian system
please look at /usr/share/doc/shorewall-common/README.Debian provided by
[the] shorewall Debian package.The easiest way to install Shorewall on Debian, is to use
apt-get.First, to ensure that you are installing the latest version of
Shorewall, please modify your
/etc/apt/preferences:Package: shorewall
Pin: release o=Debian,a=testing
Pin-Priority: 700
Package: shorewall-doc
Pin: release o=Debian,a=testing
Pin-Priority: 700Then
run:# apt-get update
# apt-get install shorewallOnce you have completed configuring
Shorewall, you can enable startup at boot time by setting startup=1 in
/etc/default/shorewall.General Notes about Upgrading ShorewallMost problems associated with upgrades come from two causes:The user didn't read and follow the migration considerations in
the release notes (these are also reproduced in the Shorewall Upgrade Issues).The user mis-handled the
/etc/shorewall/shorewall.conf file during
upgrade. Shorewall is designed to allow the default behavior of the
product to evolve over time. To make this possible, the design assumes
that you will not replace your current
shorewall.conffile during
upgrades. It is recommended that after you first install
Shorewall that you modify
/etc/shorewall/shorewall.conf so as to prevent
your package manager from overwriting it during subsequent upgrades
(since the addition of STARTUP_ENABLED, such modification is assured
since you must manually change the setting of that option). If you
feel absolutely compelled to have the latest options in your
shorewall.conf then you must proceed carefully. You should determine
which new options have been added and you must reset their value (e.g.
OPTION=""); otherwise, you will get different behavior from what you
expect.Upgrade using RPMIf you already have the Shorewall RPM installed and are upgrading to
a new version:Be sure that you have the correct RPM
package!The standard RPM package from shorewall.net and the mirrors is
known to work with SUSE, Power PPC, Trustix and
TurboLinux. There is also an RPM package provided by Simon Matter that
is tailored for RedHat/Fedora and another package from Jack Coates
that is customized for Mandriva. If you try to upgrade using the wrong
package, it probably won't work.Simon Matter names his 'common' rpm
'shorewall' rather than
'shorewall-common'.If you are upgrading from a 2.x or 3.x version to a 4.x version
or later, please see the upgrade
issues for specific instructions.Upgrade the RPMrpm -Uvh <shorewall rpm file> Shorewall is dependent on the iproute package. Unfortunately,
some distributions call this package iproute2 which will cause the
upgrade of Shorewall to fail with the diagnostic:error: failed dependencies:iproute is needed by shorewall-3.2.1-1This may be worked around by using the --nodeps option of
rpm.rpm -Uvh --nodeps <shorewall rpm> ...See if there are any incompatibilities between your
configuration and the new Shorewall version and correct as
necessary.shorewall checkRestart the firewall.shorewall restartUpgrade using tarballIf you are upgrading from a 2.x or 3.x version to a 4.x version
or later, please see the upgrade
issues for specific instructions.If you are upgrading to version 4.5.0 or later, you must first
install or upgrade the Shorewall-core package:unpack the tarballs:tar -jxf shorewall-core-4.5.0.tar.bz2cd to the shorewall directory (the version is encoded in the
directory name as in shorewall-core-4.5.0).Type:./install.sh If you already have Shorewall installed and are upgrading to a new
version using the tarball:unpack the tarball:tar -jxf shorewall-4.5.0.tar.bz2cd to the shorewall-perl directory (the version is encoded in
the directory name as in shorewall-4.5.0).Type:./install.shor if you are installing Shorewall or Shorewall6 version 4.4.8
or later, you may type:./install.sh -sThe -s option supresses
installation of all files in /etc/shorewall except
shorewall.conf. You can copy any other files you
need from one of the Samples
or from /usr/share/shorewall/configfiles/.See if there are any incompatibilities between your
configuration and the new Shorewall version and correct as
necessary.shorewall checkStart the firewall by typingshorewall startIf the install script was unable to configure Shorewall to be
started automatically at boot, see these
instructions.Upgrading the .debWhen the installer asks if you want to replace
/etc/shorewall/shorewall.conf with the new version, we strongly advise
you to say No. See above.Configuring ShorewallYou will need to edit some or all of the configuration files to
match your setup. In most cases, the Shorewall QuickStart Guides
contain all of the information you need.Uninstall/FallbackSee Fallback and
Uninstall.
shorewall-docs-xml-5.2.3/traffic_shaping_ru.xml 0000664 0000000 0000000 00000213115 13427347317 020342 0 ustar root root
Управление трафиком и шейпинг трафикаTomEastepArneBernin2001-2007Thomas M. Eastep2005Arne Bernin & Thomas M. Eastep2007Russian Translation: Grigory MokhinЭтот документ разрешается копировать, распространять и/или
изменять при выполнении условий лицензии GNU Free Documentation License
версии 1.2 или более поздней, опубликованной Free Software Foundation;
без неизменяемых разделов, без текста на верхней обложке, без текста на
нижней обложке. Копия лицензии приведена по ссылке GNU Free Documentation
License.Управление трафиком - это сложная тема, и не следует ожидать от
сообщества Shorewall готовых ответов на возникающие в связи с этим
вопросы. Поэтому, если вам нужны готовые рецепты, как нажать кнопку, чтобы
все заработало само, лучше даже не пытайтесь организовать управление
трафиком с помощью Shorewall. Вас ожидают неприятные разочарования, и вряд
ли кто-либо сможет вам помочь.Иначе говоря, чтение только документации Shorewall не будет
достаточным для понимания раскрываемых здесь тем.Как минимум, потребуется обратиться к следующим дополнительным
источникам:LARTC HOWTO: http://www.lartc.orgРуководство по HTB: http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htmНекоторые документы с сайта http://www.netfilter.org/documentation/index.html#documentation-howto.
Рекомендуем ознакомиться с очень хорошим руководством Оскара
Андреассона.Вывод команды man iptablesВведениеНачиная с версии 2.5.5 в Shorewall реализована встроенная поддержка
управления трафиком и шейпинга трафика. В более ранних версиях эти
возможности были ограниченными. Можно было использовать собственный
сценарий tcstart (это можно и сейчас), но, за исключением файла tcrules, в
файлах конфигурации Shorewall не была предусмотрена возможность
определения классов и дисциплин очередей.До сих пор поддержка управления трафиком является неполной,
например, не поддерживаются все опции (и особенно различные алгоритмы
очередей) из ядра Linux, но для большинства случаев она будет достаточной.
Если у вас уже есть сценарий для управления трафиком, который вы
собираетесь использовать и в будущем, то соответствующие инструкции
приведены по ссылке ниже в этом
документе. Для того чтобы это заработало, требуется включить
поддержку управления трафиком в ядре и в Shorewall, как описано
далее.Управление трафиком и шейпинг трафика в LinuxВ этом разделе кратко описано, как работает управление трафиком в
Linux. Даже если этого должно быть достаточно для настройки управления
трафиком в файлах конфигурации Shorewall, мы очень рекомендуем внимательно
прочитать руководство Linux Advanced
Routing and Shaping HOWTO. Во время написания этого документа
текущей версией была 1.0.0.Начиная с версии 2.2, в Linux реализованы полные возможности
управления трафиком. Предусмотрены различные алгоритмы, которые
применяются для приоритизации очередей пакетов, выходящих с интерфейса.
Стандартный алгоритм называется pfifo, и, как следует из самого названия,
это очередь типа первым пришел - первым ушел. Фактически при этом никакого
управления трафиком не происходит, и если какое-то соединение забивает
весь канал, то этот алгоритм не сможет этого предотвратить.Для управления трафиком в Shorewall используются два алгоритма, HTB
(иерархический набор маркеров) и SFQ (очередь с равноправным
стохастическим упорядочением). SFQ использует простую схему: отслеживаются
все соединения (tcp или udp), и трафик распределяется между ними. Обычно
это работает хорошо. HTB позволяет определить набор классов, между
которыми распределяется трафик. Для каждого класса можно указать
минимальную и максимальную полосу пропускания, а сами классы упорядочить в
иерархическую структуру, чтобы классы с меньшим приоритетом получали
доступ к каналу только в том случае, если запросы более важных классы
удовлетворены. Встроенные функции управления трафиком в Shorewall
позволяют определить такие классы и указать для них полосу пропускания.
Внутри самих классов используется SFQ, чтобы их различные внутренние
потоки данных обрабатывались как равноправные.Управлять можно только исходящим трафиком.
Причина этого состоит в том, что входящие пакеты уже пришли на сетевую
плату, и нужно решить, что с ними делать. Их можно только
сбросить, но особого смысла в этом не будет, поскольку пакет уже пришёл,
пройдя через узкое место - входящий канал. Следующим узким местом может
быть интерфейс, с которого уходит этот пакет, и именно на нём может
образовываться очередь. Поэтому определение очередей для входящих пакетов
не будет особенно полезным, эти пакеты просто нужно передать как можно
быстрее на исходящий интерфейс.Есть одно исключение. Если ограничить входящий трафик значением чуть
меньшим, чем фактическая пропускная способность канала, то будет исключено
образование очередей на другом конце соединения. Это бывает полезно, если
управление потоком на другом конце канала невозможно, а сам он подключен к
сети по более быстрому каналу, например, если вы подключены к провайдеру
по кабельному модему или модему DSL, а маршрутизатор провайдера подключен
к быстрому магистральному каналу. Поэтому, если отбрасывать слишком быстро
приходящие пакеты, то основной протокол сможет это обнаружить и снизить
скорость соединения. В TCP такой механизм встроен, в UDP не встроен, но
протокол, работающий поверх UDP, может иметь такой механизм.В таких случаях создание очередей будет иметь неприятные
последствия, если есть пакеты, которые должны проходить в первую очередь,
как, например, VoIP или ssh. Для таких соединений важно, чтобы пакеты
проходили с минимальной задержкой. Для других пакетов, таких как загрузка
по HTTP, задержка на несколько секунд не будет иметь значения.Если на другом конце канала образуется очередь, а маршрутизатор не
поддерживает QoS или биты QoS настроены неверно, то пакеты, для которых
важна минимальная задержка, будут ждать в той же очереди, что и менее
важные пакеты загрузки по HTTP, и задержка может быть большой.Управление исходящим трафиком достигается посредством распределения
потока пакетов по классам. Класс связан ровно с
одним сетевым интерфейсом и имеет ряд атрибутов:PRIORITY - используется для указания приоритетов классов, к
которым относятся отправляемые пакеты. Приоритет - это число, при этом
1 задаёт наивысший приоритет, 2 - следующий по важности и т.д.RATE - скорость, то есть минимальная гарантированная пропускная
способность, которая должна обеспечиваться для класса, когда
возрастает нагрузка на канал. Классы с более высоким приоритетом
(меньшие значения PRIORITY) обслуживаются даже в том случае, если
заданы другие классы с гарантированной пропускной способностью, но
низшим приоритетом (большие значения PRIORITY).CEIL - ограничение, максимальная полоса пропускания, которая
отводится для класса, когда канал свободен.MARK - метка. В Netfilter предусмотрены способы
маркировки пакетов. Метки пакетов - это числа.
В Shorewall они могут принимать значение от 1 до 255. Метки пакетов
присваиваются различным типам пакетов согласно правилам, заданным в
файле /etc/shorewall/tcrules.Для каждого интерфейса необходимо задать один класс, который будет
классом по умолчанию. К этому классу будут
относиться непомеченные данные, то есть пакеты, для которых не задана
метка в файле /etc/shorewall/tcrules.Netfilter также поддерживает метки соединений. Метки соединений
можно присвоить соединениям в правилах
/etc/shorewall/tcrules, можно скопировать метку
пакета в метку соединения (SAVE), или скопировать метку соединения в метку
пакета (RESTORE).Конфигурация ядра LinuxДля работы требуется ядро не ниже 2.4.18. На рисунке показаны опции
ядра, которые необходимо включить. Для встроенной поддержки необходимы
опции HTB scheduler, Ingress scheduler, PRIO pseudoscheduler и SFQ queue.
Прочие планировщики или алгоритмы очередей необязательны.Также требуются классификаторы u32 и fw из главного меню Networking
Options (не показаны).На следующем рисунке показано, как я настроил QoS у себя в ядре
2.6.13:Конфигурация ядра изменилась в 2.6.16 -- вот мои
рекомендации.Включение поддержки TC в ShorewallПоддержку TC требуется включить независимо от того, применяются ли
встроенные функции или вы используете собственный сценарий tcstart.Для включения встроенных функций управления трафиком в Shorewall
выполните следующее:Задайте TC_ENABLED равным
"Internal" в /etc/shorewall/shorewall.conf. Если TC_ENABLED=Yes, то
Shorewall будет искать внешний файл tcstart (см. далее).Если задать параметр CLEAR_TC в
/etc/shorewall/shorewall.conf равным Yes, то при запуске, перезапуске
и остановке Shorewall будет сбрасываться текущая конфигурация
управления трафиком. Обычно именно это и требуется при работе с
встроенными функциями, а также с собственным сценарием tcstart.Следующие действия зависят от того, применяются ли встроенные
функции или собственный сценарий. Подробнее это объясняется в
следующих разделах.Работа с встроенными функциями управления трафиком и
шейпингаВстроенные в Shorewall функции управления трафиком - это тонкая
оболочка для очереди входящих пакетов (ingress qdisc), HTB и SFQ. Эта
оболочка позволяет выполнить следующие задачи:Определить классы HTB в файлах конфигурации Shorewall.Включить загрузку конфигурации управления трафиком вместе с
загрузкой правил фильтрации пакетов и правил для меток.Распределить пакеты по классам HTB согласно значениям
TOS.Отнести исходящие пакеты TCP ACK к классу HTB.Распределить пакеты по классам HTB согласно значениям меток
пакетов.Встроенные в Shorewall функции управления трафиком ограничены
десятью (10) устройствами.Больше никаких задач встроенные функции управления трафиком не
выполняют. Поэтому, чтобы их использовать, необходимо понимать, как
работает HTB и управление трафиком в Linux, и как работают метки пакетов
Netfilter. За дополнительной информацией обратитесь к ссылкам, приведенным
в начале этого документа.Для задания пропускной способности (как устройств, так и классов)
используйте kbit или kbps (для килоБАЙТ в секунду) БЕЗ пробела между числом и единицей измерения (то
есть 100kbit НО НЕ 100 kbit). Можно также
использовать mbit, mbps или число (означающее байты), но поддерживаются
только целые числа (0.5 использовать нельзя).Для того чтобы правильно настроить устройства, необходимо выяснить
фактическую пропускную способность канала в обоих направлениях. Это
особенно важно для соединений DSL или любых других, для которых пропускная
способность канала не гарантирована. Не верьте числам, которые называет
провайдер, но сами измерьте реальную скорость канала. В этом могут помочь
различные утилиты в сети, попробуйте поискать "dsl speed test" в google
(для Германии можно использовать arcor speed
check). Найдите тест поближе к себе./etc/shorewall/tcdevicesВ этом файле можно задать пропускную способность способность
канала для устройств, для которых будет включено управление трафиком.
Это означает, что в этом файле необходимо определить параметры для
устройства, чтобы для него заработало управление трафиком.Далее описаны столбцы файла:INTERFACE - Имя интерфейса. Интерфейс может быть указан не
более одного раза. Использовать псевдоним интерфейса (например,
eth0:0) здесь нельзя, см. FAQ
#18. Также нельзя использовать символы подстановки,
например, если есть несколько интерфейсов ppp, то все их необходимо
здесь перечислить. В версиях Shorewall до 3.0.8 и 3.2.0 Beta 8,
устройство, имя которого указано в столбце, должно было существовать
в момент запуска, перезапуска или обновления Shorewall. Начиная с
версии 3.0.8 и 3.2.0 Beta 8 Shorewall может определить, существует
ли устройство, и настроит его только в том случае, если оно
существует. Если оно не существует, то будет показано следующее
предупреждение:WARNING: Device <устройство> not
found -- traffic-shaping configuration skippedIN-BANDWIDTH - Пропускная способность входящего канала для
этого интерфейса. Обратите внимание, что шейпинг входящего трафика
невозможен, так как пакеты уже пришли. В этом столбце можно задать
максимальную скорость, разрешенную для этого интерфейса, при
превышении которой пакеты будут отбрасываться. Это полезно главным
образом для соединений DSL или кабельных, чтобы избежать очередей в
устройствах провайдера. Если не следует отбрасывать никакие пакеты,
то укажите значение, превышающее фактическую максимальную скорость
канала (в Shorewall начиная с версии 3.2.6 можно также указать
0).Для того чтобы определить оптимальное значение, укажите
сначала значение, которое заведомо ниже, чем измеренная скорость
канала (процентов на 20). Далее, в ходе загрузки файлов, измеряйте
время ответа на ping между своей системой и
маршрутизатором провайдера и постепенно увеличивайте это значение.
Оптимальным будет значение, при превышении которого время ответа на
ping будет резко расти.OUT-BANDWIDTH - Пропускная способность исходящего канала для
этого интерфейса. Это максимальная скорость, с которой может
работать исходящее соединение. В терминах классов tc эта скорость
называется полной (full). Превышающий эту скорость исходящий трафик
будет отбрасываться.Предположим, что вы работаете с PPP по Ethernet (DSL), а
интерфейс - это ppp0. Устройство имеет исходящую скорость 500 кбит и
входящую - 6000 кбит#INTERFACE IN-BANDWITH OUT-BANDWIDTH
ppp0 6000kbit 500kbit/etc/shorewall/tcclassesВ этом файле можно задать классы, по которым будет распределяться
исходящий трафик.INTERFACE - Имя интерфейса. Должно совпадать с именем
интерфейса в файле
/etc/shorewall/tcdevices.MARK - метка. Должна быть целым числом от 1 до 255. Эти метки
задаются в файле tcrules. Они помечают пакеты, которые тем самым
будут отнесены к определенным здесь классам очередей. Одни и те же
метки могут использоваться для разных интерфейсов.RATE - скорость, то есть минимальная гарантированная
пропускная способность, которая должна обеспечиваться для класса,
когда возрастает нагрузка на канал. Классы с более высоким
приоритетом обслуживаются даже в том случае, если заданы другие
классы с гарантированной пропускной способностью, но низшим
приоритетом. Если сумма значений RATE для всех
классов, присвоенных интерфейсу, превышает OUT-BANDWIDTH для
интерфейса, то предел OUT-BANDWIDTH не будет
соблюдаться.CEIL - ограничение, максимальная полоса пропускания, которая
отводится для данного класса, когда канал свободен. Это полезно,
если есть трафик, для которого будет выделяться полная скорость
канала, если более важные службы (такие как ssh) не используются.
Значение "full" означает, что максимальная пропускная способность
для класса определяется значением, заданным для интерфейса.PRIORITY - позволяет указать приоритет для класса. Пакеты из
класса с более высоким приоритетом (то есть меньшим значением) будут
обрабатываться раньше, чем пакеты с низшим приоритетом. Здесь можно
просто указать значение метки, если метки присваиваются согласно
приоритетам.OPTIONS - Список параметров через запятую. Возможны следующие
параметры:default - класс по умолчанию для интерфейса, к которому
будет отнесен весь трафик, не отнесенный к другим
классам.Необходимо указать default ровно для одного класса для интерфейса.tos-<имя-tos> - позволяет указать фильтр для
заданного <имени-tos>, что в свою очередь позволяет
определить значение бит Type Of Service в пакете ip, вследствие
чего пакет будет отнесен к этому классу. Учтите, что этот фильтр
переопределяет все заданные метки, поэтому, если задать фильтр
tos для класса, то все пакеты, имеющие эту метку, войдут в этот
класс независимо от того, какая у них уже есть метка. Возможные
значения этого параметра: tos-minimize-delay (16)
tos-maximize-throughput (8) tos-maximize-reliability (4)
tos-minimize-cost (2) tos-normal-service (0)Каждая из этих опций применима только для одного класса интерфейса.tcp-ack - эта опция создает фильтр tc и класс, в который
помещаются все пакеты tcp ack на этом интерфейсе, размер которых
не превышает 64 байта. Это позволяет ускорить загрузку.
Ограничение размера пакетов ack 64 байтами служит для того,
чтобы исключить из этого класса все приложения (например, p2p),
которые помечают каждый пакет как пакет ack. Этому фильтру
должны соответствовать только пакеты БЕЗ дополнительной
нагрузки, отсюда и ограничение размера. Пакеты большего размера
будут отнесены в другие классы.Эта опция применима только для одного класса интерфейса./etc/shorewall/tcrulesКлассификатор fwmark является удобным средством для классификации
пакетов при управлении трафиком. В файле
/etc/shorewall/tcrules эти метки представлены в виде
таблицы. Глубже познакомиться с маркировкой пакетов в
Netfilter/Shorewall позволяет этот
документ.Обычно метка пакета ставится в цепочке PREROUTING перед тем, как
осуществляется замена адресов. При этом невозможно помечать входящие
пакеты согласно их целевому адресу, если применяется SNAT или
Masquerading. Тем не менее, можно осуществлять маркировку пакетов в
цепочке FORWARD, если задать опцию MARK_IN_FORWARD_CHAIN в файле
shorewall.conf.Далее описаны столбцы файла:MARK или CLASSIFY - MARK задает значение метки, которая
присваивается пакету в случае совпадения с правилом. Она должна быть
целым числом от 1 до 255. Вслед за этим значением может идти
: и одно из значений: F,
P или "T", которые обозначают соответственно
маркировку в цепочках FORWARD, PREROUTING или POSTROUTING. Если эти
дополнительные спецификаторы опущены, то цепочка, в которой
осуществляется маркировка пакетов, определяется следующим
образом:Если SOURCE - это
$FW[:<адрес>], то правило вставляется
в цепочку OUTPUT.В противном случае цепочка определяется по значению опции
MARK_IN_FORWARD_CHAIN из файла shorewall.conf.Спецификатор "T" был добавлен в Shorewall версии 3.3.6 и
недоступен в более ранних версиях.Обычно метка присваивается пакету. Если вслед за меткой
указать ":" и "C", то метка будет применяться к соединению. "C"
можно сочетать с "F", "P" или "T", чтобы указать, что соединение
следует пометить в определенной цепочке (например, "CF", "CP",
"CT").Предусмотрены также следующие специальные значения:RESTORE[/маска] --
восстановить метку пакета из метки соединения, используя маску,
если она указана. Ядро и iptables должны поддерживать
CONNMARK.Как и ранее, можно использовать дополнительные
спецификаторы :P, :F или :T.SAVE[/маска] --
сохранить метку пакета в метке соединения, используя маску, если
она указана. Ядро и iptables должны поддерживать
CONNMARK.Как и ранее, можно использовать дополнительные
спецификаторы :P, :F или :T.CONTINUE - прекратить
обработку дальнейших правил маркировки в таблице.Как и ранее, можно использовать дополнительные
спецификаторы :P, :F или :T.COMMENT (Начиная с
Shorewall версии 3.3.3) -- остальной текст в строке будет
добавлен как комментарий в правила Netfilter, генерируемые по
следующим записям. Комментарий будет выделен символам "/* ...
*/" в выводе команды shorewall show
mangleДля того чтобы комментарий не применялся к последующим
строкам, укажите COMMENT в отдельной строке.При работе с CLASSIFY ядро и iptables должны поддерживать
CLASSIFY. В этом случае в столбце будет содержаться классификатор
(classid) в виде <основной>:<дополнительный>, где
<основной> и <дополнительный> должны быть целыми
числами. Он соответствует указанию 'class' в следующих модулях
управления трафиком:atmcbqdsmarkpfifo_fasthtbprioВ версиях Shorewall до 3.2.3 правила классификации всегда
помещались в цепочку POSTROUTING. Начиная с Shorewall версии 3.2.3
классификация осуществляется в цепочке POSTROUTING, кроме тех случаев, когда SOURCE содержит
$FW[:<адрес>], для которых классификация
осуществляется в цепочке OUTPUT. При работе со встроенными функциями
управления трафиком класс <основной> - это номер устройства
(первая запись в файле /etc/shorewall/tcdevices
- это устройство 1, вторая - устройство 2 и т.д.), а класс
<дополнительный> - это значение MARK класса, перед которой
стоит число "1" (для MARK со значением 1 <дополнительный>
класс - это 11, для MARK со значением 22 - <дополнительный>
класс 122, и т.д.).SOURCE - источник пакета. Это может быть разделенный запятыми
список имен интерфейсов, IP-адресов, MAC-адресов и/или подсетей для
пакетов, маршрутизируемых по общему пути. Элементы списка могут
также включать имя интерфейса, к которому прибавлено ":" и адрес
(например, eth1:192.168.1.0/24). Так, все пакеты для соединений,
маскируемых через eth0 с других интерфейсов, можно описать одним
правилом с несколькими критериями SOURCE. Однако соединение, пакеты
которого приходят на eth0 по другому пути, например, из самой
системы файрвола, требуют отдельного правила.Поэтому создавайте отдельное правило с $FW для пакетов,
исходящих из системы файрвола. В таком правиле столбец MARK не может
содержать ":P" или ":F", поскольку маркировка пакетов, исходящих из
системы файрвола, всегда осуществляется в цепочке OUTPUT.MAC-адреса необходимо предварять символом "~" и использовать
"-" как разделитель.Пример: ~00-A0-C9-15-39-78DEST - назначение пакета. Список IP-адресов и/или подсетей,
разделенный запятыми. Если ядро и iptables поддерживают iprange, то
можно также указывать диапазоны IP-адресов. Элементы списка могут
также включать имя интерфейса, к которому прибавлено ":" и адрес
(например, eth1:192.168.1.0/24). Если в столбце MARK указан
спецификатор в виде <основной>:<дополнительный>, то
столбец может также содержать имя интерфейса.PROTO - протокол. Должен быть указан как "tcp", "udp", "icmp",
"ipp2p", "ipp2p:udp", "ipp2p:all", число или "all". Для "ipp2p"
требуется поддержка ipp2p в ядре и iptables.PORT(S) - целевые порты. Список имен портов (из
/etc/services), номеров портов или диапазонов портов, разделенный
запятыми. Если протокол - это "icmp", то столбец считается целевым
типом icmp.Если протокол - это ipp2p, то столбец интерпретируется как
опция ipp2p без начального "--" (например, "bit" для bit-torrent).
Если PORT не указан, предполагается "ipp2p".Этот поле игнорируется, если PROTOCOL = all, но должно быть
указано, если задано любое из последующих полей. В этом случае
рекомендуется указывать в этом поле "-"CLIENT PORT(S) - необязательные порты, применяемые клиентом.
Если они не указаны, то допускается любой целевой порт. Задается как
список, разделенный запятыми, имен портов, номеров портов или
диапазонов портов.USER/GROUP (Начиная с Shorewall версии 1.4.10) -
Необязательный параметр имени пользователя или группы. Он может
указываться, только если SOURCE - это сама система файрвола. Если
значение поля задано, то правило применяется только в том случае,
если программа, создавшая пакет, работает от имени указанного
пользователя и/или группы. Возможные значения:[!][<имя пользователя или номер>]:[<имя группы или
номер>][+<имя программы>]Двоеточие указывать необязательно, если задано только имя
пользователя.Примеры:joe # программа должна выполняться пользователем joe
:kids # программа выполняется участниками группы 'kids'
!:kids # программа выполняется участниками группы 'kids'
+upnpd # программа upnpd (эта функция была удалена из Netfilter в версии ядра 2.6.14).TEST - задает тест для проверки существующей метки пакета или
соединения. Правило будет совпадать только в том случае, если тест
возвращает true. Тесты имеют следующий формат:
[!]<значение>[/<маска>][:C]Здесь:! Обратное соответствие (не равно)<значение> Значение метки соединения или
пакета.<маска> Маска, применяемая к метке перед
сравнением:C обозначает метку соединения. Если она не указана, то
сравнивается метка пакета.LENGTH - длина пакета (необязательный параметр, начиная с
Shorewall версии 3.2.0). Если указано это значение, то сравнивается
длина пакета с указанным значением или диапазоном значений. Диапазон
задается в виде <мин>:<макс>, где можно опустить или
<мин>, или <макс>, но не оба эти параметра. Если опущен
<мин>, то он считается равным 0, если опущен <макс>, то
совпадающим будет любой пакет, длина которого не меньше
<мин>.Для этой опции необходима поддержка сравнения длины в
iptables. Если значение не указано или задано как "-", то сравнение
длины не выполняется.Примеры: 1024, 64:1500, :100TOS - тип обслуживания (необязательный параметр, начиная с
Shorewall версии 3.2.0 Beta 6). Стандартное имя или число.
Все пакеты, приходящие на eth1, должны иметь метку 1. Все
пакеты, приходящие на eth2 и eth3, должны иметь метку 2. Все пакеты,
созданные в системе файрвола, должны иметь метку 3.#MARK SOURCE DESTINATION PROTOCOL PORT(S)
1 eth1 0.0.0.0/0 all
2 eth2 0.0.0.0/0 all
2 eth3 0.0.0.0/0 all
3 $FW 0.0.0.0/0 allВсе пакеты GRE (протокол 47), не созданные в системе файрвола и
имеющие целевой адрес 155.186.235.151, должны иметь метку 12.#MARK SOURCE DESTINATION PROTOCOL PORT(S)
12 0.0.0.0/0 155.182.235.151 47Все пакеты SSH, приходящие с 192.168.1.0/24 и предназначенные
для 155.186.235.151, должны иметь метку 22.#MARK SOURCE DESTINATION PROTOCOL PORT(S)
22 192.168.1.0/24 155.182.235.151 tcp 22Все пакеты SSH, проходящие через первое устройство в файле
/etc/shorewall/tcdevices, должны быть отнесены в класс с меткой
10.#MARK SOURCE DESTINATION PROTOCOL PORT(S) CLIENT
# PORT(S)
1:110 0.0.0.0/0 0.0.0.0/0 tcp 22
1:110 0.0.0.0/0 0.0.0.0/0 tcp - 22Все пакеты echo ICMP должны иметь метку 1. Весь трафик
протоколов p2p должен иметь метку 4.Это чуть более сложный случай. Поскольку модуль ipp2p не в
состоянии распознать все пакеты в соединении как пакеты P2P, то все
соединение помечается как P2P, если совпадение найдено хотя бы для
одного пакета. Предполагается, что метка пакета/соединения 0 означает
неклассифицированные пакеты.#MARK SOURCE DESTINATION PROTOCOL PORT(S) CLIENT USER/ TEST
# PORT(S) GROUP
1 0.0.0.0/0 0.0.0.0/0 icmp echo-request
1 0.0.0.0/0 0.0.0.0/0 icmp echo-reply
RESTORE 0.0.0.0/0 0.0.0.0/0 all - - - 0
CONTINUE 0.0.0.0/0 0.0.0.0/0 all - - - !0
4 0.0.0.0/0 0.0.0.0/0 ipp2p:all
SAVE 0.0.0.0/0 0.0.0.0/0 all - - - !0Последние четыре правила означают следующее:
"Если пакет не был классифицирован (метка пакета 0), то
скопировать метку соединения в метку пакета. Если метка пакета уже
задана, то никаких действий более не требуется. Если пакет относится
к типу P2P, то задать метку пакета 4. Если метка пакета задана, то
сохранить ее в качестве метки соединения."
Устройства pppЕсли подключение к провайдеру выполняется через ppp/pppoe/pppoa, и
вы используете управление трафиком, то необходимо перезапустить
управление трафиком shorewall. Причина этого состоит в том, что если
соединение ppp перезапускается (обычно это происходит как минимум раз в
день), то все фильтры и qdisc tc, связанные с этим
интерфейсом, будут удалены.Самым простым решением будет перезапуск shorewall при повторном
установлении соединения. Для этого добавьте в сценарий
/etc/ppp/ip-up.d следующую строку.#! /bin/sh
/sbin/shorewall refreshРабочие примерыКонфигурация для замены WondershaperВстроенные функции управления трафиком позволяют полностью
заменить сценарий wondershaper. Примеры файлов конфигурации приведены
по адресу "http://www1.shorewall.net/pub/shorewall/Samples/tc4shorewall/.
Обратите внимание, что эти примеры необходимо настроить, чтобы они
работали в вашей среде. В них предполагается, что интерфейс соединения
с провайдером - это ppp0 (для DSL), и для другого типа соединения его
необходимо изменить. Также требуется изменить параметры в файле
tcdevices.wondershaper, чтобы они отвечали фактической скорости
канала. Ниже приведены соответствующие строки из файлов конфигурации.
В итоге получается точная замена того, что должен делать wondershaper.
Но вы можете и вносить улучшения...Файл tcdevices#INTERFACE IN-BANDWITH OUT-BANDWIDTH
ppp0 5000kbit 500kbitФайл tcclasses#INTERFACE MARK RATE CEIL PRIORITY OPTIONS
ppp0 1 full full 1 tcp-ack,tos-minimize-delay
ppp0 2 9*full/10 9*full/10 2 default
ppp0 3 8*full/10 8*full/10 2Файл tcrules#MARK SOURCE DEST PROTO PORT(S) CLIENT USER
# PORT(S)
1:F 0.0.0.0/0 0.0.0.0/0 icmp echo-request
1:F 0.0.0.0/0 0.0.0.0/0 icmp echo-reply
# метка для трафика с низким приоритетом:
# mldonkey
3 0.0.0.0/0 0.0.0.0/0 udp - 4666Wondershaper позволяет определить набор хостов и/или портов,
которым присваивается низкий приоритет. Для этого в tcrules этим
хостам нужно присвоить метку 3 (как это делается в примерах файлов
конфигурации).Присвоение низкого приоритета хостамДопустим, что в сценарии wondershaper были следующие параметры
(только в качестве примера):
# Низкий приоритет для исходящего трафика - можно оставить пустым,
# чтобы применять сетевые маски для низкого приоритета
NOPRIOHOSTSRC="192.168.1.128/25 192.168.3.28"
# Низкий приоритет - маска для назначения
NOPRIOHOSTDST=60.0.0.0/24
# Низкий приоритет - порты источника
NOPRIOPORTSRC="6662 6663"
# Низкий приоритет - порты назначения
NOPRIOPORTDST="6662 6663"Эти параметры будут отражены следующим образом в файле
tcrules:3 192.168.1.128/25 0.0.0.0/0 all
3 192.168.3.28 0.0.0.0/0 all
3 0.0.0.0/0 60.0.0.0/24 all
3 0.0.0.0/0 0.0.0.0/0 udp 6662,6663
3 0.0.0.0/0 0.0.0.0/0 udp - 6662,6663
3 0.0.0.0/0 0.0.0.0/0 tcp 6662,6663
3 0.0.0.0/0 0.0.0.0/0 tcp - 6662,6663Простая конфигурацияНиже приведен простой пример для общего подключения к Интернет с
разных компьютеров. Фактически здесь настроен шейпинг для двух хостов
с IP-адресами 192.168.2.23 и 192.168.2.42Файл tcdevices#INTERFACE IN-BANDWITH OUT-BANDWIDTH
ppp0 6000kbit 700kbitКанал имеет входящие 6 мбит и исходящие 700 кбит.Файл tcclasses#INTERFACE MARK RATE CEIL PRIORITY OPTIONS
ppp0 1 5*full/10 full 1 tcp-ack,tos-minimize-delay
ppp0 2 3*full/10 9*full/10 2 default
ppp0 3 2*full/10 8*full/10 2Добавляется класс для пакетов tcp ack с высоким приоритетом,
чтобы ускорить загрузку. Следующие два класса совместно используют
большую часть пропускной способности канала для двух хостов, и если
соединение свободно, то всю пропускную способность. Так как хосты
считаются равноправными, они имеют одинаковый приоритет. Последний
класс предназначен для остального трафика.Файл tcrules#MARK SOURCE DEST PROTO PORT(S) CLIENT USER
# PORT(S)
1:F 0.0.0.0/0 0.0.0.0/0 icmp echo-request
1:F 0.0.0.0/0 0.0.0.0/0 icmp echo-reply
2:F 192.168.2.23 0.0.0.0/0 all
3:F 192.168.2.42 0.0.0.0/0 allПакеты ping icmp и ответы помечаются отдельно, как относящиеся
к интерактивному классу. Для них метка ставится для обоих
хостов.Замечания для пользователей XenЕсли управление трафиком включено в dom0, но исходящий трафик при
этом шейпится неправильно, то причиной этого может быть "выгрузка
контрольных сумм" (checksum offloading) в ваших domU. Просмотрите вывод
команды "shorewall show tc". Ниже приведен пример:class htb 1:130 parent 1:1 leaf 130: prio 3 quantum 1500 rate 76000bit ceil 230000bit burst 1537b/8 mpu 0b overhead 0b cburst 1614b/8 mpu 0b overhead 0b level 0
Sent 559018700 bytes 75324 pkt (dropped 0, overlimits 0 requeues 0)
rate 299288bit 3pps backlog 0b 0p requeues 0
lended: 53963 borrowed: 21361 giants: 90174
tokens: -26688 ctokens: -14783В приведенном примере легко обнаружить две проблемы:Скорость (299288) заметно превышает установленный предел
(230000).Сообщается о большом числе огромных пакетов (90174).Эта неполадка устраняется выключением "checksum offloading" в domU с
помощью программы ethtool. За инструкциями обратитесь к
статье по Xen.Применение собственных сценариев tcЗамена встроенного файла tcstartЕсли вы предпочитаете сами создать файл запуска tc, просто
поместите его в /etc/shorewall/tcstart.В сценарии tcstart вместо вызова программы tc
используйте функцию run_tc из Shorewall, чтобы при ошибке tc остановить
файрвол.Задайте TC_ENABLED=Yes и CLEAR_TC=YesУкажите сценарий /etc/shorewall/tcstart с правилами управления
трафиком.Укажите также необязательный сценарий /etc/shorewall/tcclear
для остановки управления трафиком. Обычно это не требуется.Если сценарий tcstart применяет классификатор
fwmark, то можно помечать пакеты, используя записи из
/etc/shorewall/tcrules.Управление трафиком, внешнее по отношению к ShorewallДля того чтобы запустить управление трафиком при поднятии сетевых
интерфейсов, необходимо запустить сценарий управления трафиком именно в
этот момент. Это зависит от применяемого дистрибутива и здесь не
описывается. После этого сделайте следующее:Задайте TC_ENABLED=No и CLEAR_TC=NoЕсли сценарий применяет классификатор fwmark,
то можно помечать пакеты, используя записи из
/etc/shorewall/tcrules.Инструменты тестированияКак минимум один пользователь Shorewall посчитал полезными следующие
инструменты: http://e2epi.internet2.edu/network-performance-toolkit.html
shorewall-docs-xml-5.2.3/Shorewall_Doesnt.xml 0000664 0000000 0000000 00000006654 13427347317 017771 0 ustar root root
Some Things that Shorewall Does Not DoTomEastep2003-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 3.0 and
later. If you are running a version of Shorewall earlier than Shorewall
3.0.0 then please see the documentation for that releaseShorewall Does not:Act as a Personal Firewall that allows Internet
access control by application. If that's what you are looking for, try
TuxGuardian.Work with an Operating System other than Linux (version >=
2.4.0)Act as a Proxy (although it can be used with a separate proxy
such as Squid or Socks).Do content filtering:HTTP - better to use Squid, E2guardian, or Parental
Control for that.Email -- Install something like Postfix on your firewall and
integrate it with SpamAssassin , Amavisd-new and
ClamavConfigure/manage Network Devices (your Distribution includes
tools for that).In Addition:Shorewall generally does not contain any support for Netfilter
xtables-addons
features -- Shorewall only supports features from released kernels
except in unusual cases.
shorewall-docs-xml-5.2.3/PacketMarking.xml 0000664 0000000 0000000 00000071033 13427347317 017226 0 ustar root root
Packet Marking using /etc/shorewall/mangle and
/etc/shorewall/tcrulesTomEastep20062013Thomas 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 includes information that applies to Shorewall version
3.2.5 and later. Not all features described here will be available in
earlier releases./etc/shorewall/mangle superseded /etc/shorewall/tcrules in Shorewall
4.6.0. /etc/shorwall/tcrules is still supported but its use is
deprecated.Packet and Connection MarksPerhaps no aspect of Shorewall causes more confusion than packet
marking. This article will attempt to clear up some of that
confusion.Each packet has a mark whose value is initially 0. Mark values are
stored in the skb (socket buffer) structure used by
the Linux kernel to track packets; the mark value is not part of the
packet itself and cannot be seen with tcpdump,
ethereal or any other packet sniffing program. They can
be seen in an iptables/ip6tables trace -- see the
iptrace command in shorewall(8) and shorewall6(8).Example (output has been folded for display ):[11692.096077] TRACE: mangle:tcout:return:3 IN= OUT=eth0 SRC=172.20.1.130
DST=206.124.146.254 LEN=84 TOS=0x00 PREC=0x00 TTL=64
ID=0 DF PROTO=ICMP TYPE=8 CODE=0 ID=7212 SEQ=3 UID=0
GID=1000 MARK=0x10082Each active connection (even those that are not yet in ESTABLISHED
state) has a mark value that is distinct from the packet marks. Connection
mark values can be seen using the shorewall show
connections command. The default connection mark value is
0.Example (output has been folded for display ):shorewall show connections
Shorewall 3.3.2 Connections at gateway - Mon Oct 2 09:08:18 PDT 2006
tcp 6 19 TIME_WAIT src=206.124.146.176 dst=192.136.34.98 sport=58597 dport=80
packets=23 bytes=4623 src=192.136.34.98 dst=206.124.146.176 sport=80 dport=58597
packets=23 bytes=22532 [ASSURED] mark=256 use=1
…Packet marks are valid only while the packet is being processed by
the firewall. Once the packet has been given to a local process or sent on
to another system, the packet's mark value is no longer available.
Connection mark values, on the other hand, persist for the life of the
connection.Other parts of the system such as Traffic Shaping and Policy Routing cannot use connection marks —
they can only use packet marks.Packet Marking "Programs"Packet marking occurs in Netfilter's mangle
table. See the Netfilter
Overview article.You can think of entries in the mangle and tcrules files like
instructions in a program coded in a crude assembly language. The program
gets executed for each packet.That is another way of saying that if you
don't program, you may have difficulty making full use of
Netfilter/Shorewall's Packet Marking.Actually, the mangle/tcrules files define several programs. Each
program corresponds to one of the built-in chains in the mangle
table.PREROUTING program — If MARK_IN_FORWARD_CHAIN=No in
shorewall.conf, then by default entries in
/etc/shorewall/mangle and
/etc/shorewall/tcrules are part of the PREROUTING
program. Entries specifying the ":P" suffix in the ACTION column are
also part of the PREROUTING program. The PREROUTING program gets
executed for each packet entering the firewall.FORWARD program — If MARK_IN_FORWARD_CHAIN=Yes in
shorewall.conf, then by default entries
in/etc/shorewall/mangle and
/etc/shorewall/tcrules are part of the FORWARD
program. Entries specifying the ":F" suffix in the ACTION column are
also part of the FORWARD program. The FORWARD program gets executed
for each packet forwarded by the firewall.OUTPUT program — Entries with $FW in the SOURCE column are part
of the OUTPUT program. The OUTPUT program is executed for each packet
originating on the firewall itself.POSTROUTING program — Entries with a class-id in the ACTION
column (and that don't specify $FW in the SOURCE column) are part of
the POSTROUTING program. These rules are executed for each packet
leaving the firewall. Entries specifying the ":T" suffix in the ACTION
column are also part of the POSTROUTING program (Shorewall version
3.4.0 and later).INPUT program — No entries in tcrules will add entries to this
program. It is executed for each packet that is targeted to the
firewall itself.Note that a packet being forwarded by your firewall actually gets
processed by three different programs: PREROUTING, FORWARD and
POSTROUTING. Similarly, packets addressed to the firewall itself are
processed by two programs (PREROUTING and INPUT) while packets originating
on the firewall are likewise processed by two programs (OUTPUT and
POSTROUTING).Rules in each program are executed as
follows:Rules are conditionally executed based on whether the current
packet matches the contents of the SOURCE, DEST, PROTO, DPORT, SPORT,
USER, TEST, LENGTH and TOS columns.When a rule is executed, either:the current packet receives a new mark value; orthe connection to which the current packet belongs receives
a new mark value (":C", ":CF" or ":CP" suffix in the ACTION
column); orthe packet is classified for traffic shaping (class-id in
the ACTION column); orthe packet mark in the current packet is moved to the
connection mark for the connection that the current packet is part
of ("SAVE" in the ACTION column); orthe connection mark value for the connection that the
current packet is part of is moved to the current packet's mark
("RESTORE" in the ACTION column); orjump to a subroutine (another chain in the mangle table).
These jumps are generated by Shorewall; orexit the current subroutine ("CONTINUE" in the ACTION
column).Unless the subroutine is exited using CONTINUE, the current packet is always passed to the next tcrule in
the subroutine.Mark and Mask ValuesThe mark value is held in a 32-bit field. Because packet marking is
the Netfilter kludge of last resort for solving many
hard technical problems, Shorewall originally reserved half of this field
(16 bits) for future use. The remainder was split into two 8-bit
values:The low-order eight bits are used for traffic shaping marks.
These eight bits were also used for selecting among multiple providers
when HIGH_ROUTE_MARKS=No in shorewall.conf. Some
rules that deal with only these bits used a mask value of 0xff.The next 8 bits were used for selecting among multiple providers
when HIGH_ROUTE_MARKS=Yes in shorewall.conf.
These bits are manipulated using a mask value of 0xff00.As hinted above, marking rules can specify both a mark value and a
mask. The mask determines the subset of the 32 bits in the mark to be used
in the operation — only those bits that are on in the mask are manipulated
when the rule is executed. For entries in tcrules, Shorewall-generated
rules use a mask value that depends on which program the rule is part of,
what the rule does, and the setting of HIGH_ROUTE_MARKS.For entries in mangle and tcrules, the default mask value is 0xffff
except in these cases:RESTORE rules use a default mask value of 0xff.SAVE rules use a default mask value of 0xff.Connection marking rules use a mask value of 0xff.When WIDE_TC_MARKS was added, the number of bits reserved for TC
marks was increased to 14 when WIDE_TC_MARKS=Yes and the provider mark
field (when HIGH_ROUTE_MARKS=Yes) was offset 16 bits. Also, when
HIGH_ROUTE_MARKS=Yes, the mask used for setting/testing TC marks was
0xffff (16 bits).Shorewall actually allows you to have complete control over the
layout of the 32-bit mark using the following options in shorewall.conf (5) (these
options were documented in the shorewall.conf(5) manpage in
Shorewall 4.4.26):TC_BITSThe number of bits at the low end of the mark to be used for
traffic shaping marking. May be zero.PROVIDER_BITSThe number of bits in the mark to be used for provider
numbers. May be zero.PROVIDER_OFFSETThe offset from the right (low-order end) of the provider
number field. If non-zero, must be >= TC_BITS (Shorewall
automatically adjusts PROVIDER_OFFSET's value). PROVIDER_OFFSET +
PROVIDER_BITS must be <= 32.MASK_BITSNumber of bits on the right of the mark to be masked when
clearing the traffic shaping mark. Must be >= TC_BITS and <=
PROVIDER_OFFSET (if PROVIDER_OFFSET > 0)In Shorewall 4.4.26, a new option was added:ZONE_BITSNumber of bits in the mark to use for automatic zone marking
(see the Shorewall
Bridge/Firewall HOWTO).The relationship between these options is shown in this
diagram.The default values of these options are determined by the settings
of other options as follows:
The existence of both TC_BITS and MASK_BITS is owed to the way that
WIDE_TC_MARKS was originally implemented. Note that TC_BITS is 14 rather
than 16 when WIDE_TC_MARKS=Yes.Beginning with Shorewall 4.4.12, the field between MASK_BITS and
PROVIDER_OFFSET can be used for any purpose you want.Beginning with Shorewall 4.4.13, the first unused bit on the left is
used by Shorewall as an exclusion mark, allowing
exclusion in CONTINUE, NONAT and ACCEPT+ rules.Beginning with Shorewall 4.4.26, WIDE_TC_MARKS and HIGH_ROUTE_MARKS
are deprecated in favor of the options described above. The
shorewall update (shorewall6 update)
command will set the above options based on the settings of WIDE_TC_MARKS
and HIGH_ROUTE_MARKS.In Shorewall 4.5.4, a TPROXY mark was added
for TPROXY support. It is a single bit wide and is to the immediate left
of the exclusion mark.The Event Mark bit was added in Shorewall
4.5.19. It is to the immediate left of the TPROXY mark, and it need not
fall within the 32-bit mark unless the reset command is used in the IfEvent action.Shorewall-defined Chains in the Mangle TableShorewall creates a set of chains in the mangle table to hold rules
defined in your /etc/shorewall/mangle
(/etc/shorewall/tcrules) file. As mentioned above,
chains are like subroutines in the packet marking programming language. By
placing all of your rules in subroutines, CONTINUE (which generates a
Netfilter RETURN rule) can be used to stop processing your rules while
still allowing following Shorewall-generated rules to be executed.tcprePREROUTING rules.tcforFORWARD rules.tcoutOUTPUT rules.tcpostPOSTROUTING rules.Shorewall generates jumps to these chains from the built-in chains
(PREROUTING, FORWARD, etc.).An ExampleHere's the example (slightly expanded) from the comments at the top
of the /etc/shorewall/mangle file.#ACTION SOURCE DEST PROTO DPORT SPORT USER TEST LENGTH TOS
MARK(1) 0.0.0.0/0 0.0.0.0/0 icmp echo-request #Rule 1
MARK(1) 0.0.0.0/0 0.0.0.0/0 icmp echo-reply #Rule 2
MARK(1) $FW 0.0.0.0/0 icmp echo-request #Rule 3
MARK(1) $FW 0.0.0.0/0 icmp echo-reply #Rule 4
RESTORE 0.0.0.0/0 0.0.0.0/0 all - - - 0 #Rule 5
CONTINUE 0.0.0.0/0 0.0.0.0/0 all - - - !0 #Rule 6
MARK(4) 0.0.0.0/0 0.0.0.0/0 ipp2p:all #Rule 7
SAVE 0.0.0.0/0 0.0.0.0/0 all - - - !0 #Rule 8Let's take a look at each rule:This straight-forward rule simply marks all 'ping' requests
passing through the firewall with mark value 1. Note that it does not
mark pings that originate on the firewall itself.Similarly, this rule marks 'ping' replies.This rule marks 'ping' requests that originate on the firewall.
This rule and the next ones are part of the OUTPUT program.Similarly, this rule marks 'ping' replies from the firewall
itself.Remember that even though 'ping' packets were marked in one of
the first two rules, they are still passed on to rule 5 (note that
packets marked by rules 3 and 4 are not processed by this rule since
it is in a different program). That rule moves the connection mark to
the packet mark, if the packet mark is still zero
(note the '0' in the TEST column). Without the '0' in the TEST column,
this rule would overwrite the marks assigned in the first two
rules.If the packet mark is non-zero (note the '!0' in the TEST
column), then exit — The remaining rules will not be executed in this
case. The packet mark will be non-zero if this is a 'ping' packet, or
if the connection mark restored in rule 5 was non-zero.The packet mark is still zero. This rule checks to see if this
is a P2P packet and if it is, the packet mark is set to 4.If the packet mark is non-zero (meaning that it was set to 4 in
rule 7), then save the value (4) in the connection. The next time that
a packet from this same connection comes through this program, rule 6
will be executed and the P2P check will be avoided.Examining the Marking Programs on a Running SystemYou can see the mangle (tcrules) entries in action using the
shorewall show mangle command.The sample output from that command shown below has the following in
/etc/shorewall/providers:#NAME NUMBER MARK DUPLICATE INTERFACE GATEWAY OPTIONS COPY
Blarg 1 0x100 main eth3 206.124.146.254 track,balance br0,eth1Here is /etc/shorewall/mangle:#ACTION SOURCE DEST PROTO DPORT SPORT USER TEST
CLASSIFY(1:110) 192.168.0.0/22 eth3 #Our internal nets get priority
#over the server
CLASSIFY(1:130) 206.124.146.177 eth3 tcp - 873And here is /etc/shorewall/tcdevices and
/etc/shorewall/tcclasses:#INTERFACE IN_BANDWITH OUT_BANDWIDTH
eth3 1.3mbit 384kbit
#INTERFACE MARK RATE CEIL PRIORITY OPTIONS
eth3 10 full full 1 tcp-ack,tos-minimize-delay
eth3 20 9*full/10 9*full/10 2 default
eth3 30 6*full/10 6*full/10 3I've annotated the following output with comments beginning with
"<<<<" and ending with ">>>>". This example uses
HIGH_ROUTE_MARKS=Yes and TC_EXPERT=No in
shorewall.conf.gateway:~ # shorewall show mangle
Shorewall 3.3.2 Mangle Table at gateway - Mon Oct 2 15:07:32 PDT 2006
Counters reset Mon Oct 2 07:49:52 PDT 2006
<<<< The PREROUTING Program >>>>
Chain PREROUTING (policy ACCEPT 409K packets, 122M bytes)
pkts bytes target prot opt in out source destination
<<<< Restore the provider mark from the connection, if any >>>>
185K 77M CONNMARK all -- * * 0.0.0.0/0 0.0.0.0/0 CONNMARK match !0x0/0xff00 CONNMARK restore mask 0xff00
<<<< If there is no mark in the connection and the packet came in on eth3, then jump to the routemark chain
This rule is generated as a result of 'track' being specified in the providers file entry for eth3 >>>>
8804 1396K routemark all -- eth3 * 0.0.0.0/0 0.0.0.0/0 MARK match 0x0/0xff00
<<<< If the packet came in on eth3, jump the the tcpre chain -- packets entering on a 'track'ed interface can have their mark set to zero there >>>>
102K 52M tcpre all -- eth3 * 0.0.0.0/0 0.0.0.0/0
<<<< Otherwise, jump to the tcpre chain if there is no current provider mark --
if we would have had TC_EXPERT=Yes, this jump would have been unconditional>>>>
215K 44M tcpre all -- * * 0.0.0.0/0 0.0.0.0/0 MARK match 0x0/0xff00
<<<< End of PREROUTING program >>>>
<<<< INPUT Program -- Shorewall generates the single rule here which turns off the provider mark in the packet after routing
The rule does that by logically ANDing the mark value with 0xff which will turn off all but the low-order 8 bits >>>>
Chain INPUT (policy ACCEPT 98238 packets, 16M bytes)
pkts bytes target prot opt in out source destination
98234 16M MARK all -- * * 0.0.0.0/0 0.0.0.0/0 MARK and 0xff
<<<< End of INPUT program >>>>
<<<< FORWARD Program -- Shorewall generates the first rule here which turns off the provider mark in the packet after routing >>>>
Chain FORWARD (policy ACCEPT 312K packets, 106M bytes)
pkts bytes target prot opt in out source destination
312K 106M MARK all -- * * 0.0.0.0/0 0.0.0.0/0 MARK and 0xff
<<<< Jump unconditionally to the tcfor chain >>>>
312K 106M tcfor all -- * * 0.0.0.0/0 0.0.0.0/0
<<<< End of FORWARD program >>>>
<<<< OUTPUT Program >>>>
Chain OUTPUT (policy ACCEPT 1462K packets, 396M bytes)
pkts bytes target prot opt in out source destination
<<<< Restore the provider mark from the connection -- this rule was generated by Shorewall because of the 'track' option >>>>
3339 615K CONNMARK all -- * * 0.0.0.0/0 0.0.0.0/0 CONNMARK match !0x0/0xff00 CONNMARK restore mask 0xff00
<<<< If there is no provider mark, then jump to the tcout chain --
if we would have had TC_EXPERT=Yes, this jump would have been unconditional >>>>
92747 28M tcout all -- * * 0.0.0.0/0 0.0.0.0/0 MARK match 0x0/0xff00
<<<< End of FORWARD program >>>>
<<<< POSTROUTING Program -- Unconditionally jump to the tcpost chain >>>>
Chain POSTROUTING (policy ACCEPT 407K packets, 135M bytes)
pkts bytes target prot opt in out source destination
407K 135M tcpost all -- * * 0.0.0.0/0 0.0.0.0/0
<<<< End of FORWARD program >>>>
Chain routemark (1 references)
pkts bytes target prot opt in out source destination
<<<< Set connection 'track' mark for packets coming in on eth3 >>>>
8804 1396K MARK all -- eth3 * 0.0.0.0/0 0.0.0.0/0 MARK or 0x100
<<<< Save any mark added above in the connection mark >>>>
8804 1396K CONNMARK all -- * * 0.0.0.0/0 0.0.0.0/0 MARK match !0x0/0xff00 CONNMARK save mask 0xff00
Chain tcfor (1 references)
pkts bytes target prot opt in out source destination
Chain tcout (1 references)
pkts bytes target prot opt in out source destination
Chain tcpost (1 references)
pkts bytes target prot opt in out source destination
<<<< The next two rules are the entries in the /etc/shorewall/mangle file >>>>
65061 11M CLASSIFY all -- * eth3 192.168.0.0/22 0.0.0.0/0 CLASSIFY set 1:110
2224 2272K CLASSIFY tcp -- * eth3 206.124.146.177 0.0.0.0/0 tcp spt:873 CLASSIFY set 1:130
<<<< The following rules are generated by Shorewall and classify the traffic according to the marks in /etc/shorewall/classes >>>>
0 0 CLASSIFY all -- * eth3 0.0.0.0/0 0.0.0.0/0 MARK match 0xa/0xff CLASSIFY set 1:110
0 0 CLASSIFY all -- * eth3 0.0.0.0/0 0.0.0.0/0 MARK match 0x14/0xff CLASSIFY set 1:120
0 0 CLASSIFY all -- * eth3 0.0.0.0/0 0.0.0.0/0 MARK match 0x1e/0xff CLASSIFY set 1:130
Chain tcpre (2 references)
pkts bytes target prot opt in out source destination
gateway:~ #
shorewall-docs-xml-5.2.3/shorewall_prerequisites.xml 0000664 0000000 0000000 00000011036 13427347317 021467 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.2.3/ping.xml 0000664 0000000 0000000 00000006704 13427347317 015446 0 ustar root root
ICMP Echo-request (Ping)TomEastep2001-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.This article applies to Shorewall 3.0 and
later. If you are running a version of Shorewall earlier than Shorewall
3.0.0 then please see the documentation for that
release.Enabling ping will also enable ICMP-based
traceroute. For UDP-based traceroute, see the port information page.'Ping' ManagementIn Shorewall , ICMP echo-requests are treated just like any other
connection request.In order to accept ping requests from zone z1 to zone z2 where the
policy for z1 to z2 is not ACCEPT, you need a rule in
/etc/shorewall/rules of the form:#ACTION SOURCE DEST PROTO DPORT
Ping(ACCEPT) z1 z2Ping from local zone to firewallTo permit ping from the local zone to the firewall:#ACTION SOURCE DEST PROTO DPORT
Ping(ACCEPT) loc $FWIf you would like to accept ping by default even when
the relevant policy is DROP or REJECT, copy
/usr/share/shorewall/action.Drop or
/usr/share shorewall/action.Reject respectively to
/etc/shorewall and simply add this
line to the copy:Ping(ACCEPT)With that rule in place, if you want to ignore ping
from z1 to z2 then you need a rule of the form:#ACTION SOURCE DEST PROTO DPORT
Ping(DROP) z1 z2Silently drop pings from the InternetTo drop ping from the Internet, you would need this rule in
/etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
Ping(DROP) net $FWNote that the above rule may be used without changing the action
files to prevent your log from being flooded by messages generated from
remote pinging.
shorewall-docs-xml-5.2.3/Events.xml 0000664 0000000 0000000 00000065407 13427347317 015762 0 ustar root root
Shorewall EventsTomEastep2013Thomas 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.5.19 and later and supersedes
this article.OverviewShorewall events were introduced in Shorewall 4.5.19 and provide a
high-level interface to the Netfilter recent match
capability. An event is actually a list of (IP address, timestamp) pairs,
and can be tested in a number of different ways:Has event E ever occurred for IP address A (is the IP address in
the list)?Has event E occurred M or more times for IP address A?Has Event E occurred in the last N seconds for IP Address A (is
there an entry for the address with a timestamp falling within the
last N seconds)?Has Event E occurred M or more times in the last N seconds for
IP address A (are there M or more entries for the address with
timestamps falling within the last N seconds)?The event interface is implemented as three parameterized Shorewall
Actions:SetEventThis action initializes an event list for either the source or
destination IP address in the current packets. The list will contain
a single entry for the address that will have the current
timestamp.ResetEventThis action removes all entries for either the source or
destination IP address from an event list.IfEventThis action tests an event in one of the ways listed above,
and performs an action based on the result.Events are based on the Netfilter 'recent match' capability which is
required for their use.The recent-match kernel component is xt_recent which has two options
that are of interest to Shorewall users:ip_list_totThe number of addresses remembered per event. Default is
100.ip_pkt_list_totThe number of packets (event occurrences) remembered per
address. Default is 20.These may be changed with the xt_recent module is loaded or on the
kernel bootloader runline.DetailsBecause these are parameterized actions, optional parameters may be
omitted. Trailing omitted parameters may be omitted entirely while
embedded omitted parameters are represented by a hyphen ("-").Each event is given a name. Event names:Must begin with a letter.May be composed of letters, digits, hyphens ('-') or underscores
('_').May be at most 29 characters in length.SetEventSetEvent(
event, [ action ],
[ src-dst ], [
disposition ] )eventName of the event.actionAn action to perform after the event is initialized. May be
any action that may appear in the ACTION column of shorewall-rules (5).
If no action is to be performed, use COUNT.src-dstSpecifies whether the source IP address (src) or destination IP address (dst) is to be added to the event. The
default is src.dispositionIf the action involves logging,
then this parameter specifies the disposition that will appear in
the log entry prefix. If no disposition
is given, the log prefix is determined normally. The default is
ACCEPT.ResetEventResetEvent(
event, [ action ],
[ src-dst ], [
disposition ] )eventName of the event.actionAn action to perform after the event is reset. May be any
action that may appear in the ACTION column of shorewall-rules (5).
If no action is to be performed, use COUNT. The default is
ACCEPT.src-dstSpecifies whether the source IP address (src) or destination IP address (dst) is to be removed from the event. The
default is src.dispositionIf the action involves logging,
then this parameter specifies the disposition that will appear in
the log entry prefix. If no disposition
is given, the log prefix is determined normally.IfEventIfEvent(
event, [ action ],
[ duration ], [
hitcount ], [
src-dst], [
command[:option]...,
[ disposition ] )eventName of the event.actionAn action to perform if the test succeeds. May be any action
that may appear in the ACTION column of shorewall-rules (5).
The default is ACCEPT.durationNumber of seconds over which the event is to be tested. If
not specified, the test is not constrained by time.hitcountSpecifies the minimum number of packets required for the
test to succeed. If not specified, 1 packet is assumed.src-dstSpecifies whether the source IP address (src) or destination IP address (dst) is to be tested. The default is
src.commandMay be one of the following:checkSimply test if the
duration/hitcount
test is satisfied. If so, the
action is performed.resetLike check. If the
test succeeds, the event will be
reset before the action is taken.
Requires the Mark in filter table
capability in your kernel and iptables.updateLike check.
Regardless of whether the test succeeds, an entry with the
current time and for the src-dst
iP address will be added to the
event.The default is check.option may be one of:reapRegardless of whether the test succeeds, entries for
the src-dst IP address that are
older than duration seconds will
be deleted from the event.ttlConstrains the test to require that the packet TTL
match the ttl in the original packet that created the
entry.dispositionIf the action involves logging,
then this parameter specifies the disposition that will appear in
the log entry prefix. If no disposition
is given, the log prefix is determined normally.'show event' and 'show events' CommandsThe CLI programs (/sbin/shorewall,
/sbin/shorewall-lite, etc.) support show
event and show events commands.The show event command shows the contents of
the events listed in the command while show
events lists the contents of all events.root@gateway:~# shorewall show events
Shorewall 4.5.19-Beta2 events at gateway - Sat Jul 13 07:17:59 PDT 2013
SSH
src=75.101.251.91 : 2225.808, 2225.592
src=218.87.16.135 : 2078.490
SSH_COUNTER
src=65.182.111.112 : 5755.790
src=113.162.155.243 : 4678.249
sticky001
src=172.20.1.146 : 5.733, 5.728, 5.623, 5.611, 5.606, 5.606, 5.589, 5.588, 5.565, 5.551, 5.543, 5.521, 5.377, 5.347, 5.347, 5.345, 5.258, 5.148, 5.048, 4.949
src=172.20.1.151 : 41.805, 41.800
sticky002
src=172.20.1.213 : 98.122, 98.105, 98.105, 98.105, 98.088, 98.088, 98.088, 98.088, 98.058, 98.058, 80.885, 53.528, 53.526, 53.526, 53.510, 53.383, 53.194, 53.138, 53.072, 3.119
src=172.20.1.146 : 4.914, 4.914, 4.898, 4.897, 4.897, 4.896, 4.896, 4.896, 4.882, 4.881, 4.875, 4.875, 4.875, 4.875, 4.875, 4.875, 4.875, 4.874, 4.874, 4.874
root@gateway:~# The SSH and SSH_COUNTER events are created using the following
Automatic Blacklisting example. The sticky001 and sticky002 events are
created by the SAME rule action.Each line represents one event. The list of numbers following the
':' represent the number of seconds ago that a matching packet triggered
the event. The numbers are in chronological sequence, so In this event,
there were 20 packets from 172.20.1.146 that arrived between 5.733 and
4.949 seconds ago:sticky001
src=172.20.1.146 : 5.733, 5.728, 5.623, 5.611, 5.606, 5.606, 5.589, 5.588, 5.565, 5.551, 5.543, 5.521, 5.377, 5.347, 5.347, 5.345, 5.258, 5.148, 5.048, 4.949Note that there may have been earlier packets that also matched,
but the system where this example was captured used the default value of
the ip_pkt_list_tot xt_recent option
(20).The output of these commands is produced by processing the
contents of /proc/net/xt_recent/*. You can access
those files directly to see the raw data. The raw times are the uptime
in milliseconds. The %CURRENTTIME entry is created by the show
event[s] commands to obtain the current uptime.ExamplesAutomatic BlacklistingThis example is for ssh, but it can be adapted for any
application.The name SSH has been changed to SSHLIMIT so as not to override
the Shorewall macro of the same name./etc/shorewall/actions:#ACTION OPTION DESCRIPTION
SSHLIMIT #Automatically blacklist hosts who exceed SSH connection limits
SSH_BLACKLIST #Helper for SSHLIMIT/etc/shorewall/action.SSH_BLACKLIST:#
# Shorewall version 4 - SSH_BLACKLIST Action
#
?format 2
###############################################################################
#TARGET SOURCE DEST PROTO DPORT SPORT
#
# Log the Reject
#
LOG:warn:REJECT
#
# And set the SSH_COUNTER event for the SOURCE IP address
#
SetEvent(SSH_COUNTER,REJECT,src)/etc/shorewall/action.SSHLIMIT:#
# Shorewall version 4 - SSHLIMIT Action
#
?format 2
###############################################################################
#TARGET SOURCE DEST PROTO DPORT SPORT
#
# Silently reject the client if blacklisted
#
IfEvent(SSH_COUNTER,REJECT,300,1)
#
# Blacklist if 5 attempts in the last minute
#
IfEvent(SSH,SSH_BLACKLIST,60,5,src,check:reap)
#
# Log and reject if the client has tried to connect
# in the last two seconds
#
IfEvent(SSH,REJECT:warn:,2,1,-,update,Added)
#
# Un-blacklist the client
#
ResetEvent(SSH_COUNTER,LOG:warn,-,Removed)
#
# Set the 'SSH' EVENT and accept the connection
#
SetEvent(SSH,ACCEPT,src)etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
SSHLIMIT net $FW tcp 22 The technique demonstrated in this example is not self-cleaning.
The SSH_COUNTER event can become full with blackisted addresses that
never attempt to connect again. When that happens and a new entry is
added via SetEvent, the least recently seen address in the table is
deleted.Generalized Automatic BlacklistingThe above two actions are generalized in the AutoBL and AutoBLL
actions released in Shorewall 4.5.19. Only AutoBL is invoked directly
from your rules file; AutoBL invoked AutoBLL internally.AutoBLAutoBL(
event, [
Interval ], [
hitcount ], [
successive ], [
blacklist-time ], [
disposition ], [
log_level ] )eventName of the event. The blacklisting event itself will be
event_BL (analogous to SSH_COUNTER
above).intervalInterval, in seconds, over which hits are to be counted.
Default is 60 seconds.hitcountNumber of matching packets that will trigger automatic
blacklisting when they arrive in
interval seconds. Default is
5.successiveIf a matching packet arrives within this many seconds of
the preceding one, it should be logged according to
log_level and handled according to
the disposition. If successive
packets are not to be considered, enter 0. Default is 2
seconds.blacklist-timeTime, in seconds, that the source IP address is to be
blacklisted. Default is 300 (5 minutes).dispositionThe disposition of blacklisted packets. Default is
DROP.log_levelLog level at which packets are to be logged. Default is
info.To duplicate the SSHLIMIT entry in
/etc/shorewall/rules shown above:#ACTION SOURCE DEST PROTO DPORT
AutoBL(SSH,-,-,-,REJECT,warn)\
net $FW tcp 22 Port KnockingThis example shows a different implementation of the one shown in
the Port Knocking article.In this example:Attempting to connect to port 1600 enables SSH access. Access
is enabled for 60 seconds.Attempting to connect to port 1601 disables SSH access (note
that in the article linked above, attempting to connect to port 1599
also disables access. This is an port scan defence as explained in
the article).To implement that approach:/etc/shorewall/actions:#ACTION OPTION DESCRIPTION
Knock #Port Knocking/etc/shorewall/action.Knock:#
# Shorewall version 4 - Port-Knocking Action
#
?format 2
###############################################################################
#ACTION SOURCE DEST PROTO DPORT
IfEvent(SSH,ACCEPT:info,60,1,src,reset)\
- - tcp 22
SetEvent(SSH,ACCEPT) - - tcp 1600
ResetEvent(SSH,DROP:info) etc/shorewall/rules:#ACTION SOURCE DEST PROTO DPORT
Knock net $FW tcp 22,1599-1601 Stateful Port Knocking (knock with a sequence of ports)Gerhard Wiesinger
has contributed a Perl module that allows you to define portknocking
sequences. Download the
module and copy it into your site_perl directory.Using Gerhard's module, a port-knocking rule is defined via a
'?PERL' statement. This example opens the SSH port from net->fw using
the knock sequence 52245, 15623, 19845:?BEGIN PERL
use KnockEnhanced;
KnockEnhanced 'net', '$FW', {name => 'SSH1', log_level => 3, proto => 'tcp', target => 'ssh', knocker => [52245,15623,19845]};
?END PERLA few notes on the parameters:The first parameter is the rule SOURCEThe second parameter is the rule DESTThe third parameter is a Perl hash reference that defines the
remaining parameters. Each parameter is specified via
param =>
value.proto is the protocol --
if not specified, the default is tcpseconds is the timeout
between successive events -- default is 60 seconds.original_dest is the rule
ORIGDESTtarget is the port(s)
that you are trying to open. May either be a single name or
number, or it may be a list of names and/or numbers separated by
commas and enclosed in square brackets ("[...]").name is a name used as
the base for event and chain names. If not supplied, the first
target is used, in which case
the first target must be a port name.log_level specifies
logging for the generated rulesPort names and numbers may be optionally followed by a colon
(":") and a protocol name or number to override the specified
protocol.The module itself contains additional examples of its
usage.
shorewall-docs-xml-5.2.3/ipsets.xml 0000664 0000000 0000000 00000022530 13427347317 016013 0 ustar root root
Shorewall and IpsetsTomEastep20052008201020152017Thomas 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 appropriate for your
version.What are Ipsets?Ipsets are an extension to Netfilter/iptables that are available in
xtables-addons
if they are not available in your current distribution. Instructions for
installing xtables-addons may be found in the Dynamic Zones article. Note that xtables-addons
might not be required with the 'ipset' package provided by your
distribution. See also the section capabilities in
the configuration file basics
article and the Shorecap
program.Ipset allows you to create one or more named sets of addresses then
use those sets to define Netfilter/iptables rules. Possible uses of ipsets
include:Blacklists. Ipsets provide an efficient way to represent large
sets of addresses and you can maintain the lists without the need to
restart or even refresh your Shorewall configuration.Zone definition. Using the /etc/shorewall/hosts file, you can
define a zone based on the (dynamic)
contents of an ipset. Again, you can then add or delete
addresses to the ipset without restarting Shorewall.See the ipsets site (URL above) for additional information about
ipsets.Shorewall Support for IpsetsSupport for ipsets was introduced in Shorewall version 2.3.0. In
most places where a host or network address may be used, you may also use
the name of an ipset prefaced by "+".Example: "+Mirrors"When using Shorewall, the names of ipsets are restricted as
follows:They must begin with a letter (after the '+').They must be composed of letters, digits, dashes ("-") or
underscores ("_").To generate a negative match, prefix the "+" with "!" as in
"!+Mirrors".Example 1: Blacklist all hosts in an ipset named "blacklist"/etc/shorewall/blrules#ACTION SOURCE DEST PROTO DPORT
DROP net:+blacklistExample 2: Allow SSH from all hosts in an ipset named "sshok:/etc/shorewall/rules#ACTION SOURCE DEST PROTO DPORT
ACCEPT net:+sshok $FW tcp 22The name of the ipset can be optionally followed by a
comma-separated list of flags enclosed in square brackets ([...]). Each
flag is either src or dst and specifies whether it is the SOURCE address
or port number or the DESTINATION address or port number that should be
matched. The number of flags must be appropriate for the type of ipset. If
no flags are given, Shorewall assumes that the set takes a single flag and
will select the flag based on the context. For example, in the blacklist
file and when the ipset appears in the SOURCE column of the rules file,
src is assumed. If the ipset appears in
the DEST column of the rules file, dst is
assumed. Note that by using [dst] in the
blacklist file, you can coerce the rule into matching the destination IP
address rather than the source.Beginning with Shorewall 4.4.14, multiple source or destination
matches may be specified by placing multiple set names in '+[...]' (e.g.,
+[myset,myotherset]). When so enclosed, the set names need not be prefixed
with a plus sign.Shorewall can save/restore your ipset contents with certain
restrictions:You must set SAVE_IPSETS=Yes in shorewall.conf (5).You must have at least one entry in the other configuration
files that uses an ipset.You cannot use an ipset in shorewall-stoppedrules
(5) (shorewall-routestopped
(5)).The restore command cannot restore ipset
contents saved by the save command unless the
firewall is first stopped.Beginning with Shorewall 4.6.4, you can save selective ipsets by
setting SAVE_IPSETS to a comma-separated list of ipset names. You can also
restrict the group of sets saved to ipv4 sets by setting
SAVE_IPSETS=ipv4.With Shorewall 4.6.4, the SAVE_IPSETS option may specify a list of
ipsets to be saved. When such a list is specified, only those ipsets
together with the ipsets supporting dynamic zones are saved. Shorewall6
support for the SAVE_IPSETS option was also added in 4.6.4. When
SAVE_IPSETS=Yes in shorewall6.conf(5), only ipv6
ipsets are saved. For Shorewall, if SAVE_IPSETS=ipv4 in shorewall.conf(5), then only
ipv4 ipsets are saved. Both features require ipset version 5 or
later.Although Shorewall can save the definition of your ipsets and
restore them when Shorewall starts, in most cases you must use the ipset
utility to initially create and load your ipsets. The exception is that
Shorewall will automatically create an empty iphash ipset to back each
dynamic zone.Shorewall6 and Shorewall-init Support for IpsetsIpset support in Shorewall6 was added in Shorewall 4.4.21.Beginning with Shorewall 4.6.4, SAVE_IPSETS is available in shorewall6-conf(5). When set
to Yes, the ipv6 ipsets will be saved. You can also save selective ipsets
by setting SAVE_IPSETS to a comma-separated list of ipset names.Prior to Shorewall 4.6.4, SAVE_IPSETS=Yes in shorewall.conf(5) won't work
correctly because it saves both IPv4 and IPv6 ipsets. To work around this
issue, Shorewall-init is capable restoring ipset contents during 'start'
and saving them during 'stop'. To direct Shorewall-init to save/restore
ipset contents, set the SAVE_IPSETS option in
/etc/sysconfig/shorewall-init (/etc/default/shorewall-init on Debian and
derivatives). The value of the option is a file name where the contents of
the ipsets will be save to and restored from. Shorewall-init will create
any necessary directories during the first 'save' operation.If you configure Shorewall-init to save/restore ipsets, be sure to
set SAVE_IPSETS=No in shorewall.conf and shorewall6.conf.If you configure SAVE_IPSETS in shorewall.conf(5) and/or shorewall6.conf(5) then do
not set SAVE_IPSETS in shorewall-init.
shorewall-docs-xml-5.2.3/shorewall_setup_guide_fr.xml 0000664 0000000 0000000 00000341423 13427347317 021575 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