Thread: Basic Server Security setup
-
29-05-2009, 09:01 #1
Basic Server Security setup
Hi guys this is just a basic linux based server security setup that can help you out somewhat.
Ok so basically first thing is first
If you have cpanel installed but not CSF
log into your ssh the port is usually 22 if you have not changed it yet
in ssh type in this
NOTE* This is for free CSF
Basically what it is doing is downloading the fileCode:rm -fv csf.tgz wget http://www.configserver.com/free/csf.tgz tar -xzf csf.tgz cd csf sh install.sh
csf.tgz to your webserver and taking on the extension .tgz using the
command and then changes to the directory to csfCode:tar -xzf
and then installs it
now we are going to see if you are running the iptables
type this in your ssh
this is basically stating for it to run the script csftest.pl scriptCode:perl /etc/csf/csftest.pl
and inside that script
for future notice you should not use any other
iptables firewall configuration script
so there we go we installed csf now if you want to edit it
you can via ssh by using the pico command pico is user friendly or via cpanel whm
csf will work withCode:/etc/csf/
DirectAdmin , cpanel/ preconfigured wise
now we need to test if klogd us running most vps server disable it
go here
and make sure that any klogd lines are not commented out. Also after done editing restart klogd/etc/init.d/syslog
Webmin Module Installation/Upgrade
Install csf as above
Install the csf webmin module in:
Webmin > Webmin Configuration > Webmin Modules >
how to uninstall it
now that we got csf installed head on over to your whmCode:On cPanel servers: cd /etc/csf sh uninstall.sh On DirectAdmin servers: cd /etc/csf sh uninstall.directadmin.sh On generic linux servers: cd /etc/csf
scroll all the way down and click config server security
after that click check server security it will display a whole lot of red shit
these are errors we aer going to need to fix now bare in mind some of these you usually dont have to fix but that depends on you
Seeing that i aleady dont this i dont really see the errors anymore so ill try to remember them
Basically most of them you will have to edit through tweak settings and of course mysql , easyapache and such
also for more ease on editing the files in the server download winscp
WinSCP :: Download
Login to root and there you can edit all of your files through there instead of editing through ssh.
__________________________________________________ __________________________________________________ ____________________________________
PHP SECURITY
For the php disabling functions i reccomend this but do realize these functions being disabled can cause errors for your clients or such
usual php location
Code:/usr/local/lib/php.ini
After thatCode:apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, openlog, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, xmlrpc_entity_decode,shell_exec, syslog,
Asuming you have php harden installed aka susohin lets move on
I dont have it turned on but its better safe than sorry so if you want to enable php safe_mode
Safe mode is an easy way to lock down the security and functions you can use. PHP.net explains php safe_mode as, "The PHP safe mode is an
attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP
level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for
now."
Now that you have enabled php safe mode lets customize your safe mode to work on websites.
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files
(e.g. httpd.conf) and .htaccess files.
how to turn on safe mode?
Ctrl + W and type in: safe_mode
you will see
make it look like thisCode:safe_mode = Off
Now save the file by ctrl + x then yCode:safe_mode = On
Restart the Apache web server by
Now how to make it work with sites some scripts require safe mode to be turned off but its not so lets fix thatCode:/etc/init.d/httpd restart
SSH to your server and login as root.
Then find the httpd.conf, normally it’s in /etc/httpd/conf/ or /usr/local/apache/conf/
If it’s not in either of those places try search for it: locate httpd.conf
Then find the site you wish to edit.
Ctrl+W and type in the domain name
Now add this line:Code:<VirtualHost ***.***.***.***> ServerAlias www.domain.net domain.net ServerAdmin webmaster@domain.net DocumentRoot /home/domain/public_html BytesLog domlogs/domain.net-bytes_log ServerName www.domain.net User domain Group domain CustomLog domlogs/domain.net combined ScriptAlias /cgi-bin/ /home/domain/public_html/cgi-bin/ </VirtualHost>
if that code does not work type thisCode:php_admin_flag safe_mode Off
now you have to choose one it can not be both and in the end it should look like thisCode:php_admin_value safe_mode 0
Now save the changes.Code:<VirtualHost ***.***.***.***> ServerAlias www.domain.net domain.net ServerAdmin webmaster@domain.net DocumentRoot /home/domain/public_html php_admin_flag safe_mode Off BytesLog domlogs/domain.net-bytes_log ServerName www.domain.net User domain Group domain CustomLog domlogs/domain.net combined ScriptAlias /cgi-bin/ /home/domain/public_html/cgi-bin/ </VirtualHost>
Ctrl + X then Y
Restart the Apache web server by
If you run into trouble after editing httpd.conf you can run the apachectl configtestCode:/etc/init.d/httpd restart
in shell.
Help?
PHP customzing help here
http://php.us.themoes.org/manual/en/...on.changes.php
now The biggest problem with PHP is that on cPanel servers is that PHP will run as nobody. When someone sets a script to 777 access that means the
nobody user has write access to that file. So if someone on the same shared server wrote a script to search the system for 777 files they
could inject anything they wanted, compromising the unsuspecting users account.
PHPsuexec makes PHP run as the user so 777 permissions are not allowed. There are a few downfalls to PHPsuexec but
I think it's required on a shared environment for the security of everyone. Safe_mode doesn't prevent you from compromising other users
files. This is where PHPsuexec comes in, it stops the user from being able to read another users files. It also makes it easier for you, the
administrator, to track PHP mail function spamming and lots of other issues caused by PHP scripts because now you can easily track it ot the
users account responsible.
For this you will need to recompile PHP with suexec. On cPanel /scripts/easyapach has this build in
Stop PHP nobody Spammers
First of all there is 2 ways to do this
in ssh type this
or you can do thisCode:find / -name "[Ff]orm[mM]ai* find / -name "[Cc]giemai*" chmod a-rwx /path/to/filename
Turn off exim while we do this so it doesn't freak out.
[code]
/etc/init.d/exim stop
[code]
backup your original /usr/sbin/sendmail file. On systems using Exim MTA, the sendmail file is just basically a pointer to Exim itself.
Create the spam monitoring script for the new sendmailCode:mv /usr/sbin/sendmail /usr/sbin/sendmail.hidden
or just use winscpCode:pico /usr/sbin/sendmail
Paste in the following:
Change the new sendmail permissionsCode:#!/usr/local/bin/perl # use strict; use Env; my $date = `date`; chomp $date; open (INFO, ">>/var/log/spam_log") || die "Failed to open file ::$!"; my $uid = $>; my @info = getpwuid($uid); if($REMOTE_ADDR) { print INFO "$date - $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME n"; } else { print INFO "$date - $PWD - @infon"; } my $mailprog = '/usr/sbin/sendmail.hidden'; foreach (@ARGV) { $arg="$arg" . " $_"; } open (MAIL,"|$mailprog $arg") || die "cannot open $mailprog: $!n"; while (<STDIN> ) { print MAIL; } close (INFO); close (MAIL);
Create a new log file to keep a history of all mail going out of the server using web scriptsCode:chmod +x /usr/sbin/sendmail
Start Exim up againCode:touch /var/log/spam_log chmod 0777 /var/log/spam_log
Monitor your spam_log file for spam, try using any formmail or script that uses a mail function - a message board, a contact script.Code:/etc/init.d/exim start
log rotation:Code:tail - f /var/log/spam_log
Your spam_log file isn't set to be rotated so it might get to be very large quickly. Keep an eye on it and consider adding it to your logrotation.
FIND:Code:pico /etc/logrotate.conf
ADD BELOW:Code:# no packages own wtmp -- we'll rotate them here /var/log/wtmp { monthly create 0664 root utmp rotate 1 }
You may also want to chattr + i /usr/sbin/sendmail so it doesn't get overwritten.Code:# SPAM LOG rotation /var/log/spam_log { monthly create 0777 root root rotate 1 }
__________________________________________________ __________________________________________________ _______________
Disable Open DNS Recursion
If you are running bind DNS server, then you might want to check your dns server statistics with dnstools.com. You dont want to allow recursive lookups to performed on your server other than local IP. It can also slowdown your server.
nano /etc/named.conf
Under Options { place a line
Then restart the bindCode:Options { recursion no; .....
You will also need to restrict zone transfers and notifications if you are running Bind 9. Refer to: dns server hardeningCode:service named restart
__________________________________________________ __________________________________________________ _______________
Install Mod_Security
ModSecurity is a free open source web application firewall which can help you to guard against LFI (local file inclusion attacks) and SQL injection vulnerabilities.
CPanel Installation:
Just go to Cpanel WHM > Plugins > Enable Mod_Security > Save
Source Installation:
That should install mod security in your cpanel. Under apache it should show under installed modules if you run test.php with phpinfo() in it. Try adding some mod security rules. Installing mod_security could be sometimes complicated. Dont use apxs for compiling mod_security as it causes number of problems.
Note: Mod_security needs libxml2 and http-devel libraries before it can be installed. It also requires mod_unique_id enabled in apache modules. To install mod_unique_id, you have to place
LoadModule unique_id_module modules/mod_unique_id.so
in your httpd.conf file.
Download the latest version of mod_security for apache2 from ModSecurity: Open Source Web Application FirewallCode:yum install libxml2 libxml2-devel httpd-devel
ThenCode:wget http://www.modsecurity.org/download/modsecurity-apache_2.1.7.tar.gz tar zxf modsecurity-apache_2.5.4.tar.gz cd modsecurity-apache_2.5.4 cd apache2
If you cannot find ./configure then you will need to edit Makefile and make change to top_dir = /usr/lib/httpd (for centos)
Next, copy the rule files depending on which you want (you can also select minimal rules file which comes with source). Make a directory named modsecurity under /etc/httpd/conf and copy all the modsecurity rules there. Finally include those files in the httpd.conf fileCode:make make install
# /etc/httpd/conf/httpd.conf
ThenCode:LoadModule unique_id_module modules/mod_unique_id.so LoadFile /usr/lib/libxml2.so LoadModule security2_module modules/mod_security2.so Include conf/modsecurity/*.conf
Log FilesCode:/etc/init.d/httpd restart
Watch for log files to detect any errors or intrusion activity
/var/log/httpd/modsec_audit
/var/log/httpd/error_log
If you get any errors, i have compiled a list of errors while compiling. see here
__________________________________________________ ________________________________
Install Mod_Evasive
ModEvasive module for apache offers protection against DDOS (denial of service attacks) in your server.
then run the following command for apache2..Code:wget http://www.zdziarski.com/projects/mod_evasive/mod_evasive_1.10.1.tar.gz tar zxf mode_evasive-1.10.1.tar.gz cd mod_evasive
Once mod evasive is installed, place the following lines in your /etc/httpd/conf/httpd.confCode:> /usr/sbin/apxs -cia mod_evasive20.c
Follow the instructions in the README for more tuning of mod_evasive. This will compile, install and activate the module in your server.Code:<IfModule mod_evasive20.c> DOSHashTableSize 3097 DOSPageCount 2 DOSSiteCount 50 DOSPageInterval 1 DOSSiteInterval 1 DOSBlockingPeriod 10 </IfModule>
-
29-05-2009, 09:03 #2
Part 2
Install RkHunter (Rootkit)
RKHunter - (RootKit Hunter) Is a security scanning tool which will scan for rootkits, backdoors, and local exploits. RKHunter will ensure you about 99.9% that your dedicated web server is secure.
Lets setup RKHunter to e-mail you you daily scan reports.Code:wget www.sfr-fresh.com/linux/misc/rkhunter-1.3.4.tar.gz tar -xzvf rkhunter-1.3.4.tar.gz cd rkhunter ./installer.sh
Type
Add The Following:Code:pico -w /etc/cron.daily/rkhunter.sh
nowtypeCode:#!/bin/bash (/usr/local/bin/rkhunter -c --cronjob 2>&1 | mail -s "RKhunter Scan Details" replace-this@with-your-email.com)
__________________________________________________ __________________________________Code:chmod +x /etc/cron.daily/rkhunter.sh
Install PortsEntry
Portsentry is a tool to detect port scans and log it. Download the sorce package of portsentry from sourceforge.net
If you get errors like while compilingCode:wget www.sfr-fresh.com/unix/privat/portsentry-1.2.tar.gz tar zxf portsentry-1.2.tar.gz make linux make install
To fixCode:make linux SYSTYPE=linux Making gcc -O -Wall -DLINUX -DSUPPORT_STEALTH -o ./portsentry ./portsentry.c \ ./portsentry_io.c ./portsentry_util.c ./portsentry.c: In function 'PortSentryModeTCP': ./portsentry.c:1187: warning: pointer targets in passing argument 3 of 'accept' differ in signedness ./portsentry.c: In function 'PortSentryModeUDP': ./portsentry.c:1384: warning: pointer targets in passing argument 6 of 'recvfrom' diffe r in signedness ./portsentry.c: In function 'Usage': ./portsentry.c:1584: error: missing terminating " character ./portsentry.c:1585: error: 'sourceforget' undeclared (first use in this function) ./portsentry.c:1585: error: (Each undeclared identifier is reported only once ./portsentry.c:1585: error: for each function it appears in.) ./portsentry.c:1585: error: expected ')' before 'dot' ./portsentry.c:1585: error: stray '\' in program ./portsentry.c:1585: error: missing terminating " character ./portsentry.c:1595: error: expected ';' before '}' token make: *** [linux] Error 1
Open portsentry.c and look for the following line. There will be a extra carriage return breaking the line and you have to delete the carriage return and make single line. It should look like below.
Then run make and make install. That should fix it!Code:printf ("Copyright 1997-2003 Craig H. Rowland <craigrowland at users dot sourceforget dot net>\n");
To launch portsentry
check the log files /var/log/secure on what portsentry is active or not.Code:/usr/local/psionic/portsentry/portsentry -stcp /usr/local/psionic/portsentry/portsentry -sudp
__________________________________________________ ________________________________
Prevent IP Spoofing
IP spoofing is a security exploit and can be prevented from placing nospoof on in host.conf file. Edit the host.conf file and place the following lines. If you run dns bind, give it preference.
__________________________________________________ _______________________________Code:order bind,hosts nospoof on
Install ClamAV
Antivirus protection is the last thing you need for your security to protect against worms and trojans invading your mailbox and files! Just install clamav (a free open source antivirus software for linux). More information can be found on clamav website
Once you have installed clamav in your centos…here are some of the basic commands using the software..Code:yum install clamav
1. To update the antivirus database
2. To run antivirusCode:> freshclam
3. Running as Cron Daily JobCode:clamav -r /home
To run antivirus as a cron job (automatically scan daily) just run crontab -e from your command line. Then add the following line and save the file.
02 1 * * * root clamscan -R /var/www
This will run the cron job daily @ 1.02 AM by scanning the public html. You can change the folder to whatever you want for mail etc.
Disable Telnet & Other Unused Services
You may want to disable services like telnet, finger and other unwanted services running on your server with xinet.
look for lines disable=no and change to disable=yesCode:nano /etc/xinetd.d/telnet // OR nano /etc/xinetd.d/krb5-telnet
__________________________________________________ _________________________________Code:chkconfig telnet off
Install a root breach DETECTOR and EMAIL WARNING
If someone does happen to get root, be warned quickly by installing a detector and warning at your box. You will at least get the hackers/spammers ip address and be warned someone is in there.
Server e-mail everytime someone logs in as root
To have the server e-mail you everytime someone logs in as root, SSH into server and login as root.
At command prompt type:
Scroll down to the end of the file and add the following line:Code:pico .bash_profile
Save and exit.Code:echo 'ALERT - Root Shell Access on:' `date` `who` | mail -s "Alert: Root Access from `who | awk '{print $6}'`" your@email.com
Set an SSH Legal Message
To an SSH legal message, SSH into server and login as root.
At command prompt type:
OR usually its int he /etc/ssh/sshd_configCode:pico /etc/motd
look for banner once inside /etc/ssh create a .txt file called SSH_Banner.txt
and where it shows banner uncomment it and place it with
Enter your message, save and exit.Code:/etc/ssh/ssh_banner.txt
Note: I use the following message...
__________________________________________________ _____________________________________________ALERT! You are entering a secured area! Your IP and login information
have been recorded. System administration has been notified.
This system is restricted to authorized access only. All activities on
this system are recorded and logged. Unauthorized access will be fully
investigated and reported to the appropriate law enforcement agencies.
Install BFD (Brute Force Detection - optional)
To install BFD, SSH into server and login as root.
At command prompt type:
After BFD has been installed, you need to edit the configuration file.Code:cd /root/ wget http://www.rfxnetworks.com/downloads/bfd-current.tar.gz tar -xvzf bfd-current.tar.gz cd bfd-0.4 ./install.sh
At command prompt type:
Under Enable brute force hack attempt alerts:Code:pico /usr/local/bfd/conf.bfd
Save the changes then exit.Code:Find ALERT_USR="0" and change it to ALERT_USR="1" Find EMAIL_USR="root" and change it to EMAIL_USR="your@email.com"
To start BFD
At command prompt type:
__________________________________________________ _________________________________Code:/usr/local/sbin/bfd -s
-
29-05-2009, 09:06 #3
Part 3
Helpful linux commands
System Information
who
List the users logged in on the machine. --
rwho -a
List all users logged in on your network. The rwho service must be enabled for this command to work.
finger user_name
System info about a user. Try: finger root last. This lists the users last logged-in on your system.
history | more
Show the last (1000 or so) commands executed from the command line on the current account. The | more causes the display to stop after each screen fill.
pwd
Print working directory, i.e. display the name of your current directory on the screen.
hostname
Print the name of the local host (the machine on which you are working).
whoami
Print your login name.
id username
Print user id (uid) and his/her group id (gid), effective id (if different than the real id) and the supplementary groups.
date
Print or change the operating system date and time. E.g., change the date and time to 2000-12-31 23:57 using this command
date 123123572000
To set the hardware clock from the system clock, use the command (as root)
setclock
time
Determine the amount of time that it takes for a process to complete+ other info. Don’t confuse it with date command. For e.g. we can find out how long it takes to display a directory content using time ls
uptime
Amount of time since the last reboot
ps
List the processes that are have been run by the current user.
ps aux | more
List all the processes currently running, even those without the controlling terminal, together with the name of the user that owns each process.
top
Keep listing the currently running processes, sorted by cpu usage (top users first).
uname -a
Info on your server.
free
Memory info (in kilobytes).
df -h
Print disk info about all the file systems in a human-readable form.
du / -bh | more
Print detailed disk usage for each subdirectory starting at root (in a human readable form).
lsmod
(as root. Use /sbin/lsmod to execute this command when you are a non-root user.) Show the kernel modules currently loaded.
set|more
Show the current user environment.
echo $PATH
Show the content of the environment variable PATH. This command can be used to show other environment variables as well. Use set to see the full environment.
dmesg | less
Print kernel messages (the current content of the so-called kernel ring buffer). Press q to quit less. Use less /var/log/dmesg to see what dmesg dumped into the file right after bootup. - only works on dedciated systems
Commands for Process control
ps
Display the list of currently running processes with their process IDs (PID) numbers. Use ps aux to see all processes currently running on your system (also those of other users or without a controlling terminal),
each with the name of the owner. Use top to keep listing the processes currently running.
fg
PID Bring a background or stopped process to the foreground.
bg
PID Send the process to the background. This is the opposite of fg. The same can be accomplished with Ctrl z
any_command &
Run any command in the background (the symbol ‘&’ means run the command in the background?).
kill PID
Force a process shutdown. First determine the PID of the process to kill using ps.
killall -9 program_name
Kill program(s) by name.
xkill
(in an xwindow terminal) Kill a GUI-based program with mouse. (Point with your mouse cursor at the window of the process you want to kill and click.)
lpc
(as root) Check and control the printer(s). Type ??? to see the list of available commands.
lpq
Show the content of the printer queue.
lprm job_number
Remove a printing job job_number from the queue.
nice program_name
Run program_name adjusting its priority. Since the priority is not specified in this example, it will be adjusted by 10 (the process will run slower), from the default value (usually 0). The lower the number (of niceness to other users on the system), the higher the priority. The priority value may be in the range -20 to 19. Only root may specify negative values. Use top to display the priorities of the running processes.
renice -1 PID
(as root) Change the priority of a running process to -1. Normal users can only adjust processes they own, and only up from the current value (make them run slower).
__________________________________________________ __________________________________
Well thats it for now i hope you enjoyed this tutorial and thanks to
webhostingtalk.com & Quick Linux Server w/ Apache+PHP+MySQL+MailServer+PhpMyAdmin+Webmin+FTP Server+Webalizer+Firewall they wrote this tutorial i re- edited some of the text and commands and some more information put into it
-
29-05-2009, 23:30 #4
Thank you very much for posting this wonderful server security related tutorial here..
Rock _a.k.a._ Jack
Windows Hosting || Windows Reseller Hosting
Cloud Hosting || Powerful Dedicated Servers
Follow eUKhost on Twitter || Join eUKhost Community on Facebook
For complaints, grievances or suggestions kindly email our FeedBack Dept.
Proper action will be taken accordingly & instantaneously!
-
30-05-2009, 03:10 #5
No problem glad to help you guys some of this stuff i got from other sites and some i added in my self
-
13-07-2009, 09:47 #6
Thank you very much for posting great stuff on forum.
MAX
-
24-07-2009, 06:52 #7
Junior Member
- Join Date
- Jul 2009
- Posts
- 11
Thanks for sharing a nice tutorial in such an effective and detailed manner about server security setup.
-
24-07-2009, 11:02 #8
Hello,
Thank you for posting such valuable stuff on forum..
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)


LinkBack URL
About LinkBacks




Reply With Quote


Thought I would post in here as I've had a ticket on the system for about 10hours now which earlier...
How long for a ticket response?