Linux - SecurityThis forum is for all security related questions.
Questions, tips, system compromises, firewalls, etc. are all included here.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I had moved this from another forum... I should not have had it there, please forgive me for mis-labeling!
Version:
Linux version 2.6.18-028stab093.2 (root@rhel5-build-x64) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)) #1 SMP Tue Aug 23 16:27:58 MSD 2011
CentOS release 5.5 (Final)
I have root access on my VPS.
I keep adding rules to iptables, I save, and everything is good for awhile. But without restarting, eventually it is cleared and I have no idea why! I am going to guide you through exactly what I am doing:
1) I log in to the VPS
2) List the iptable contents:
now... if I wait for a little while... POOF they are gone again! I know these things are stored in memory, is there some other service that can be restarting that could be clearing iptables -t filter?
This is on a web server, could I edit etc/init.d/httpd and add the line "service iptables start" somewhere to ensure if httpd restarts it restarts iptables too?
There has to be something actively clearing this out
check your crontab for something like the following....
Code:
*/10 * * * * /sbin/iptables -F
This would actually be advisable anyway while testing firewall rules just in case you lock yourself out, but to have it in there once you release into production, etc., is going to produce the problem you have pointed out.
I like to disable selinux too, but that's prolly not the problem.
Question: Is this an OpenVZ VPS?
Lemme know I'm interested in following your issue.
No CronTabs set up right now... but yeah, I probably should do that while testing.
Code:
[root@server init.d]# crontab -l
no crontab for root
Not really sure how to determine if it is a OpenVZ VPS. I know it says something like "Parallels Virtuozzo Containers 4.0" and runs the "Parallels Power Panel".
The reason I am all over this iptables thing right now is I have been getting dozens of "brute force monitor" emails from Direct Admin's new brute force monitor (control panel for my web sites).
I have a script I am integrating in to direct admin to populate iptables when and IP Address goes over 20 attempts in 24 hours. (and it is not my ip of course )
This is on a web server, could I edit etc/init.d/httpd and add the line "service iptables start" somewhere to ensure if httpd restarts it restarts iptables too?
NO. don't do that (but the answer to your question is yes you could).
Your firewall should start long before any services like that.
Do some of the following so we can see just what your setup for:
Put all of your rules into the /etc/sysconfig/iptables file. This is the default and when you start your firewall with either 'service iptables start|stop|restart' or '/etc/init.d/iptables start|stop|restart', that's the file that is expected to contain your rules.
Again, don't start your firewall from /etc/init.d/httpd!!! - it has its own startup script at /etc/init.d/iptables
You may also like to see what's going on in realtime (well, one second increments anyway) to see exactly when your firewall is getting hosed:
Code:
# watch -n1 netstat -tulpn
and
Code:
watch -n1 iptables -L
Personally, I'm not a fan of saving my netfilter tables. I like to know that my firewalls are starting from my script (/etc/sysconfig/iptables) and that it is exactly as that file specifies.
Since your firewall should start at boot right at the point where the network services are coming up (and obviously before SSHD or HTTPD), any changes you make or need to make will be reflected in the firewall script, not some saved configuration you may not be completely sure about - but that's just me.
As I mentioned before, I'm not a fan of selinux. It does have its uses at times, but I hardly ever use it and therefore completely disable it. selinux interferes with some things in weird ways, and you'll find that many install docs have you disable it before beginning your setups.
If you don't know that you need it. I recommend disabling it (Yes, some RH'ers will prolly flame me for that advice but many distros don't even include it because of these reasons).
A quick way to turn it off is below:
Code:
# setenforce 0
# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
FYI: I haven't addressed IPv6 here
I hope that helps
Kindest regards,
.
Last edited by tallship; 01-05-2012 at 08:25 PM.
Reason: maek pritty
No CronTabs set up right now... but yeah, I probably should do that while testing.
Code:
[root@server init.d]# crontab -l
no crontab for root
Not really sure how to determine if it is a OpenVZ VPS. I know it says something like "Parallels Virtuozzo Containers 4.0" and runs the "Parallels Power Panel".
Okay. Yes, it's OpenVZ. Rather, it's the commercial version (Parallels).
I know what's going on now. You're fighting yourself
The Parallels power panel is where you should be inserting your firewall rules. doing it directly on the CLI will get wiped as there are all kinds of automated monitors and safeguards built into your VPS.
So unless you disable that stuff, just use their control panel gui for your container and make your adjustments there. That includes cronjobs, etc.
What's happening is since the changes aren't being made via their control panel, they're getting wiped because they're not in that firewall app in the control panel - it's annoying, but for the purposes of having a point and click management tool it's a good thing, since, if someone were to do some weird things to your machine it would get reset (ergo, the source of your frustrations).
Quote:
Originally Posted by markbad311
The reason I am all over this iptables thing right now is I have been getting dozens of "brute force monitor" emails from Direct Admin's new brute force monitor (control panel for my web sites).
Okay, put these two lines in (noting that port 22 is SSH by default unless you have changed it, so change that to whatever port your SSH daemon is listening on if you did change it.
Code:
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 14495 --hitcount 8 --rttl --name SSH -j DROP
Most people put the seconds to 60, which rate limits it but heck, make it something like a big prime number because you have a console you can log into w/Parallels anyway if you lock yourself out from being able to ssh in and besides that, LOL, you prolly aren't going to mess up your login 8 times in a row
This will make those brute force attacks *vanish*
Quote:
Originally Posted by markbad311
I have a script I am integrating in to direct admin to populate iptables when and IP Address goes over 20 attempts in 24 hours. (and it is not my ip of course )
Excellent. But I'm a little bit meaner. I do it either forever or like I mentioned above, with a REALLY BIG PRIME number.
The reason being is that certain intervals like 60 seconds, 5 minutes, 60 minutes, and 24 hours are easy for a prober to ascertain, and they'll get another 20 attempts, which in the case of a weak password might be able to get cracked in a year or two of you not even knowing it's still going on.
Call me paranoid, but if you do, call me secure
One last thing, you might want to take a gander at my article on securing SSHD at my website below. It's pretty comprehensive as a guide to disable passwords completely and use encrypted keys instead, as well as changing the port that SSHD listens on.
Some people even run two SSH daemons, one which is on 22 and does nothing but waste the time of the scanners and one that is on an obscure port that you use.
All in all it sounds like you're taking security seriously, which is not only commendable, but will save you from a lot of tears and hard lessons other people just don't seem to ever learn.
Lemme know if this takes care of your problem okay?
Kindest regards,
.
Last edited by tallship; 01-05-2012 at 08:50 PM.
Reason: fix typo
So unless you disable that stuff, just use their control panel gui for your container and make your adjustments there. That includes cronjobs, etc.
Let's hope I can, because I rarely can log in to the darned thing. I always have to login via my IP address, and it always resets my connection to my browser.
So, really... that is what I am now on the hunt for. How to disable their iptable "wiper" because frankly, I think iptables is more secure from what I read, and I can more easily script iptables from the brute force monitor using php or a cron job.
Code:
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 14495 --hitcount 8 --rttl --name SSH -j DROP
I guess the trick would be to get this in to their GUI rather then iptables right? At least until it is disabled.
Besides, I get goofy errors with some of the more complex rules:
Code:
[root@server ~]#iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables: Unknown error 4294967295
Quote:
Originally Posted by tallship
All in all it sounds like you're taking security seriously, which is not only commendable, but will save you from a lot of tears and hard lessons other people just don't seem to ever learn.
My plan is to build a easier to use, read, track, and block system off of direct admin's brute force monitor.
Insert records in a mysql db automatically based on your brute force monitor's criteria for notifications
Create rules on the fly, and rebuild the iptable nightly and restart the service
send me a end of the week security report.
send me a "high activity" sms alert anytime activity reaches a to be determined level.
I am also going to integrate the same system with my web request forms, so when I or clients get spammed, it gets added from a link in the email and that dude is done for.
I will keep you updated, have not found anything definitive yet.
Last edited by markbad311; 01-05-2012 at 10:15 PM.
Reason: spelling
Here is the unique IP addresses and their rules the last 15k hits
Code:
[root@server etc]# service iptables status
Table: mangle
Chain PREROUTING (policy ACCEPT)
num target prot opt source destination
Chain INPUT (policy ACCEPT)
num target prot opt source destination
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
num target prot opt source destination
Table: filter
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 DROP all -- 109.73.10.10 0.0.0.0/0
2 DROP all -- 112.220.98.51 0.0.0.0/0
3 DROP all -- 118.213.88.23 0.0.0.0/0
4 DROP all -- 118.26.232.230 0.0.0.0/0
5 DROP all -- 125.131.117.212 0.0.0.0/0
6 DROP all -- 125.88.112.11 0.0.0.0/0
7 DROP all -- 178.18.16.145 0.0.0.0/0
8 DROP all -- 180.153.139.4 0.0.0.0/0
9 DROP all -- 182.18.188.46 0.0.0.0/0
10 DROP all -- 184.107.124.76 0.0.0.0/0
11 DROP all -- 190.136.182.156 0.0.0.0/0
12 DROP all -- 200.107.236.164 0.0.0.0/0
13 DROP all -- 201.26.172.55 0.0.0.0/0
14 DROP all -- 202.96.199.150 0.0.0.0/0
15 DROP all -- 208.115.247.251 0.0.0.0/0
16 DROP all -- 210.25.137.232 0.0.0.0/0
17 DROP all -- 211.140.3.183 0.0.0.0/0
18 DROP all -- 211.236.245.187 0.0.0.0/0
19 DROP all -- 218.3.163.67 0.0.0.0/0
20 DROP all -- 219.140.165.85 0.0.0.0/0
21 DROP all -- 222.90.232.36 0.0.0.0/0
22 DROP all -- 49.212.60.183 0.0.0.0/0
23 DROP all -- 60.13.74.178 0.0.0.0/0
24 DROP all -- 60.171.214.30 0.0.0.0/0
25 DROP all -- 62.212.68.132 0.0.0.0/0
26 DROP all -- 66.246.246.13 0.0.0.0/0
27 DROP all -- 85.10.215.12 0.0.0.0/0
28 DROP all -- 88.191.152.141 0.0.0.0/0
29 DROP all -- 88.80.20.1 0.0.0.0/0
30 DROP all -- 91.211.52.53 0.0.0.0/0
31 DROP all -- 91.93.35.75 0.0.0.0/0
32 DROP all -- 93.182.132.103 0.0.0.0/0
33 DROP all -- 95.211.135.151 0.0.0.0/0
34 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
35 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Now since we are on the subject... how can I make this list a little better? I will read the ssh stuff you have Bradley but I am sure there is some quick and dirty I can do... and unfortunately some of the stuff you sent me won't parse;
Code:
[root@server ~]#iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables: Unknown error 4294967295
[root@server ~]#iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables: Unknown error 4294967295
The line looks good and IIRC the error is specific to VPS: a dom0 user has to load and then make available kernel modules first so best contact them and ask.
The line looks good and IIRC the error is specific to VPS: a dom0 user has to load and then make available kernel modules first so best contact them and ask.
I sent my hosting provider a note about this and they said:
Quote:
Thank you for contacting our Technical Support Department.
I have consulted with our administrators on this matter . The reason for the error is that actually your command is not correct at all. Do note that you are on a VPS which is a virtual and not real server. You are trying to set command for eth0 which is a physical network card and does not exist on a virtual server . In the VPS systems the virtual network cards are from the type venetXXX for example.
Let us know if we can do anything else for you.
Then I said to myself... damn, they are right, better check that out:
I can see two things to try: either have a "-i lo -j ACCEPT" as first rule and in subsequent rules just don't list a real or virtual ethernet device name or use the main virtual device name "-i venet0" but specify the alias address, in your case "-i venet0 -s 216.65.1.90" or "-i venet0 -s 209.25.134.76". As for ethernet OpenVZ can be configured with a venet (Layer 3) or veth (Layer 2) virtual ethernet device (see http://wiki.openvz.org/) but that's something the Host Node user configures for a container and not something you can change from inside your VPS.
My initial reason to open this ticket is now resolved.
Does anyone want a free toy?
Here you go:
This piece of php code goes in to your /usr/local/directadmin/data/<username>/ directory. Edit it and give it your db name, userid, and password and it will grab you direct admin log file, and throw it in to that database:
Code:
#!/usr/local/bin/php
<?php
ini_set("display_errors", "1");
ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);
set_time_limit(0);
error_reporting(E_ALL);
$sysHost = "localhost";
$sysDb = "yourdb";
$sysUser = "youdbuser";
$sysPw = "password";
$PATH_TO_LOG = "brute_log_entries.list";
$Conn = mysql_connect($sysHost, $sysUser, $sysPw) or die (mysql_error());
$db = mysql_select_db($sysDb, $Conn) or die (mysql_error());
if (($handle = fopen($PATH_TO_LOG, "r")) !== FALSE)
{
$line = 0;
while (!feof($handle))
{
$line_of_text = urldecode(fgets($handle));
if ($line_of_text != "")
{
$arr = split('&', str_replace("\n", "", strstr($line_of_text, "attempts=")));
if(is_array($arr))
{
for($i=0; $i<count($arr);$i++)
{
$tmpArr = $arr[$i];
$tmpArr = split("=", $tmpArr);
if(is_array($tmpArr))
{
if(isset($tmpArr[0]) && isset($tmpArr[1]))
$arrSplitted[$line][$tmpArr[0]] = $tmpArr[1];
elseif(isset($tmpArr[0]) && !isset($tmpArr[1]))
$arrSplitted[$line][$tmpArr[0]] = '';
}#End array test
}#End File line loop
}#End array test
}#End Empty test
$line++;
}#End While
//Create the table these records will be inserted in to, use if not exists so it won't keep doing it.
$CreateTable = "CREATE TABLE IF NOT EXISTS `dynamiciptables` (
`id` bigint(20) NULL auto_increment,
`ip` varchar(50) NULL,
`user` varchar(50) NULL,
`attempts` int(11) NULL,
`filter` varchar(100) NULL,
`log` text NULL,
`time` int NULL,
PRIMARY KEY (`id`),
KEY `ip` (`ip`,`User`),
KEY `User` (`User`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
mysql_query($CreateTable, $Conn) or die(mysql_error());
//If it is already created, lets nix the contents and insert a fresh copy of the log.
mysql_query("TRUNCATE TABLE `dynamiciptables` ", $Conn) or die(mysql_error());
$flushCount = 1;
$totalInserts = 0;
$sql = 'INSERT INTO `dynamiciptables`(`ip`, `user`, `attempts`, `filter`, `log`, `time`) VALUES ';
for($r=0; $r < count($arrSplitted);$r++)
{
//echo $r . "=>" . $arrSplitted[$r]["ip"] . ', ' . $arrSplitted[$r]["filter"] . ', ' . $arrSplitted[$r]["user"] . ', ' . $arrSplitted[$r]["attempts"]. ', ' . $arrSplitted[$r]["log"]. ', ' . $arrSplitted[$r]["time"] . '<br/>
//';
if($flushCount == 1)
{
$sql = 'INSERT INTO `dynamiciptables`(`ip`, `user`, `attempts`, `filter`, `log`, `time`) VALUES ';
}
else
{
$sql .= ",";
}
$sql .= " ('".sanitize($arrSplitted[$r]["ip"])."', '".sanitize($arrSplitted[$r]["user"])."', '".sanitize($arrSplitted[$r]["attempts"])."', '".sanitize($arrSplitted[$r]["filter"])."', '".sanitize($arrSplitted[$r]["log"])."', '".sanitize($arrSplitted[$r]["time"])."')";
if($flushCount >= 20) #Every 20 lets insert
{
mysql_query($sql .';', $Conn) or die("<strong>SQL</strong>: " . $sql . "<br/><br/><strong>Error</strong>:" . mysql_error());
$sql = '';
$totalInserts += $flushCount;
$flushCount = 0;
}
$flushCount++;
}
echo 'A total of '. $totalInserts . ' records have been added to the "dynamiciptables" table.';
}
else
{
echo 'Did not open file';
}
function sanitize($input)
{
if(get_magic_quotes_gpc())
$input = stripslashes($input);
//I found some instances of html being in the logs.
if(strpos($input,"<") || strpos($input,">"))
$input = str_replace("<","<",str_replace(">",">",$input));
return(mysql_real_escape_string($input));
}
?>
Then we add another file... this file will look at that database, and grab all of the offending ip addresses, and create iptable rules:
Code:
#!/usr/local/bin/php
<?php
ini_set("display_errors", "1");
ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);
set_time_limit(0);
error_reporting(E_ALL);
global $msg;
global $sysHost;
global $sysDb;
global $sysUser ;
global $sysPw;
//LOCAL CODE
$sysHost = "localhost";
$sysDb = "database";
$sysUser = "databaseuser";
$sysPw = "password";
LogError("Logged in as: " . system('whoami'), '', true);
//List IP Tables
LogError(system("iptables -L"), '', true);
//You can add many ips NOT to block here... this is mine, I would hate to get locked out!
$myIP = "'174.100.237.160'";
$conn = mysql_connect($sysHost, $sysUser, $sysPw, true) or die (LogError("writeiptables #25: ". mysql_error(), "DB Connect", false));
$db = mysql_select_db($sysDb, $conn) or die (LogError("writeiptables #26: ". mysql_error(), "DB Select", false));
$sql = "SELECT DISTINCT ip FROM dynamiciptables WHERE ip NOT IN (".$myIP.") GROUP BY ip";
$result = mysql_query($sql, $conn) or die (LogError("writeiptables #29: ". mysql_error(), $sql, false));
if(mysql_num_rows($result) > 0)
{
//Flush IP Tables
LogError(system("iptables -F"), '', true);
//Stop the service
LogError(system("service iptables stop"), '', true);
while($dv = mysql_fetch_array($result))
{
LogError(system("iptables -A INPUT -s " . $dv['ip'] . " -j DROP"), '', true);
}
//a few more rules
LogError(system("iptables -A INPUT -p tcp --dport ssh -j ACCEPT"), '', true);
LogError(system("iptables -A INPUT -p tcp --dport 80 -j ACCEPT"), '', true);
//Save
LogError(system("/sbin/service iptables save"), '', true);
//Start
LogError(system("service iptables start"), '', true);
//Check Status
LogError(system("service iptables status"), '', true);
}
function sanitize($input)
{
if(get_magic_quotes_gpc())
$input = stripslashes($input);
//I found some instances of html being in the logs.
if(strpos($input,"<") || strpos($input,">"))
$input = str_replace("<","<",str_replace(">",">",$input));
return(mysql_real_escape_string($input));
}
//This is an error handling function that I stripped out to just alert things to the console
function LogError($error, $sqlSys, $blnLog)
{
echo $error . "\r\n";
}
LogError("\r\nScript Complete", '', true);
?>
Works perfectly on my production box. Use at your own risk! But let me know if you used it!
Last edited by markbad311; 01-07-2012 at 12:06 AM.
Reason: typo
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.