<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>IPTables &#8211; Johnny Morano&#039;s Tech Articles</title>
	<atom:link href="https://jmorano.moretrix.com/tag/iptables/feed/" rel="self" type="application/rss+xml" />
	<link>https://jmorano.moretrix.com</link>
	<description>Ramblings of an old-fashioned space cowboy</description>
	<lastBuildDate>Sat, 09 Apr 2022 07:12:09 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>

<image>
	<url>https://jmorano.moretrix.com/wp-content/uploads/2022/04/cropped-jmorano_emblem-32x32.png</url>
	<title>IPTables &#8211; Johnny Morano&#039;s Tech Articles</title>
	<link>https://jmorano.moretrix.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Perl script to monitor the rate of logs</title>
		<link>https://jmorano.moretrix.com/2022/04/perl-script-to-monitor-the-rate-of-logs/</link>
					<comments>https://jmorano.moretrix.com/2022/04/perl-script-to-monitor-the-rate-of-logs/#respond</comments>
		
		<dc:creator><![CDATA[Johnny Morano]]></dc:creator>
		<pubDate>Thu, 07 Apr 2022 12:39:50 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Dev]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Logging]]></category>
		<guid isPermaLink="false">https://jmorano.moretrix.com/?p=1399</guid>

					<description><![CDATA[In a previous article (IPTables Logging in JSON with NFLOG and ulogd2) we learned how to log certain&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In a previous article (<a href="https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/" data-type="post" data-id="1308">IPTables Logging in JSON with NFLOG and ulogd2</a>) we learned how to log certain IPTables rules to JSON log files.</p>



<p>Monitoring the logs in real-time on the command line, can also be very useful when debugging either the rules themselves or when analyzing certain issues. Rather than just looking at the logs, in some situations it might be useful to track the rate of the log messages. A self-written Perl script can be useful as it allows to be flexible when it comes to:</p>



<ul class="wp-block-list"><li>parsing logs</li><li>formatting the output (with colors or tables or &#8230;)</li><li>calculating statistics</li><li>&#8230;</li></ul>



<p>The following Perl script uses a few modules which need to be present:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">use IO::Async::Timer::Periodic;
use IO::Async::Loop;
use Time::HiRes qw/time/;
use Term::ANSIColor qw(:constants);
use Getopt::Long;</pre>



<p>The first two modules can be installed on Debian systems with:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">apt install libio-async-perl</pre>



<p>The others are part of the normal Perl packages and do not require any extra installation.</p>



<p>Next the script will use a polling mechanism to read from standard output at fixed intervals, to calculate the rate of the unique log lines. The default polling rate is set to 2 seconds but it can be managed through command line parameters:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my $last_poll_time = time;

my $poll_rate = 2;
GetOptions (
    'p|pollrate=i' => \$poll_rate,
);

my $loop = IO::Async::Loop->new;
my $timer = IO::Async::Timer::Periodic->new(
   interval => $poll_rate,
   on_tick  => \&amp;log_rate
);

$timer->start;
$loop->add( $timer );
$loop->run;</pre>



<p>Finally, the script will define a subroutine called <code>log_rate</code>, which will read from standard output (or even a file) at each poll interval. Important is of course that the log lines from standard output do not contain unique data such as timestamps. The output must be as generic as possible.</p>



<p>Example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tail -qf /var/log/ulog/blocked_detailed.json /var/log/ulog/blocked.json /var/log/ulog/passed.json  | jq -r --unbuffered '."oob.prefix"' 
blocked: invalid state
blocked: invalid state
blocked: invalid state
blocked: invalid state
blocked: invalid state
action=blocked
action=blocked
action=blocked
action=blocked
action=blocked
action=passed
action=passed
action=passed
action=passed</pre>



<p>The code snippit for <code>log_rate</code> could contain:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sub log_rate {
    local $SIG{ALRM} = sub { die time, " time exceeded to read STDIN\n" };

    alarm($poll_rate);
    my $h;
    eval {
        local $| = 1;
        while (my $line = &lt;>) {
            chomp($line);
            $h->{$line}++;
        }
    };
    alarm(0);

    return unless keys %$h;

    my $delta_time = time - $last_poll_time;
    print DARK WHITE . sprintf("%d: ", time) . RESET;
    print( BOLD WHITE . $_ ." [" . GREEN . sprintf("%.2f/s", $h->{$_}/$delta_time) . BOLD WHITE "] | " . RESET) foreach keys %$h; 
    print "\n";

    $last_poll_time = time;
}</pre>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 2</mark> will start with declaring the &#8220;<code>ALARM</code>&#8221; signal. This signal is called when the <code>alarm</code> timeout has been reached (see further below).</p>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 4</mark> defines the <code>alarm</code> timeout in seconds: meaning: if everything below<mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"> line 4</mark> (until the next <code>alarm</code> line) takes longer than the defined timeout in seconds, the &#8220;ALRM&#8221; signal handler defined at <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">line 2</mark> will be called, which basically stops the code execution with a <code>die</code> (which in theory should stop the script with an <code>exit 1</code>).</p>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 5</mark> defines a hash reference which is required down below, to temporarily store unique log lines.</p>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 6</mark> until <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">12</mark> define an <code>eval</code> block. The <code>eval</code> block will catch the ALRM signal <code>die</code> (once reached) without stopping the script with an <code>exit 1</code>. Inside the <code>eval</code> block, the standard output will be read with the diamond operator (<code>&lt;></code>) and unique lines will be counted and stored in the <code>$h</code> hash reference.</p>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 13</mark>, right after the <code>eval</code> block, sets to <code>alarm</code> timeout to 0 again, which means it is disabled. This allows that only execution of the <code>eval</code> block will be evaluated for timeout. </p>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Line 15</mark> ensures that only when log lines were discovered and stored in the temporary hash-ref<code> $h</code>, that rates will be printed to the screen.</p>



<p>The rest of the code will take care of printing the discovered log lines with their rates to the screen. Colors from <code>Term::ANSIColor</code> are used to make the output more vivid.</p>



<p>Example output:</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="911" height="285" src="https://jmorano.moretrix.com/wp-content/uploads/2022/04/Screenshot-from-2022-04-06-14-14-00.png" alt="" class="wp-image-1405" srcset="https://jmorano.moretrix.com/wp-content/uploads/2022/04/Screenshot-from-2022-04-06-14-14-00.png 911w, https://jmorano.moretrix.com/wp-content/uploads/2022/04/Screenshot-from-2022-04-06-14-14-00-300x94.png 300w, https://jmorano.moretrix.com/wp-content/uploads/2022/04/Screenshot-from-2022-04-06-14-14-00-768x240.png 768w" sizes="(max-width: 911px) 100vw, 911px" /></figure>



<p>The full version of the script can be found at: <a href="https://github.com/insani4c/perl_tools/tree/master/log_rate" target="_blank" rel="noreferrer noopener">https://github.com/insani4c/perl_tools/tree/master/log_rate</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jmorano.moretrix.com/2022/04/perl-script-to-monitor-the-rate-of-logs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>IPTables Logs in Loki and Grafana (with Promtail)</title>
		<link>https://jmorano.moretrix.com/2022/04/iptables-logs-in-loki-and-grafana-with-promtail/</link>
					<comments>https://jmorano.moretrix.com/2022/04/iptables-logs-in-loki-and-grafana-with-promtail/#respond</comments>
		
		<dc:creator><![CDATA[Johnny Morano]]></dc:creator>
		<pubDate>Fri, 01 Apr 2022 08:00:00 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Grafana]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[Loki]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[Promtail]]></category>
		<guid isPermaLink="false">https://jmorano.moretrix.com/?p=1310</guid>

					<description><![CDATA[In the previous article (Logging in IPTables with NFLog and ulogd2) rules were created to log certain IPTables&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In the previous article (<a href="https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/" data-type="URL" data-id="https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/">Logging in IPTables with NFLog and ulogd2</a>) rules were created to log certain IPTables rules with the use of <code>NFLOG</code> and <code>ulogd2</code> to a file in JSON format.</p>



<p>With Promtail (<a rel="noreferrer noopener" href="https://grafana.com/docs/loki/latest/clients/promtail/" data-type="URL" data-id="https://grafana.com/docs/loki/latest/clients/promtail/" target="_blank">https://grafana.com/docs/loki/latest/clients/promtail/</a>), the above created log files can be sent to <a rel="noreferrer noopener" href="https://grafana.com/docs/loki/latest/" data-type="URL" data-id="https://grafana.com/docs/loki/latest/" target="_blank">Loki</a> so that they can finally be displayed in <a rel="noreferrer noopener" href="https://grafana.com/grafana/" data-type="URL" data-id="https://grafana.com/grafana/" target="_blank">Grafana</a>.</p>



<p>The installation of both Loki and Grafana are not covered in this article. The installation of Promtail is documented at <a rel="noreferrer noopener" href="https://grafana.com/docs/loki/latest/clients/promtail/installation/" target="_blank">https://grafana.com/docs/loki/latest/clients/promtail/installation/</a>.</p>



<p>Once Promtail is installed, create the following configuration file at <code>/etc/promtail-local-config.yaml</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">server:                                                                                                                                                                                                            
  http_listen_port: 9080                                                                                                                                                                                           
  grpc_listen_port: 0                                                                                                                                                                                              
                                                                                                                                                                                                                   
positions:                                                                                                                                                                                                         
  filename: /var/tmp/promtail_positions.yaml                                                                                                                                                                       
                                                                                                                                                                                                                   
clients:                                                                                                                                                                                                           
  - url: http://loki_server:3100/loki/api/v1/push       
                                                                                                                                                               
scrape_configs:
    - job_name: iptableslogsjson
      static_configs:
      - targets:
          - localhost
        labels:
          instance: myhostname01
          job: iptableslogsjson
          __path__: /var/log/ulog/*json
      pipeline_stages:
      - json:
          expressions:
            timestamp: timestamp
            prefix: '"oob.prefix"'
            src: src_ip
            dst: dest_ip
      - labels:
          timestamp:
          prefix:
          src:
          dst:</pre>



<p>With the above configuration, Promtail will create 4 extra labels per log line:</p>



<ul class="wp-block-list"><li><code>timestamp</code>: Contains the logged timestamp</li><li><code>prefix</code>: the NFLOG prefix string</li><li><code>src</code>: the source IP address</li><li><code>dst</code>: the destination IP address</li></ul>



<p>Once the logs are arriving in Loki, and Loki has been configured as a datasource in Grafana, graphs can be created using <a href="https://grafana.com/docs/loki/latest/logql/" data-type="URL" data-id="https://grafana.com/docs/loki/latest/logql/" target="_blank" rel="noreferrer noopener">LogQL</a>.</p>



<p>Example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">sum(rate({job="iptableslogsjson"} [$__interval])) by (prefix)</pre>



<figure class="wp-block-image size-full"><img decoding="async" width="916" height="296" src="https://jmorano.moretrix.com/wp-content/uploads/2022/03/Screenshot-from-2022-03-30-15-29-02.png" alt="" class="wp-image-1311" srcset="https://jmorano.moretrix.com/wp-content/uploads/2022/03/Screenshot-from-2022-03-30-15-29-02.png 916w, https://jmorano.moretrix.com/wp-content/uploads/2022/03/Screenshot-from-2022-03-30-15-29-02-300x97.png 300w, https://jmorano.moretrix.com/wp-content/uploads/2022/03/Screenshot-from-2022-03-30-15-29-02-768x248.png 768w" sizes="(max-width: 916px) 100vw, 916px" /></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://jmorano.moretrix.com/2022/04/iptables-logs-in-loki-and-grafana-with-promtail/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>IPTables Logging in JSON with NFLOG and ulogd2</title>
		<link>https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/</link>
					<comments>https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/#comments</comments>
		
		<dc:creator><![CDATA[Johnny Morano]]></dc:creator>
		<pubDate>Thu, 31 Mar 2022 08:00:00 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[nflog]]></category>
		<category><![CDATA[SysAdmin]]></category>
		<category><![CDATA[ulogd2]]></category>
		<guid isPermaLink="false">https://jmorano.moretrix.com/?p=1308</guid>

					<description><![CDATA[Logging with IPTables requires the use of an extra IPTables extension called NFLOG (https://manpages.debian.org/experimental/iptables/iptables-extensions.8.en.html#NFLOG) and a separate daemon&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Logging with IPTables requires the use of an extra IPTables extension called <code>NFLOG</code> (<a rel="noreferrer noopener" href="https://manpages.debian.org/experimental/iptables/iptables-extensions.8.en.html#NFLOG" target="_blank">https://manpages.debian.org/experimental/iptables/iptables-extensions.8.en.html#NFLOG</a>) and a separate daemon process, called <code>ulogd2</code> (<a rel="noreferrer noopener" href="https://www.netfilter.org/projects/ulogd/index.html" target="_blank">https://www.netfilter.org/projects/ulogd/index.html</a>). Ulogd2 reads out the packets sent to the above mentioned extension and stores them in local files or databases.</p>



<p>First, install the <code>ulogd2</code> package (example is based on Debian/ Ubuntu):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">apt install ulogd2
</pre>



<p>Example: log and drop packets which have an invalid state</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Log and drop all invalid packets                                                                                                                                                                                         
iptables -A INPUT -m conntrack --ctstate INVALID -j NFLOG --nflog-group 123 --nflog-prefix "packet with invalid state"
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
</pre>



<p>To log all those packets to a file in JSON format, <code>ulogd2</code> requires the following configuration at <code>/etc/ulogd.conf</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="ini" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="true" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[global]                                                                                                                                                                                                           
logfile="syslog"
loglevel=3                                                                                                                                                                                                                   
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_inppkt_NFLOG.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_filter_IFINDEX.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_filter_IP2STR.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_filter_IP2BIN.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_filter_PRINTPKT.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_filter_HWHDR.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_raw2packet_BASE.so"
plugin="/usr/lib/x86_64-linux-gnu/ulogd/ulogd_output_JSON.so"

stack=log1:NFLOG,base1:BASE,ifi1:IFINDEX,ip2str1:IP2STR,mac2str1:HWHDR,json1:JSON

[log1]
group=123

[json1]
sync=1
file="/var/log/ulog/netfilter_log.json"</pre>



<p>After creating the configuration file, ensure that <code>ulogd2</code> is restarted and that the directory <code>/var/log/ulog</code> exists</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir /var/log/ulog
chown ulog /var/log/ulog
systemctl restart ulogd2.service</pre>



<p>Once the above created rule matches, a JSON log line will be written to disk:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tail -1 /var/log/ulog/netfilter_log.json | jq
{
  "timestamp": "2022-03-30T14:46:20.527282+0200",
  "dvc": "Netfilter",
  "raw.pktlen": 52,
  "raw.pktcount": 1,
  "oob.prefix": "packet with invalid state",
  "oob.time.sec": 1648644380,
  "oob.time.usec": 527282,
  "oob.mark": 0,
  "oob.ifindex_in": 2,
  "oob.hook": 1,
  "raw.mac_len": 14,
  "oob.family": 2,
  "oob.protocol": 2048,
  "raw.label": 0,
  "raw.type": 1,
  "raw.mac.addrlen": 6,
  "ip.protocol": 6,
  "ip.tos": 0,
  "ip.ttl": 116,
  "ip.totlen": 52,
  "ip.ihl": 5,
  "ip.csum": 41779,
  "ip.id": 16049,
  "ip.fragoff": 16384,
  "src_port": 58662,
  "dest_port": 445,
  "tcp.seq": 3872158206,
  "tcp.ackseq": 0,
  "tcp.window": 8192,
  "tcp.offset": 0,
  "tcp.reserved": 0,
  "tcp.urg": 0,
  "tcp.ack": 0,
  "tcp.psh": 0,
  "tcp.rst": 0,
  "tcp.syn": 1,
  "tcp.fin": 0,
  "tcp.res1": 0,
  "tcp.res2": 0,
  "tcp.csum": 60039,
  "oob.in": "eth0",
  "oob.out": "",
  "src_ip": "181.122.165.177",
  "dest_ip": "1.1.1.1",
  "mac.saddr.str": "94:f7:ad:4f:81:fc",
  "mac.daddr.str": "aa:aa:aa:aa:aa:aa",
  "mac.str": "aa:aa:aa:aa:aa:aa:94:f7:ad:4f:81:fc:08:00"
}</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://jmorano.moretrix.com/2022/03/logging-in-iptables-with-nflog-and-ulogd2/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Block countries using IPtables and IPDeny.com</title>
		<link>https://jmorano.moretrix.com/2022/03/block-countries-using-iptables/</link>
					<comments>https://jmorano.moretrix.com/2022/03/block-countries-using-iptables/#comments</comments>
		
		<dc:creator><![CDATA[Johnny Morano]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 07:12:28 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[SysAdmin]]></category>
		<guid isPermaLink="false">https://jmorano.moretrix.com/?p=1285</guid>

					<description><![CDATA[Certain server setups do not require access for all countries or just want to block certain countries since&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Certain server setups do not require access for all countries or just want to block certain countries since they are know for their malicious activity.</p>



<p>One simple (not full bullet-proof) way of doing this, is by setting up block rules on firewall level, which can be achieved on Linux servers with <code>iptables</code> and zone files of <a rel="noreferrer noopener" href="https://www.ipdeny.com/" target="_blank">https://www.ipdeny.com/</a>. These zone files contain the network ranges assigned to a specific country.</p>



<p>The network ranges are fed to a tool called <code>ipset</code>, which sets up of hash map that can be easily used within <code>iptables</code> rules.</p>



<p>On Debian/Ubuntu systems, <code>ipset</code> can be installed with the <code>apt</code> command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">apt install ipset</pre>



<p>Next, create an iptables chain called &#8220;<code>blocked_countries</code>&#8220;, to which we will add rules afterwards. Add this chain to the beginning of the <code>INPUT</code> and <code>FORWARD</code> chain, to have early blocking in your ruleset.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">iptables -N blocked_countries
iptables -I INPUT -j blocked_countries -m comment --comment "Blocked countries"
iptables -I FORWARD -j blocked_countries -m comment --comment "Blocked countries"</pre>



<p>Finally, create a shell script which will download the required zone files from <a rel="noreferrer noopener" href="https://ipdeny.com/" target="_blank">https://ipdeny.com/</a> and which feeds them to <code>ipset</code>. The  example script will try to block the countries China, Russia and Belarus:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#!/bin/bash

COUNTRIES=('cn' 'ru' 'by')

for COUNTRY in "${COUNTRIES[@]}"; do
    ipset create "countries_${COUNTRY}" hash:net
done

iptables -v -F blocked_countries

for i in "${COUNTRIES[@]}"; do
    echo "Ban IP of country ${i}"
    ipset flush "countries_${i}"


    for IP in $(wget -O - https://www.ipdeny.com/ipblocks/data/countries/${i}.zone)
    do
        ipset add "countries_${i}" $IP
    done
    iptables -I blocked_countries   -m set --match-set "countries_${i}" src  -j LOGDROP -m comment   --comment "Block .${i}"
done
﻿</pre>



<p>You can check the <code>blocked_countries</code> chain if packets are being blocked by your new rules:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="monokai" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">iptables -v -n -L blocked_countries 
# Warning: iptables-legacy tables present, use iptables-legacy to see them
Chain blocked_countries (2 references)
 pkts bytes target     prot opt in     out     source               destination         
    2   104 LOGDROP    all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-set countries_by src /* Block .by */
 2182  155K LOGDROP    all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-set countries_ru src /* Block .ru */
  344 21370 LOGDROP    all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-set countries_cn src /* Block .cn */
﻿</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://jmorano.moretrix.com/2022/03/block-countries-using-iptables/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Connect your home and company networks with OpenVPN</title>
		<link>https://jmorano.moretrix.com/2011/06/connect-your-home-and-company-networks-with-openvpn/</link>
					<comments>https://jmorano.moretrix.com/2011/06/connect-your-home-and-company-networks-with-openvpn/#respond</comments>
		
		<dc:creator><![CDATA[insaniac]]></dc:creator>
		<pubDate>Wed, 22 Jun 2011 14:27:41 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[OpenVPN]]></category>
		<category><![CDATA[SysAdmin]]></category>
		<guid isPermaLink="false">http://jmorano.moretrix.com/?p=618</guid>

					<description><![CDATA[Introduction OpenVPN is an opensource Virtual Private Networking (VPN) solution which can be downloaded freely on the Internet.&#8230;]]></description>
										<content:encoded><![CDATA[<h4>Introduction</h4>
<p><a href="http://www.openvpn.net/">OpenVPN</a> is an opensource Virtual Private Networking (VPN) solution which can be downloaded freely on the Internet. It also included in almost every Linux distro to-date, so it can be easily installed using your distro&#8217;s favourite package manager tools. It uses the SSL/TLS VPN stacks, which makes it different from almost every other VPN solution (which are usually based on IPSec).</p>
<p>This guide will described how OpenVPN can be installed and configured on a Debian system, so that it can be used as a means to connect to your home and company networks. </p>
<p><span id="more-618"></span></p>
<h4>The Server</h4>
<p>First install the openvpn package:</p>
<pre class="brush:bash"># apt-get install openvpn</pre>
<p>If apt-get suggests extra packages to install, just install them!</p>
<p>Two networks will be created:<br />
* one to create a secure network for servers: 192.168.1.0/24<br />
* one to create a secure network of client PC&#8217;s, Macbooks, Linux desktops, &#8230; : 10.66.99.0/24</p>
<p>Next, we will need an OpenVPN configuration file for the OpenVPN we&#8217;re about to create:</p>
<pre class="brush:bash">
.oO( ieyasu | /etc/openvpn )Oo. cat server.conf 
# LIKE A BOSS
local 176.9.64.17
port 1194
proto udp
dev tun0

mode server
tls-server

persist-key
persist-tun

#certificates and encryption
ca ca.crt
cert ieyasu.crt
key ieyasu.key
dh dh2048.pem
tls-auth ta.key 0
cipher AES-256-CBC
comp-lzo

server 192.168.1.0 255.255.255.0
route  10.66.99.0 255.255.255.0

ifconfig-pool-persist ipp.txt
push "route 10.66.99.0 255.255.255.0"

# separate client configs
client-config-dir ccd

#log and security
user nobody
group nogroup
keepalive 5 30
status /var/log/openvpn-status.log
verb 3
</pre>
<p>We will also need some firewall rules allowing our OpenVPN traffic:</p>
<pre class="brush:bash">
$IPTABLES -A INPUT   -i tun0 -s 192.168.1.0/24 -d 192.168.1.0/24 -j ACCEPT
$IPTABLES -A INPUT   -i tun0 -s 10.66.99.0/24  -d 192.168.1.1    -j ACCEPT
$IPTABLES -A INPUT   -i tun0 -s 10.66.99.0/24  -d 10.66.99.0/24  -j ACCEPT

$IPTABLES -P FORWARD DROP
$IPTABLES -A FORWARD -i tun0 -s 10.66.99.0/24  -d 192.168.1.1    -j ACCEPT
$IPTABLES -A FORWARD -i tun0 -s 10.66.99.0/24  -d 10.66.99.0/24  -j ACCEPT
$IPTABLES -A FORWARD -i tun0 -s 192.168.1.0/24 -d 192.168.1.0/24 -j ACCEPT

$IPTABLES -A INPUT -p udp --dport 1194 -j ACCEPT
</pre>
<p>Now we need to create a CCD file for each client. The CCD file contains the network settings for the connection OpenVPN clients.<br />
Example:</p>
<pre class="brush:bash">
.oO( ieyasu | ~ )Oo. cat /etc/openvpn/ccd/bear
ifconfig-push 192.168.1.11 192.168.1.12
.oO( ieyasu | ~ )Oo. cat /etc/openvpn/ccd/lion
ifconfig-push 10.66.99.3 10.66.99.4
</pre>
<p>The final thing to do for the OpenVPN server, is to create the x509 certificates.</p>
<p>First:</p>
<pre class="brush:bash">
# mkdir /etc/openvpn/easy-rsa/
# cp -R /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa/
</pre>
<p>This will copy the required tools for creating the certificates for both the server as the clients.</p>
<p>Next, specify your information in /etc/openvpn/easy-rsa/vars, only the bottom is of real importance:</p>
<pre class="brush:bash">
vi /etc/openvpn/easy-rsa/vars
*snip*
# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="BE"
export KEY_PROVINCE="LIM"
export KEY_CITY="As"
export KEY_ORG="MORETRIX"
export KEY_EMAIL="info@moretrix.com"
</pre>
<p>Finally we will create the CA and the server certificate (we&#8217;re making a 2048 one!):</p>
<pre class="brush:bash">
# cd /etc/openvpn/easy-rsa/
# chown -R root:admin .
# chmod g+w .
# source ./vars
# ./clean-all
# ./build-dh
# ./pkitool --initca
# ./pkitool --server server
# cd keys
# openvpn --genkey --secret ta.key
# cp server.crt server.key ca.crt dh2048.pem ta.key ../../
</pre>
<p>Finally we just need to start the OpenVPN service and the server is ready!</p>
<pre class="brush:bash">
# /etc/init.d/openvpn restart
</pre>
<h4>The Clients</h4>
<p>Every client will need his own x509 certificate:</p>
<pre class="brush:bash">
# cd /etc/openvpn/easy-rsa
# ./pkitool bear
</pre>
<p><strong>bear</strong> is the name of the client host.</p>
<p>Now create a client configuration file, let&#8217;s call it <em>bear.conf</em> and we&#8217;ll save in it <em>/tmp/client_config/</em>:</p>
<pre class="brush:bash">
client
dev tun
remote 176.9.64.17 1194
nobind
resolv-retry infinite
persist-key
persist-tun
ca ca.crt
cert bear.crt
key bear.key
tls-auth ta.key 1
cipher AES-256-CBC
comp-lzo
verb 3
</pre>
<p>Finally grab all the files the client will need</p>
<pre class="brush:bash">
# cd /etc/openvpn/easy-rsa/keys/
# cp ca.crt ta.key bear.crt bear.key /tmp/client_config/
# cd /tmp/client_config/
# ls -ltr
total 24
-rw------- 1 root root  636 Jun 22 16:17 ta.key
-rw-r--r-- 1 root root 1537 Jun 22 16:17 ca.crt
-rw-r--r-- 1 root root 5053 Jun 22 16:17 bear.crt
-rw------- 1 root root 1704 Jun 22 16:17 bear.key
-rw-r--r-- 1 root root  185 Jun 22 16:17 bear.conf
</pre>
<p>If the client also uses the OpenVPN command line tools, just copy the above files to /etc/openvpn and restart the openvpn service.</p>
<pre class="brush:bash">
root@bear:/etc/openvpn# ls -ltr
total 28
-rwxr-xr-x 1 root root 1357 2011-03-11 02:03 update-resolv-conf
-rw-r--r-- 1 root root  636 2011-06-20 22:40 ta.key
-rw-r--r-- 1 root root 1537 2011-06-20 22:40 ca.crt
-rw-r--r-- 1 root root 1704 2011-06-20 22:40 bear.key
-rw-r--r-- 1 root root 5053 2011-06-20 22:40 bear.crt
-rw-r--r-- 1 root root  185 2011-06-21 20:13 bear.conf
root@bear:/etc/openvpn# /etc/init.d/openvpn restart
</pre>
<h4>Resources</h4>
<p>* <a href="https://help.ubuntu.com/community/OpenVPN">https://help.ubuntu.com/community/OpenVPN</a><br />
* <a href="http://openvpn.net/index.php/open-source/documentation/howto.html">http://openvpn.net/index.php/open-source/documentation/howto.html</a><br />
* <a href="http://openvpn.net/index.php/open-source/documentation/miscellaneous/76-ethernet-bridging.html">http://openvpn.net/index.php/open-source/documentation/miscellaneous/76-ethernet-bridging.html</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jmorano.moretrix.com/2011/06/connect-your-home-and-company-networks-with-openvpn/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>IPtables Firewall Script</title>
		<link>https://jmorano.moretrix.com/2010/10/iptables-firewall-script/</link>
		
		<dc:creator><![CDATA[insaniac]]></dc:creator>
		<pubDate>Mon, 18 Oct 2010 13:29:49 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Dev]]></category>
		<category><![CDATA[IPTables]]></category>
		<category><![CDATA[UNIX]]></category>
		<guid isPermaLink="false">http://jmorano.moretrix.com/?p=397</guid>

					<description><![CDATA[Some years ago, I had been searching the Internet quite a lot for a descent and simple firewall&#8230;]]></description>
										<content:encoded><![CDATA[<p>Some years ago, I had been searching the Internet quite a lot for a descent and simple firewall script. I wanted maximum security and less as possible complexity. Most of the scripts back then, were made for huge network environments or for DSL users. None of them seemed to cover the simple server protection through IPtables.</p>
<p>So I started gathering information, reading articles and fiddling my own IPtables firewall script.<br />
<span id="more-397"></span><br />
Eventually over the years, the script quite big and is still easy to maintain.</p>
<p>The script itself has quite a lot of comments and should explain itself.</p>
<pre class="brush:shell">
#!/bin/bash
### BEGIN INIT INFO
# Provides:          firewall
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: Start/stop firewall script from hell
### END INIT INFO


# Description: Simple firewall script
# Author: Johnny Morano <insaniac@moretrix.com>
# Version: 0.04
# Usage:
#    ./firewall.sh 


#---------#
# History #
#---------#
 
# 0.01 .... Initial release, based on http://iptables-tutorial.frozentux.net/iptables-tutorial.html
# 0.02 .... Added more security by reading http://www.brandonhutchinson.com/iptables_fw.html
# 0.03 .... Added even more shit thanks to http://danieldegraaf.afraid.org/info/iptables/examples
# 0.04 .... Using ULOGD now for traffic accounting (inspired by http://tumbleweed.org.za/2008/04/02/bandwidth-accounting-ulogd)
# 0.05 .... Loading modules through modprobe

#---------------#
# Configuration #
#---------------#

IPTABLES=/sbin/iptables
SYSCTL=/sbin/sysctl
MODPROBE=/sbin/modprobe

#----------------#
# Initialization #
#----------------#

echo 
echo "    #---------------------------#"
echo "    # Firewall Script From Hell #"
echo "    #---------------------------#"
echo "                 by Johnny Morano"
echo

#
# Module loading
#
echo "Preload IP-Tables modules..."
$MODPROBE ip_tables
$MODPROBE iptable_nat
$MODPROBE iptable_mangle
$MODPROBE iptable_filter
$MODPROBE ipt_REJECT
$MODPROBE ipt_ULOG
$MODPROBE nf_nat
$MODPROBE nf_conntrack
$MODPROBE nf_conntrack_ipv4
$MODPROBE nf_conntrack_ftp

#
# Drop ICMP echo-request messages sent to broadcast or multicast addresses
#
echo "Enable network security settings..."
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses

#
# Drop source routed packets
#
echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

#
# Enable TCP SYN cookie protection from SYN floods
#
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

#
# Don't accept ICMP redirect messages
#
echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects

#
# Don't send ICMP redirect messages
#
echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects

#
# Enable source address spoofing protection
#
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter

#
# Log packets with impossible source addresses
#
echo 1 > /proc/sys/net/ipv4/conf/all/log_martians

#
# Disable some ICMP settings that can be insecure
# Some of these were already disabled by the above echo statements
#
echo "Disable some ICMP settings..."
$SYSCTL -q -w net.ipv4.icmp_ignore_bogus_error_responses=1
$SYSCTL -q -w net.ipv4.icmp_echo_ignore_all=0
$SYSCTL -q -w net.ipv4.icmp_echo_ignore_broadcasts=1
$SYSCTL -q -w net.ipv4.icmp_ratelimit=1000

echo "Enable some extra network security..."
$SYSCTL -q -w net.ipv4.conf.all.accept_redirects=0
$SYSCTL -q -w net.ipv4.conf.all.accept_source_route=0
$SYSCTL -q -w net.ipv4.conf.all.rp_filter=1
$SYSCTL -q -w net.ipv4.conf.all.log_martians=1
$SYSCTL -q -w net.netfilter.nf_conntrack_acct=1

#
# Prevent SYN flood
#
$SYSCTL -q -w net.ipv4.tcp_syncookies=1

#
# Don't accept TCP connections unless we were here for their establishment
#
if [ -e /proc/sys/net/netfilter/ ]; then
        $SYSCTL -q -w net.netfilter.nf_conntrack_tcp_loose=1
else
        $SYSCTL -q -w net.ipv4.ip_conntrack_tcp_loose=1
fi
 
#
# Create policies and flush chains, then delete rules
#
echo "Creating default policies..."
$IPTABLES -P INPUT ACCEPT  
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -P FORWARD DROP  

echo "Flushing and deleting chains..."
for type in filter mangle nat; do
        echo "- Flushing, deleting and zeroing chains for $type"
        $IPTABLES -t $type -F
        $IPTABLES -t $type -X
        $IPTABLES -t $type -Z
done

# 
# Accounting stuff
#
echo "Creating accounting chains"
$IPTABLES -t mangle -N incoming
$IPTABLES -t mangle -N outgoing
$IPTABLES -t mangle -F incoming
$IPTABLES -t mangle -F outgoing

#$IPTABLES -t mangle -A incoming -p tcp --dport 80  -m comment --comment  "Incoming http TCP connections"
#$IPTABLES -t mangle -A incoming -p tcp --dport 443 -m comment --comment  "Incoming http/ssl TCP connections"
#$IPTABLES -t mangle -A incoming -p tcp --dport 22  -m comment --comment  "Incoming ssh TCP connections"
#$IPTABLES -t mangle -A incoming -p tcp --dport 21  -m comment --comment  "Incoming ftp TCP connections"
#$IPTABLES -t mangle -A incoming -p tcp --dport 25  -m comment --comment  "Incoming smtp TCP connections"
$IPTABLES -t mangle -A incoming -p tcp -m comment --comment  "Incoming TCP connections"

$IPTABLES -t mangle -A incoming -p udp -m comment --comment  "Incoming UDP connections"
$IPTABLES -t mangle -A incoming -p icmp -m comment --comment "Incoming ICMP connections"

$IPTABLES -t mangle -A outgoing -p tcp -m comment --comment  "Outgoing TCP connections"
$IPTABLES -t mangle -A outgoing -p udp -m comment --comment  "Outgoing UDP connections"
$IPTABLES -t mangle -A outgoing -p icmp -m comment --comment "Outgoing ICMP connections"

echo "Adding accounting to PRE- and POSTROUTING"
$IPTABLES -t mangle -A PREROUTING -i eth0 -j incoming
$IPTABLES -t mangle -A POSTROUTING -o eth0 -j outgoing

#
# Create a LOGDROP chain to log and drop packets
#
echo "Creating LOGDROP chain..."
$IPTABLES -N LOGDROP
$IPTABLES -F LOGDROP
#$IPTABLES -A LOGDROP -j LOG --log-prefix "firewall dropped packet: " --log-tcp-options --log-ip-options --log-uid -m limit --limit 2/sec
$IPTABLES -A LOGDROP -j ULOG --ulog-prefix "FIREWALL DROPPED" --ulog-nlgroup 1
$IPTABLES -A LOGDROP -p tcp -j REJECT --reject-with tcp-reset -m comment --comment "Reject TCP connections with tcp-reset"
$IPTABLES -A LOGDROP -p udp -j REJECT --reject-with icmp-port-unreachable -m comment --comment "Reject UDP connections with icmp-port-unreachable"
$IPTABLES -A LOGDROP -j DROP

#
# Create TCP_CHAIN chain
#
for CHAIN in TCP_CHAIN BAD_TCP TCP_SLOWLORIS ICMP_CHAIN UDP_CHAIN ; do
        echo "Creating chain $CHAIN..."
        $IPTABLES -N $CHAIN
        $IPTABLES -F $CHAIN
done

#----------------#
# Firewall rules #
#----------------#
#

#
# allow localhost services
#
echo "Accept localhost connections..."
$IPTABLES -A INPUT -i lo -s 0/0 -d 0/0 -j ACCEPT
$IPTABLES -A OUTPUT -o lo -s 0/0 -d 0/0 -j ACCEPT

#
#
# Allow network connections which have already been established (started by host) and related to your connection.
# FTP requires this as it may use various ports in support of the file transfer.)
#
echo "Set up established state..."
$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -m comment --comment "Allow established incoming connections"
$IPTABLES -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT -m comment --comment "Allow established outgoing connections"

#
# Block Fragments
#
echo "Drop Fragments on INPUT"
$IPTABLES -A INPUT -f -j LOGDROP -m comment --comment "Fragments Packets"

#
# Block bad TCP stuff
#
echo "Drop bad TCP packets (portscans, spoofing, ...)"
$IPTABLES -A BAD_TCP -p tcp ! --syn -m state --state NEW -j LOGDROP -m comment  --comment "Drop Sync"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL ALL -j LOGDROP -m comment           --comment "XMAS Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL NONE -j LOGDROP  -m comment         --comment  "NULL Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j LOGDROP -m comment --comment "Merry XMAS Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL FIN,URG,PSH -j LOGDROP -m comment   --comment "NMAP XMAS Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL PSH,ACK -m state --state RELATED -j LOGDROP -m comment --comment "Drop ALL PSH,ACK state RELATED"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL SYN,ACK,PSH -j LOGDROP -m comment   --comment "Drop ALL SYN,ACK,PSH"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ALL SYN,PSH -j LOGDROP -m comment       --comment "Drop ALL SYN,PSH"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags SYN,RST SYN,RST -j LOGDROP -m comment   --comment "SYN/RST Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags RST,FIN RST,FIN -j LOGDROP -m comment   --comment "RST/FIN Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags SYN,URG SYN,URG -j LOGDROP -m comment   --comment "SYN/URG Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags SYN,ACK SYN,ACK -m state --state NEW -j REJECT --reject-with tcp-reset -m comment --comment "SYN/ACK Attack"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags SYN,FIN SYN,FIN -j LOGDROP  -m comment  --comment  "SYN/FIN Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags SYN,ACK NONE -j LOGDROP -m comment      --comment "Drop SYN,ACK NONE"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ACK,FIN FIN -j LOGDROP -m comment       --comment "Drop ACK,FIN FIN"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ACK,PSH PSH -j LOGDROP -m comment       --comment "Drop ACK,PSH PSH"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags ACK,URG URG -j LOGDROP -m comment       --comment "Drop ACK,URG URG"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags FIN,ACK FIN -j LOGDROP  -m comment      --comment  "Fin Packets Scan"
$IPTABLES -A BAD_TCP -p tcp --tcp-flags FIN,RST FIN,RST -j LOGDROP -m comment   --comment "Drop FIN,RST FIN,RST"

#
# Add BAD_TCP chain as 1st rule to TCP_CHAIN
# 
$IPTABLES -A TCP_CHAIN -j BAD_TCP
 
# ICMP rules
# Allow ping and traceroute
#
echo "Allow ping and traceroute..."
$IPTABLES -A ICMP_CHAIN -p icmp -s 0/0 --icmp-type 8 -j ACCEPT -m comment --comment "Allow ICMP ping"
$IPTABLES -A ICMP_CHAIN -p icmp -s 0/0 --icmp-type 11 -j ACCEPT -m comment --comment "Allow ICMP traceroute"


##
## Disable port-scans (part 1)
## 
#echo "Disable portscans..."
#$IPTABLES -A INPUT -m recent --update --hitcount 16 --name portscanblock --seconds 3600 -j LOGDROP
#$IPTABLES -A INPUT -m recent --name portscanblock --set -m tcp -p tcp --tcp-flags ! SYN,RST,ACK,FIN SYN -j LOGDROP

#
# Prevents more than 2 SSH connections per minute, to slow down SSH scans
# Allow connections to SSH server, but only allow 2 connections from one IP
#
echo "Allow only 2 SSH connections /minute and not more than 4 connections in total..."
$IPTABLES -A TCP_CHAIN -p tcp -m tcp --dport 22 -m recent --update --hitcount 2 --seconds 60 --name sshsin -j LOGDROP -m comment --comment "Drop SSH connection if more than 2 in 60 secs"
$IPTABLES -A TCP_CHAIN -p tcp --syn --dport 22 -m connlimit --connlimit-mask 32 --connlimit-above 4 -j LOGDROP -m comment --comment "Don't allow more than 4 connections"
$IPTABLES -A TCP_CHAIN -p tcp -m tcp --syn --dport 22 -m recent --set --name sshsin -j ACCEPT -m comment --comment "Allow TCP connections to ssh"

#
# Allow traffic to webserver
#
echo "Allow web traffic..."
# Small defense against slowloris
$IPTABLES -A TCP_CHAIN -p tcp --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 32 -j LOGDROP -m comment --comment "Allow only 20 connections per IP to port 80"
# This chain will be provisioned from /root/bin/block_slowloris_attacks.sh
$IPTABLES -A TCP_CHAIN -p tcp --dport 80 -j TCP_SLOWLORIS

$IPTABLES -A TCP_CHAIN -p tcp --dport 80 -j ACCEPT -m comment --comment "Allow TCP connections to http"
$IPTABLES -A TCP_CHAIN -p tcp --dport 443 -j ACCEPT -m comment --comment "Allow TCP connections to https"

#$IPTABLES -A TCP_CHAIN -p tcp --dport 6000 -j ACCEPT -m comment --comment "Allow TCP connections to X11"
#$IPTABLES -A TCP_CHAIN -p udp --dport 6000 -j ACCEPT -m comment --comment "Allow UDP connections to X11"

#
# Allow traffic to mail platform
#
echo "Allow mail traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport  25 -j ACCEPT -m comment --comment "Allow TCP connections to smtp"
$IPTABLES -A TCP_CHAIN -p tcp --dport 110 -j ACCEPT -m comment --comment "Allow TCP connections to pop3"
$IPTABLES -A TCP_CHAIN -p tcp --dport 143 -j ACCEPT -m comment --comment "Allow TCP connections to imap"
$IPTABLES -A TCP_CHAIN -p tcp --dport 465 -j ACCEPT -m comment --comment "Allow TCP connections to smtps"
$IPTABLES -A TCP_CHAIN -p tcp --dport 993 -j ACCEPT -m comment --comment "Allow TCP connections to imaps"
$IPTABLES -A TCP_CHAIN -p tcp --dport 995 -j ACCEPT -m comment --comment "Allow TCP connections to pop3s"

#
# Allow traffic to FTP server
#
echo "Allow FTP traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport 20 -j ACCEPT -m comment --comment "Allow TCP connections to ftp-data"
$IPTABLES -A TCP_CHAIN -p tcp --dport 21 -j ACCEPT -m comment --comment "Allow TCP connections to ftp"
$IPTABLES -A TCP_CHAIN -p tcp --dport 989 -j ACCEPT -m comment --comment "Allow TCP connections to ftps-data"
$IPTABLES -A TCP_CHAIN -p tcp --dport 990 -j ACCEPT -m comment --comment "Allow TCP connections to ftps"
$IPTABLES -A TCP_CHAIN -p tcp --dport 115 -j ACCEPT -m comment --comment "Allow TCP connections to sftp"
$IPTABLES -A INPUT -m helper --helper ftp -j ACCEPT


#
# Allow traffic to DNS server
#
echo "Allow FTP traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport 53 -j ACCEPT -m comment --comment "Allow TCP connections to dns"
$IPTABLES -A UDP_CHAIN -p udp --dport 53 -j ACCEPT -m comment --comment "Allow UDP connections to dns"

#
# Allow traffic to database server (needed for replication)
#
echo "Allow MYSQL traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport 3306 -s 88.198.65.228 -j ACCEPT -m comment --comment "Allow TCP connections to mysql"
$IPTABLES -A UDP_CHAIN -p udp --dport 3306 -s 88.198.65.228 -j ACCEPT -m comment --comment "Allow UDP connections to mysql"

#
# Allow traffic to NTP server
#
echo "Allow NTP traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport 123 -j ACCEPT -m comment --comment "Allow TCP connections to ntp"
$IPTABLES -A UDP_CHAIN -p udp --dport 123 -j ACCEPT -m comment --comment "Allow UDP connections to ntp"

#
# Allow traffic to torrent
#
echo "Allow torrent traffic..."
$IPTABLES -A TCP_CHAIN -p tcp --dport 6959 -j ACCEPT -m comment --comment "Allow TCP connections to torrent"
$IPTABLES -A UDP_CHAIN -p udp --dport 6959 -j ACCEPT -m comment --comment "Allow UDP connections to torrent"

#
# Allow traffic to DCC
#
echo "Allow DCC traffic..."
$IPTABLES -A UDP_CHAIN -p udp --dport 6277 -j ACCEPT -m comment --comment "Allow UDP connections to DCC"

#
# Needed for portscan block (part 2)
#
#$IPTABLES -A INPUT -m recent --set --name portscanblock

#
# Allow the ICMP_CHAIN, TCP_CHAIN and UDP_CHAIN chains on INPUT
# 
echo "Add ICMP_, TCP_ and UDP_CHAIN to INPUT..."
$IPTABLES -A INPUT -p icmp -j ICMP_CHAIN
$IPTABLES -A INPUT -p tcp  -j TCP_CHAIN
$IPTABLES -A INPUT -p udp  -j UDP_CHAIN

#
# debugging and logging
#
echo "Log and drop everything else..."
$IPTABLES -p ALL -A INPUT -j LOGDROP -m comment --comment "Drop all packets"
</pre>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
