I seem to work best at night, it’s dark out, and generally quite dark inside too; there is more bandwidth because it is off peek, and in general there is nobody coming over or phoning and interrupting me. Incidentally, its also when I do the majority of my reading, at home; in bed, at night. Much more pleasant that way…
PSAD Anyway, the latest tut I have been post is called “Linux Firewalls – Attack detection and response with iptables, PSAD and FWSNORT” – the site where PSAD, FWSNORT and a fair few other Linux and security tools are developed. Now, you may think that with a title like that your going to have to know a lot about Linux and Firewalls before you begin but that is simply not true, Linux Firewalls takes you right from the very start of how iptables works to manually porting Snort rules over to iptables for detection, and in my humble opinion, it does a damn good job of it. In fact, it done such a good job of it, I have used the reference firewall scripts and PSAD configurations to install and configure iptables and PSAD on my new VPS, which I will hopefully be moving some of my sites to.
Some of the things you should probably have already if you want to get the best out of Linux Firewalls is…
A comfortable familiarity with the distribution of Linux you wish to use.
Basic understanding of how networks communicate.
Reasonable understanding of how TCP works (ie. the three way handshake)
Reasonable understanding of how UDP works
A system to test this stuff on, if you don’t have a system to test this stuff out on, you could always set up a few virtual machines using VirtualBox or VMWare.
A will to learn about this kind of stuff
Missing any one of these things (except the will to learn, thats pretty important) probably isn’t going to be a huge deal, but if your missing a lot of them, you might struggle a bit with some of the concepts.
Here is a sample of one of the basic Linux Firewall scripts that I have adapted from the book…
#!/bin/sh
#Port and IP addresses changed to protect the innocent.
IPTABLES=/sbin/iptables MODPROBE=/sbin/modprobe
### Flush existing rules and settings. Set to default drop. echo"[+] Flushing existing iptables rules..." $IPTABLES-F $IPTABLES-X #$IPTABLES -t nat -F CLICK HERE TO DOWNLOAD FULL SCRIPT (1.82KB)
I hope that this imprompt topics at least some help to you.
It’s inevitable: if your computer is Internet-connected you will have people coming a-knockin’. Fortunately Linux users are more savvy than to think any keep-alive ping or other piece of Internet flotsam is a hack attempt.
Even so, it’s simply a matter of time before your router’s lights flash heavily and /var/log/auth.log (/var/log/secure on RedHat) fills with chilling messages like these:
$ tail /var/log/auth.log Aug 1 20:23:41 www.PCTipsbyAnu.tk sshd[15577]: (pam_unix) authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=61.218.125.178 Aug 1 20:23:44 www.PCTipsbyAnu.tk sshd[15577]: Failed password for invalid user edward from 210.48.230.5 port 43812 ssh2 Aug 1 20:23:46 www.PCTipsbyAnu.tk sshd[15581]: Invalid user javed from 210.48.230.5 Aug 1 20:23:46 www.PCTipsbyAnu.tk sshd[15581]: (pam_unix) check pass; user unknown Aug 1 20:23:46 www.PCTipsbyAnu.tk sshd[15581]: (pam_unix) authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=61.218.125.178 Aug 1 20:23:49 www.PCTipsbyAnu.tk sshd[15581]: Failed password for invalid user javed from 210.48.230.5 port 44088 ssh2 Aug 1 20:23:51 www.PCTipsbyAnu.tk sshd[15585]: Invalid user code from 210.48.230.5 Aug 1 20:23:51 www.PCTipsbyAnu.tk sshd[15585]: (pam_unix) check pass; user unknown Aug 1 20:23:51 www.PCTipsbyAnu.tk sshd[15585]: (pam_unix) authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=61.218.125.178 Aug 1 20:23:53 www.PCTipsbyAnu.tk sshd[15585]: Failed password for invalid user code from 210.48.230.5 port 44346 ssh2
The warnings are clear: someone is trying to log in via sshd, the secure shell daemon, trying random username and password combinations. And, as great as high-bandwidth is, the downside is that malicious forces can attempt thousands of login attempts in a very short time.
Now, the right term for a person who attempts to exploit security is a cracker, but “hacker” – rightfully an inquisitive and enthusiastic person – has been popularised as a malicious meddler. Nevertheless, at this point in time semantics are the last thing on your mind: whether you're being hacked or cracked you’ve got to secure your system and keep out the bad guys.
In fact, someone successfully logging in is only one of your worries. Firstly, each attempt adds several lines to your log files. In time, a lot of disk space is wasted and your logs become almost meaningless with other information you might be seeking being well hidden amongst the tens of thousands of repetitive entries.
And, more importantly, a high-speed multi-threaded attack runs the risk of denying your service by consuming all your bandwidth – let alone system resources. And if your system is too busy handling these connections, how will you log in, yourself?
So then - what do you do?
Lock down sshd The very first step is to beef up the security on SSH itself.
Firstly, you don’t want anyone logging in to your system as root. This gives unfettered power. This doesn’t stop you remoting in to your system using an ordinary user account and su’ing to root. Edit the /etc/ssh/sshd_config file and ensure it has an entry “PermitRootLogin no”. This means ssh will just prevent root logins; any attempt will fail even if the password is right. Best of all, the failure message gives no hint the connection failed because of this rule; it looks like any other bad username/password combo. This means your cracker has to guess a genuine username and password so their work is made much harder.
Depending on how flexible your network is, you might also consider changing the port number that SSH listens on. By default, it uses port 22 and this is the port crackers will be attempting to use. You could change this to some other arbitrary port. You will still be able to SSH in, specifying the appropriate port number, but others will have no success unless they realise firstly there’s another port open, and secondly that it is used for SSH (the fact a non-standard port is open gives no immediate information as to the protocol it uses.) Once again, edit /etc/ssh/sshd_config and set a customised port number on the ListenAddress line.
This is a good start. Yet, there’s still more to do. The biggest problem is there’s no built-in mechanism to stop repeated login attempts from the same IP address, even if it is failing continually.
Fortunately, all modern Linux distros come standard with a built-in firewall package known as netfilter/iptables. Netfilter is the framework that interacts with the kernel to inspect network packets; iptables is a firewall component which uses netfilter to filter packets based on specified rules. (Previously, the predominant package for this purpose was ipchains.)
Well and good, but unfortunately, iptables has no built-in rules to protect against brute force attacks. It’s installed, but it’s just sitting there idle.
Recently, CODE MOBILE faced this very problem. He solved his issue with two dead simple iptables rules that everyone can use. These are:
sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 8 --rttl --name SSH -j DROP
This pair of commands rate-limits all incoming SSH connections to eight per minute. A valid user who knows their username and password won’t be inconvenienced at all, but brute-force crackers will have their connection attempts – each being a try at a username and password – dropped right down to eight from the lofty number otherwise offered by high-speed data networks.
You can use iptables –L at any time to list your firewall rules and you can use iptables –F at any time to flush the rules. It’s definitely worthwhile checking Kevin’s blog for more detail on his rules, including how to make them take effect upon system boot.
iptables – Plan B
The rules above are clear and concise. The problem is they don’t really send a strong message to the cracker to go away. 2020Code strive for more protection with stricter iptables rules:
Firstly, a two-second pause is forced between successive SSH connections from the same host, slowing down login attempts.
Secondly, if the same host attempts (and fails) connection five times within the span of one minute, the host is automatically blacklisted.
Thirdly, this block lapses after a full hour passes with no connection attempts from the host.
This is much more industrial strength. Now the cracker only gets five chances every sixty-one minutes. They’ll soon move on to other grounds. The downside is fat-fingered legitimate users can potentially lock themselves out, and this is especially problematic if you have possibly many users from behind a NAT’d network who legitimately need to connect to your system and some of the users are slightly forgetful or password-challenged.
sshblack
You might prefer not to edit the iptables rules yourself. Or, you may want rules which exercise more intelligence so that genuine users, albeit absent-minded, aren’t locked out.
In this case, sshblack is a freely-downloaded Perl script that eases the burden. It actively monitors log files for any concerning activity and reacts to aggressive attacks by adding their IP address to a blacklist. Any host attempting a connection which is found in the blacklist is prevented from making an SSH connection. After a period of time, the host is removed from the blacklist. The script can send e-mail notices keeping you aware of any possible concerns.
The downsides to sshblack are that it hasn’t been updated since 2006, and also that it works by parsing log files. This means it doesn’t necessarily react instantaneously to cracking attempts depending on the processor’s load.
DenyHosts
We've saved the best to last. Now you know the problem and approaches to solving it, there’s another terrific option, the SourceForge project called DenyHosts, written in Python. Like all the above, the fundamental purpose is to thwart SSH attacks by blocking IP addresses which appear to be engaging in malicious behaviour. Where DenyHosts differs is that it isn’t running in isolation. The above solutions will reject hosts after they’ve already made failed attempts on your computer; by contrast DenyHosts uses a communal database to proactively protect your system. You need not even suffer one connection attempt by a host which has been detected as hostile by others.
DenyHosts is a snap to set up. Just install the RPM or unpack the tarball – both available for free download from SourceForge. Out of all the methods surveyed here, DenyHosts is the slickest and most elegant. Its one catch is that it is tied to the version of Python installed. This means you need to exercise caution whenever upgrading Python. Alternatively, you can install multiple versions of Python in different directories.
It’s not uncommon to have crackers survey your system. Sadly, it’s also not uncommon for people to overlook security options. The above techniques can make the difference on your computer and bolster your security and peace of mind.
The iptables tool is a magnificent means of securing a Linux box. But it can be rather overwhelming. Even after you gain a solid understanding of the command structure and know what to lock down and how to lock it down, iptables can be confusing. But the nice thing about iptables is that it’s fairly universal in its protection. So having a few iptables rules to put together into a script can make this job much easier.
With that in mind, let’s take a look at 10 such commands. Some of these rules will be more server oriented, whereas some will be more desktop oriented. For the purpose of this article, I’m not going to explain all of the various arguments and flags for iptables. Instead, I’ll just give you the rule and explain what it does.
For more information on the specifics of the rule, you can read the man page for iptables, which will outline the arguments and flags for you.
1: iptables -A INPUT -p tcp -syn -j DROP
This is a desktop-centric rule that will do two things:
First it will allow you to actually work normally on your desktop. All network traffic going out of your machine will be allowed out, but all TCP/IP traffic coming into your machine will simply be dropped. This makes for a solid Linux desktop that does not need any incoming traffic. What if you want to allow specific networking traffic in —
for example, ssh for remote management? To do this, you’ll need to add an iptables rule for the service and make sure that service rule is run before rule to drop all incoming traffic.
2:iptables -A INPUT -p tcp –syn –destination-port 22 -j ACCEPT
Let’s build on our first command. To allow traffic to reach port 22 (secure shell), you will add this line. Understand that this line will allow any incoming traffic into port 22. This is not the most secure setup alone. To make it more secure, you’ll want to limit which machines can actually connect to port 22 on the machine. Fortunately, you can do this with iptables as well. If you know the IP address of the source machine, you can add the -s SOURCE_ADDRESSoption (Where SOURCE_ADDRESS is the actual address of the source machine) before the –destination-port portion of the line.
3:/sbin/iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
This will allow all previously initiated and accepted exchanges to bypass rule checking.
The ESTABLISHED and RELATED arguments belong to the –stateswitch.
The ESTABLISHED argument says, “Any packet that belongs to an existing connection,” and the RELATED argument says, “Any packet that does not belong to an already existing connection but is related to an existing connection.” The “state machine” of iptables is a means for iptables to track connections with the help of the kernel level “conntrack” module. By tracking connections, iptables knows what connections can be allowed and what can’t. This reduces the amount of work the administrator has to do.
Here’s how state works. If the local user initiates a connection, that packet (to that connection) is set as NEW in the prerouting chain. When the local user gets a return packet, the state is changed to ESTABLISHED in the prerouting chain. So when a state is set as ESTABLISHED, it can be allowed with the right iptables rule.
4:iptables -N LOGDROP
With this handy chain, iptables will log all dropped packets. Of course, this is only part of the chain. To complete it, you need to add the follow two rules:
iptables -A logdrop -J LOG and iptables -A logdrop -J DROP
Now all matching packets (in this case, anything that has been dropped) will be added to the logdrop chain which will log them and then drop them.
When you need to route packets from external sources to specific ports on specific internal machines, this is what you want to do. This rule takes advantage of network address translation to route packets properly. To suit your needs, the WLAN_INTERFACE must be changed to the WLAN interface that bridges the external network to the internal network, the PORTNUMBERS must be changed, and DESTINATION_IP must be changed to match the IP address of the destination machine.
6:iptables -A INPUT -p tcp –syn –dport 25 -j ACCEPT
This is the beginning of a SYN flood protection rule. This portion of the rule blocks DoS attacks on a mail server port. (You can change this to suit your mail server needs.) There are three more portions of this rule set. The first is to add the same rule but modify the port to whatever is being served up by whatever ports you have open. The next portion is iptables -A INPUT -p tcp –syn -m limit –limit 1/s –limit-burst 4 -j ACCEPT, which is the actual SYN flood protection. Finally, iptables -A INPUT -p tcp –syn -j DROP will drop all SYN flood packets.
7:iptables -A INPUT -p tcp -m tcp -s MALICIOUS_ADDRESS -j DROP
This is where you can take care of malicious source IP addresses. For this to work properly, you must make sure you know the offending source IP address and that, in fact, it’s one you want to block. The biggest problem with this occurs when the offending address has been spoofed. If that’s the case, you can wind up blocking legitimate traffic from reaching your network. Do your research on this address.
8:iptables -N port-scan
This is the beginning of a rule to block furtive port scanning. A furtive port scan is a scan that detects closed ports to deduce open ports. Two more lines are needed to complete this rule:
iptables -A port-scan -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s -j RETURN iptables -A port-scan -j DROP
Notice that the above rule set is adding a new chain called “port-scan”. You don’t have to name it such; it’s just easier to keep things organized. You can also add timeouts to the above rule set like so:
iptables -A specific-rule-set -p tcp --syn -j syn-flood iptables -A specific-rule-set -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j port-scan
9:iptables -A INPUT -i eth0 -p tcp -m state –state NEW -m multiport –dports ssh,smtp,http,https -j ACCEPT
What you see here is a chain making use of the multiport argument, which will allow you to set up multiple ports. Using the multiport argument lets you write one chain instead of multiple chains. This single rule saves you from writing out four separate rules, one each for ssh, smtp, http, and https. Naturally, you can apply this to ACCEPT, DENY, REJECT.
10:iptables -A PREROUTING -i eth0 -p tcp –dport 80 -m state –state NEW -m nth –counter 0 –every 4 –packet 0 -j DNAT –to-destination 192.168.1.10:80
If you’re looking to load balance between multiple mirrored servers (in the example case, load balancing a Web server at 192.168.1.10), this rule is what you want. At the heart of this rule is the nth extension, which tells iptables to act on every “nth” packet. In the example, iptables uses counter 0 and acts upon every 4th packet. You can extend this to balance out your mirrored sites this way. Say you have four mirrored servers up and you want to balance the load between them. You could have one line for each server like so:
1:iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth
As you can see the server on .10 will be routed every 0 packet, the server on .20 will be routed every 1st packet, the server on .30 will be routed every 2nd packet, and the server on .40 will be routed every 3rd packet.
Other options?
These 10 iptables rules will help you secure your Linux server. Of course, with anything Linux, there are multiple possibilities to achieve the same results. But these rules should serve as an outstanding springboard for Linux server security — as well as Linux security discussion.