Thursday 24 October 2013

How to Fix an (errno: 24) in MySQL


When creating a large number of partitions or tables, MySQL may mysteriously stop working and you find this type of error on /var/lib/mysql/hostname.err:

[ERROR] /usr/sbin/mysqld: Can't open file: './database/table.frm' (errno: 24)

errno: 24 simply means that too many files are open for the given process.
There is a read-only mysql variable called open_files_limit that will show how many open files are allowed by the mysqld:

SHOW VARIABLES LIKE 'open%';

 A lot systems set this to something very low, like 1024. Unfortunately, the following will NOT work: SET open_files_limit=100000

[mysqld]
open_files_limit = 100000

Then, be sure to restart mysql:

 /etc/init.d/mysql restart

Now, SHOW VARIABLES LIKE 'open%' should show 100000. The number you use may be different.

ERROR 2006 (HY000) at line 149351: MySQL server has gone away


I get this error while I was trying to import a Mysql dump file.

In order to solve this issue :

Locate and edit the my.cnf file your server is currently using.

In the [mysqld] section alter the max_allowed_packet settings to something like 

[mysqld] 
max_allowed_packet=32M 

After Altering the configuration file, restart the mysql server.
 

 

 


Finding the Inode usage of a Cpanel account 


Go to /home/username and execute the following command :

---------------------------------------------------------------------------------------------------------------------------
echo "Inode usage for: $(pwd)" ; for d in `find -maxdepth 1 -type d |cut -d\/ -f2 |grep -xv . |sort`; do c=$(find $d |wc -l) ; printf "$c\t\t- $d\n" ; done ; printf "Total: \t\t$(find $(pwd) | wc -l)\n"
-------------------------------------------------------------------------------------------------------------------------------

Sample output
=================

root@server [~]# cd ~chereenm/

root@server [/home/chereenm]# echo "Inode usage for: $(pwd)" ; for d in `find -maxdepth 1 -type d |cut -d\/ -f2 |grep -xv . |sort`; do c=$(find $d |wc -l) ; printf "$c\t\t- $d\n" ; done ; printf "Total: \t\t$(find $(pwd) | wc -l)\n"

Inode usage for: /home/chereenm
12 - .cagefs
 1 - .cagefs.cron
1 - .cagefs.screen
 2 - .cagefs.tmp
2 - .cl.selector
2 - .cpaddons
 40 - .cpanel
17 - etc
1 - .htpasswds
401 - mail
3 - .mozilla
2 - public_ftp
182 - public_html
3 - .spamassassin
190 - tmp
Total: 871

root@server [/home/chereenm]#
-------------------------------------------------------------------

Script to Change the Passwords of all Cpanel Accounts


Copy and paste the following into the file.
 
==========
#! /bin/bash
ls -1 /var/cpanel/users | while read user; do
pass=`</dev/urandom tr -dc “A-Za-z0-9*-/+.*=_\|\\#” | head -c16
echo “$user $pass” >> new-pass.txt
/scripts/realchpass $user  $pass
/scripts/ftpupdate
done
==========
 
Give execute permission to the file.
chmod +x changepass.sh
Execute
sh changepass.sh



Changing the timestamp on email clients


SquirrelMail
===========

Go inside the webmail program and click Options at the top.

Click the first link called Personal Information.

Under Timezone Options, look for "Your current timezone:" Change the drop down   to your time zone.

Click the Submit button.


Horde
======

 Go inside the webmail program and click Options at the top.

Click the second link called Locale and Time. Look for "Your current time zone:"

Change the drop down to your time zone.

Click the Save Options button.


RoundCube
==========

Go inside the webmail program and click Personal Settings at the top right.

Under User Interface, look for "Time zone"

Change the drop down to your time zone.

Click the Save button.


Outlook 2007
===========

At any time, you can change the time zone in Outlook so that it matches your current geographic location. Please consult the Outlook Help menu for assistance with other versions

On the Tools menu, click Options. Click Calendar Options.

Click Time Zone.

Under Current time zone, type a name for the current time zone in the Label box. In the Time zone list, click the time zone that you want to use.

 If you want your computer clock to automatically adjust for daylight saving time (DST) changes, select the Adjust for daylight saving time check box. This option is available only in time zones that use daylight saving time (DST).

 Click OK and you are done.


Thunderbird
===========

A Mozilla application has no clock of its own. It uses your system clock. Your system clock is controlled by your operating system settings.


Difference between ports 465 and 587


 Port 465 is for smtps - SSL encryption is started automatically before any SMTP level communication. 

Port 587 is for msa - it is almost like standard SMTP port. SSL encryption may be started by STARTTLS command at SMTP level if server supports it. Standard SMTP port accepts email from other mail servers without authentication. MSA should accept email after authentication (SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port.

 

 




Tuesday 15 October 2013

SMTP Error (-1): Connection to server failed

When trying to send emails from Roundcube,Horde and SquirrelMail if you are receving the error as follows :

-------------------------------------------------------------------
SMTP Error (-1): Connection to server failed
--------------------------------------------------------------------

This error is typically seen due to a setting in the CSF firewall or another firewall. It might be caused by having the following set :

SMTP_BLOCK = 1
SMTP_ALLOWLOCAL = 0

You would need to change SMTP_ALLOWLOCAL to 1 to enable webmail to function.


Monday 22 July 2013

LFD


If you installed CSF, (Config Server Firewal), on the server, there is a daemon called Login Failure Daemon (lfd), bundled with CSF, which is a process that runs all the time and periodically (every X seconds) scans the latest log file entries for login attempts against your server that continually fail within a short period of time.

Normally called "Brute-force attacks" the daemon process responds quickly to such patterns and blocks the IP's.

To check why 'lfd' has failed look at the end of /var/log/lfd.log

You can see errors as follows :

---------------------------------------------------------------------------------------------------------
/var/log/lfd.log:Jul 15 09:28:33 server lfd[11662]: Error: cannot fork: Cannot allocate memory, at line 2402
/var/log/lfd.log:Jul 15 14:10:09 server lfd[9297]: open3: fork failed: Cannot allocate memory at /usr/sbin/lfd line 1981
/var/log/lfd.log:Jul 16 05:43:22 server lfd[18107]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 16 06:51:08 server lfd[1916]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 16 09:24:53 server lfd[7386]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 16 17:01:15 server lfd[17889]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 16 22:55:31 server lfd[5289]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 17 00:12:06 server lfd[8044]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 17 02:19:15 server lfd[17821]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 17 07:15:43 server lfd[21667]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 17 09:10:10 server lfd[7318]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 17 23:41:36 server lfd[24521]: Error: cannot fork: Cannot allocate memory, at line 6066
/var/log/lfd.log:Jul 18 00:00:11 server lfd[5859]: Error: cannot fork: Cannot allocate memory, at line 2018
/var/log/lfd.log:Jul 18 20:31:45 server lfd[11656]: open3: fork failed: Cannot allocate memory at /usr/sbin/lfd line 1981
/var/log/lfd.log:Jul 19 04:16:15 server lfd[31925]: Error: cannot fork: Cannot allocate memory, at line 6066
/var/log/lfd.log:Jul 19 06:00:07 server lfd[12118]: Error: cannot fork: Cannot allocate memory, at line 2018
/var/log/lfd.log:Jul 19 06:06:03 server lfd[20240]: Error: cannot fork: Cannot allocate memory, at line 5380
/var/log/lfd.log:Jul 19 16:50:16 server lfd[21681]: Error: cannot fork: Cannot allocate memory, at line 5380

-------------------------------------------------------------------------------------------

On further checking I have seen that the plugins installed on the server such as cmm, cmc, cmq, cse, csf, cxs, msinstall, msfe was not properly working which lead to these LFD email alerts to clients email address 

Runing the following command fixed the issue.

curl -s configserver.com/free/csupdate | perl 

CSF error : No response from subprocess (/usr/local/cpanel/whostmgr/docroot/cgi/addon_csf.cgi): subprocess exited with status 2


On checking the Cpanel error log at /usr/local/cpanel/logs/error_log, you can see the errors as :

--------------------------------------------------------------------------------
Can't locate Net/LibIDN.pm in @INC (@INC contains: /usr/local/cpanel /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi /usr/lib/perl5/site_perl/5.8.8 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi /usr/lib/perl5/vendor_perl/5.8.8 /usr/lib/perl5/vendor_perl /usr/lib/perl5/5.8.8/i386-linux-thread-multi /usr/lib/perl5/5.8.8 .) at /usr/local/cpanel/Cpanel/Encoder/Punycode.pm line 10.
Compilation failed in require at /usr/local/cpanel/Cpanel/DomainTools.pm line 13.
BEGIN failed--compilation aborted at /usr/local/cpanel/Cpanel/DomainTools.pm line 13.
Compilation failed in require at /usr/local/cpanel/Cpanel/CheckData.pm line 8.
BEGIN failed--compilation aborted at /usr/local/cpanel/Cpanel/CheckData.pm line 8.
Compilation failed in require at /usr/local/cpanel/Cpanel/cPanelFunctions.pm line 11.
BEGIN failed--compilation aborted at /usr/local/cpanel/Cpanel/cPanelFunctions.pm line 11.
Compilation failed in require at /usr/local/cpanel/whostmgr/docroot/cgi/addon_csf.cgi line 24.
BEGIN failed--compilation aborted at /usr/local/cpanel/whostmgr/docroot/cgi/addon_csf.cgi line 24.
----------------------------------------------------------------------------------------------

Inorder to fix this issue run the following command :

curl -s configserver.com/free/csupdate | perl

This script will update: cmm, cmc, cmq, cse, csf, cxs, msinstall, msfe
Only those scripts that are already installed will be updated. Those that are updated are done so regardless as to whether they are the same or an older version of those available.


Move all addon domains as a standalone accounts under a reseller


If there so many addon domains under a Cpanel account and we need to change all of these addon domains as a stand alone account under a reseller account, follow these steps:

Backup
------
1. Take a full backup of the user from Cpanel
2. Extract the backup.


Create as stand alone account
-----------------------------
3. Remove one addon domain
4. Create that domain from WHM --> Create new account


Restore web files
-----------------
5. Copy all web files of that addon domain from the backup to the new document root.
6. Change the ownership all files to newuser.newuser


Restore DB's
-----------
7. Make sure the name of DB for each domain.
8. In backup directory there is a mysql directory. All DB's are under that mysql directory.
9. Login to the new cpanel account of that new account.
10. Create a DB, DB user from Cpanel --> Mysql
11. Give all privileges to that mysql user to the corresponding DB from there.
12. Make sure to edit all mysql configuration files in the document root of that domain.
13. Restore the old DB to new DB.


Restore mails
-------------
14. In the backup, we can see a directory named mail. Copy the directory of the domain from that directory to new accounts mail directory /home/newuser/mail/
15. Change the ownership of that directory under /home/newuser/mail/ to newuser.newuser


Restore mail accounts with same password
----------------------------------------
16. In the backup we can see a directory etc. Copy the directory of the domain from that directory to new accounts /home/newuser/etc/
17. Change the ownership of that directory under /home/newuser/etc/ to newuser.mail

Thursday 11 July 2013

Cpanel plugin to list the number of domains which is not working or not resolving from the server


Installation
-----------

# cd /home
# rm -f latest-accountdnscheck
# wget http://www.ndchost.com/cpanel-whm/plugins/accountdnscheck/download.php
# sh latest-accountdnscheck


Now login to your WHM > plugins > Account DNS Check

Or you can do this by executing command :

/var/cpanel/accountdnscheck/scripts/cli_run.sh

Thursday 4 July 2013

White List Hostname in CSF


Please follow the steps to white list hostname in CSF for domains using dynamic IPs.


1) Open the file "csf.dyndns" present on your server and add the hostname of your domain.

2) Open the file "csf.conf" present on your server and set DYNDNS = "300" which would would check for IP updates every 5 minutes

3) Open the file "csf.conf" present on your server and set DYNDNS_IGNORE = "1" to always ignore DYNDNS IP addresses in lfd blocking

4) Restart the firewall

FTP Command to Download all Subdirectories and files in a Directory


Please use the command wget -r ftp://username:password@1.2.3.4/dir/* for downloading all the subdirectories and files under a directory.

Wordpress Permlink Showing Blank Page


If you encountered any blank page issue on the permlink on wordpress,please do the following,

Just open the configuration file wp-admin/includes/misc.php
And replace the code of got_mod_rewrite with below

----------------------------------------------------------------------------------
function got_mod_rewrite() {
 //$got_rewrite = apache_mod_loaded('mod_rewrite', true); //old line with false negative;
 $got_rewrite = true;//force the response to true as we know mod_rewite is installed;
 return apply_filters('got_rewrite', $got_rewrite);
}                                            
-------------------------------------------------------------------------------------


Reparing Corrupted Mysql Database


Solution :1

Login to server with root access

Stop mysql using following command

/etc/init.d/mysql stop

Run following command to check all the tables in the database

Run following command to check all the tables in teh database

/usr/bin/myisamchk /var/lib/mysql/databasename/*.MYI

Run following command to repair all the tables in the database

/usr/bin/myisamchk -r /var/lib/mysql/databasename/*.MYI

Then recheck again using following command

/usr/bin/myisamchk /var/lib/mysql/databasename/*.MYI

Restrart MySql service using following command

/etc/init.d/mysql restart

Solution : 2

If you want repair DB using myisamchk, you need to shutdown MySQL service before proceeding otherwise it will corrupt some other databases.

Alternatively, if you do not want to shut down MySQL, you can use mysqlcheck.

mysqlcheck [DBNAME]

To repair the database tables:

mysqlcheck -r [DBNAME]

also we can use the commands

mysqlcheck -u{username} -p{password}  –check –optimize –auto-repair –all-databases

Webmin and Virtualmin Installation in Centos


Webmin installation :
-------------------------

Create a respository :

vi /etc/yum.repos.d/webmin.repo
[Webmin]
name=Webmin Distribution Neutral
#baseurl=http://download.webmin.com/download/yum
mirrorlist=http://download.webmin.com/download/yum/mirrorlist
enabled=1

wq!

wget http://www.webmin.com/jcameron-key.asc
rpm --import jcameron-key.asc

yum install webmin


open port 10000 to access webmin :
iptables -I INPUT -p tcp --dport 10000 -j ACCEPT

To install virtualmin :
------------------------------

make a script below

vi virtualmininstall.sh

curl http://software.virtualmin.com/gpl/scripts/install.sh > install.sh ; chmod 755 ./install.sh ; ./install.sh ;

wq!

make the script executable :  chmod +x virtualmininstall.sh
execute the script :  sh virtualmininstall.sh

After the installation is complete login to server

https://serverip:10000
username :  root
password :

Starting Xen Vm from Backend


First shutdown the Vm via Solusvm, Then issue the command :

 xm create /home/xen/vm441/vm441.cfg

Where vm441 is the VM ID

Clamav Configuration


To install clamav

#yum install clamd

run #freshclam to update the virus definitions

create a file  /home/clamscan  and enter the below :

clamscan -ri --exclude-dir=^/sys\|^/proc\|^/dev / | mail -s "ClamAV Scan Results for `date +%D`" user@domain.com

Save the file and exit. (user@domain.com must be replaced by email address to which scan results are to be mailed)

#crontab -e

0 0 * * * /home/clamscan      

save the file and exit.   The above cron will run everyday at midnight.

Enabling SPF for all accounts in WHM


Command to install spf record on single cPanel account :  
----------------------------------------------------------
/usr/local/cpanel/bin/spf_installer <cPanelusername>


Install spf records for all cPanel accounts :
--------------------------------------------------

cd /var/cpanel/users

for i in `ls /var/cpanel/users` ;do /usr/local/cpanel/bin/spf_installer $i ;done

MYSQL OPTIMIZATION


I'm pasting some parameters which worked for me while optimizing mysql settings in /etc/my.conf file

vi /etc/my.cnf

[mysqld]
socket=/var/lib/mysql/mysql.sock
#skip-locking — disabled by default
#skip-innodb — only when all tables are MyISAM
skip-name-resolve # saves dns resolution time.
query_cache_limit=1M
query_cache_size=64M
query_cache_type=1
max_connections=500
interactive_timeout=75
wait_timeout=25
connect_timeout=10

thread_cache_size=128
key_buffer=256M
sort_buffer_size=2M
read_buffer_size=2M ## sort+read x connections + key = memory usage
join_buffer=2M
max_allowed_packet=16M
table_cache=1024
record_buffer=2M
thread_concurrency=8
myisam_sort_buffer_size=64M
#log-bin
server-id=1

[safe_mysqld]
err-log=/var/log/mysqld.log
pid-file=/var/lib/mysql/mysql.pid
open_files_limit=8192

[mysqldump]
quick
max_allowed_packet=16M

[mysql]
no-auto-rehash
#safe-updates

[isamchk]
key_buffer=64M
sort_buffer=64M
read_buffer=16M
write_buffer=16M

[myisamchk]
key_buffer=64M
sort_buffer=64M
read_buffer=16M
write_buffer=16M

/etc/init.d/mysql restart

CPanel Log File Locations


cPanel Installation Logs:

/var/log/cpanel-install-thread0.log


Apache :

/usr/local/apache/logs/access_log

/usr/local/apache/logs/error_log


Apache domlogs :

/usr/local/apache/domlogs/example.com


Apache SUEXEC Logs :

/usr/local/apache/logs/suexec_log


MySQL :

/var/lib/mysql/hostname.err


BIND (named) Log:

/var/log/messages


Exim :

/var/log/exim_mainlog

/var/log/exim_paniclog

/var/log/exim_rejectlog


Courier or Dovecot IMAP :

/var/log/maillog


Tomcat Logs :

/usr/local/jakarta/tomcat/logs/catalina.err

/usr/local/jakarta/tomcat/logs/catalina.out


cPanel Access Log :

/usr/local/cpanel/logs/access_log


cPanel Error Log :

/usr/local/cpanel/logs/error_log


cPanel License Log :

/usr/local/cpanel/logs/license_log


Stats Execution Logs :

/usr/local/cpanel/logs/stats_log


ChkServd (cPanel Monitoring Daemon) Logs:

/var/log/chkservd.log


cPHulkd :

/usr/local/cpanel/logs/cphulkd.log


cPanel Backup Logs:

/usr/local/cpanel/logs/cpbackup/*.log


Pure-FTP :

/var/log/messages

/var/log/xferlog (symlinked to /usr/local/apache/domlogs/ftpxferlog)


Cron Logs :

/var/log/cron


SSH Logs :

/var/log/secure


ModSecurity :

/usr/local/apache/logs/modsec_audit.log

/usr/local/apache/logs/modsec_debug_log





How to Stop Open Relay of Exim (Cpanel servers)


An open relay is a smtp server configured in such a way that is allows a third party to relay (send / receive email messages that are neither from nor for local users). Therefore, such servers are usually targets for spam senders.

You can test if a server is an open relay via this link :  http://www.mailradar.com/openrelay/

If the server supports open relay, you can stop it via the following script in Cpanel servers

/scripts/fixrelayd

service exim restart

How to Fix an (errno: 24) in MySQL


Upon checking the mysql logs in /var/lib/mysql/HOSTNAME.err, I got error as :

-----------------------------------------------------------------------------
[ERROR] /usr/sbin/mysqld: Can't open file: './database/table.frm' (errno: 24)
-----------------------------------------------------------------------------

errno: 24 simply means that too many files are open for the given process. There is a read-only mysql variable called open_files_limit that will show how many open files are allowed by the mysqld.

A lot systems set this to something very low, like 1024. When creating a large number of partitions or tables, MySQL may mysteriously stop working and will generate this eeror.

Add the following parameter in /etc/my.cnf file and restart mysql service.

[mysqld]
open_files_limit = 100000







Tuesday 2 July 2013

Rootkit Hunter Installation in Centos 5,6 using Yum


Update yum repository with epel package:

Centos 5.x

wget http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
sudo rpm -Uvh remi-release-5*.rpm epel-release-5*.rpm

Centos 6.x

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
sudo rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm

Run:
yum update

After update:
yum install rkhunter

Get more details about Rkhunt commands and all.
man rkhunter

Tuesday 25 June 2013

Creating Backup of a Xen vm


Let the vm ID be vm378.

dd if=/dev/Xen/vm378_img of=/dev/Xen/vm378_img.img 

Friday 21 June 2013

Checking and Reparing filesystem using with FSCK


fsck is a Unix utility for checking and repairing file system inconsistencies . File system can become inconsistent due to several reasons and the most common is abnormal shutdown due to hardware failure , power failure or switching off the system without proper shutdown. Due to these reasons the super-block in a file system is not updated and has mismatched information relating to system data blocks, free blocks and inodes .

fsck – Modes of operation :

Interactive :- fsck examines the file system and stops at each error it finds in the file system and gives the problem description and ask for user response whether to correct the problem or continue without making any change to the file system.

Non interactive :- fsck tries to repair all the problems it finds in a file system without stopping for user response useful in case of a large number of inconsistencies in a file system but has the disadvantage of removing some useful files which are detected to be corrupt .

If file system is found to have problem at the booting time non interactive fsck is run and all errors which are considered safe to correct are corrected. But if still file system has problems the system boots in single user mode asking for user to manually run the fsck to correct the problems in file system.

Running fsck :

         fsck should always be run in a single user mode which ensures proper repair of file system . If it is run in a busy system where the file system is changing constantly fsck may see the changes as inconsistencies and may corrupt the file system .

If the system can not be brought in a single user mode fsck should be run on the partitions ,other than root & user , after unmounting them . Root & user partitions can not be unmounted . If the system fails to come up due to root/user files system corruption the system can be booted with CD and root/user partitions can be repaired using fsck.

fsck phases

fsck checks the file system in a series of 5 pages and checks a specific functionality of file system in each phase.


** phase 1 – Check Blocks and Sizes
** phase 2 – Check Pathnames
** phase 3 – Check Connectivity
** phase 4 – Check Reference Counts
** phase 5 – Check Cylinder Groups

Procedure
=======
1) Take system down to runlevel one (make sure you run all command as root user):

# init 1

2)Unmount file system, for example if it is /home (/dev/sda3) file system then type command:

umount /home

3) Now run fsck on the partition:

# fsck -fyC /dev/sda3

y- Display completion/progress bars for those filesystem checkers (currently only for ext2 and ext3) which support them
C - to fix any detected filesystem corruption automatically

4) Once fsck finished, remount the file system:

# mount /home

5) Go to multiuser mode

# init 3

Resize Xen Lvm


Example : Inorder to extend 40 GB in the vm442

lvresize /dev/xen/vm442_img -L +40G
resize2fs /dev/xen/vm442_img

resize2fs will ask to run e2fsck first so run e2fsck first

e2fsck -f /dev/xen/vm442_img

Screen Commands


To install screen : #yum install screen

After installation if you see "/var/run/screen must have permissions 777" then change the permission to 777  :  #chmod 777 /var/run/screen

#screen -ls --  this will list screenname and state (attached or detached)

After typing screen -ls it will show whether screen is "detached" or "attached" state

To reattach "detached" screen --  #screen -r <screenname>

Leaving screen --  press down ctrl + A together and type D   (ctrl A + D)

When u type screen -ls if the screen is attached, then do the below

#screen -D <screenname>     then
#screen -r <screenname>

To enter a name for the screen :   #Screen -S test

Detecting common Zone file errors of Domains



The domain won't resove if the zone file of the domain have any syntax errors or configuration errors.

So better way to understand the syntax or normal errors in the zone file is by running the command

named-checkzone domain.com domain.com.db on the server
where domain.com is the domain name and domain.com.db is the zone file.

 named-checkzone weibo520.com weibo520.com.db
zone weibo520.com/IN: loaded serial 2013011601
OK

If the zone file is correct then it will show the result as ok as above. If it has errors it will list the errors as well, so that it will be easier for us to investigate.

Login Problem in horide,squirrel mail and round cube in Cpanel


If you are facing login issue with horde,squirrel mail and roundcube after login to the webmail for an account.

At first run the following commands.
/usr/local/cpanel/bin/updatehorde --force
/usr/local/cpanel/bin/updatesquirrelmail --force
/usr/local/cpanel/bin/updateroundcube --force

 Normally it will fix those issues. but still there is login problems, then it might be with some configuration issues on the Cpanel acount.

Please run the following command in root SSH:
/scripts/whoowns domain.com
Where domain.com is the domain name in question. If it doesn't show any ownership, then move the following files:

cd /etc
mv userdomains userdomains.bak
mv trueuserdomains trueuserdomains.bak

At that point, run the following script and recheck ownership for the domain:

/scripts/updateuserdomains
/scripts/whoowns domain.com

If instead of showing no ownership, the domain showed the wrong ownership, you'd have to edit the /var/cpanel/users/username file that is improperly owning the domain to remove the DNS line that it has for that domain, then run the above move and updateuserdomains commands.



If the ownership is correct, then at that point, try instead checking the Roundcube logs as it has the most accurate logging of the 3 webmail programs. Try to log into the account in Roundcube, and then go to /var/cpanel/roundcube and tail the log:

After this issue will be fixed.






Thursday 20 June 2013

Error while uploading files to Cpanel accounts


If you are getting the following error while uploading files to the Cpanel accounts :

------------------------------------------------------
unknown bytes complete FAILED! :Upload
canceled: VIRUS DETECTED! ( Access denied. ERROR )
------------------------------------------------------

Go to WHM >> Manage Plugins.

There you can see the different add-ons. Check for clamavconnector.
If it is not installed, install it. If it is there, uninstall and install again.

Friday 14 June 2013

Warning while restarting the CSF service


--------------------------------------------------------------------------------------------------------
*WARNING* Since the Virtuozzo VPS iptables ip_conntrack_ftp kernel module is currently broken you have to open a PASV port hole in iptables for incoming FTP connections to work correctly. See the csf readme.txt under 'A note about FTP Conne ction Issues' on how to do this if you have not already done so.
---------------------------------------------------------------------------------------------------------

It is important when using an SPI firewall to ensure FTP client applications
are configured to use Passive (PASV) mode connections to the server.

On servers running Monolithic kernels (e.g. VPS Virtuozzo/OpenVZ and custom
built kernels) ip_conntrack and ip_conntrack_ftp iptables kernel modules may
not be available or fully functional. If this happens, FTP passive mode (PASV)
won't work. In such circumstances you will have to open a hole in your firewall
and configure the FTP server to use that same hole.

For example, with pure-ftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/pure-ftpd.conf and then restart pure-ftpd:
PassivePortRange        30000 35000

For example, with proftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/proftpd.conf and then restart proftpd:
PassivePorts    30000 35000

FTP over SSL/TLS will usually fail when using an SPI firewall. This is because
of the way the FTP protocol established a connection between client and server.
iptables fails to establish a related connection when using FTP over SSL
because the FTP control connection is encrypted and so cannot track the
relationship between the connection and the allocation of an ephemeral port.

Named dead but Pid file exists


root@server# /etc/init.d/named status
WARNING: key file (/etc/rndc.key) exists, but using default configuration file (/etc/rndc.conf)
rndc: connect failed: 127.0.0.1#953: connection refused
named dead but pid file exists

If you are receiving the above mentioned error while restarting named, Please execute the following script in Cpanel servers :

/scripts/fixrndc and restart the nameserver (service named restart)

Temporarily rejected RCPT lowest numbered MX points to local host


When MTA (Mail Transport Agent) such as Sendmail and Exim attemps to relay and transmits email through the mail server while receiving mail from external address to local account, the mail will not get delivered and been rejected with the one or all of following errors in the maillog log file.

----------------------------------------------------------------------------------------------------------
2007-08-05 08:08:88 H=(example.com) [196.172.0.188] sender verify defer for : lowest numbered MX record points to local host
2007-08-05 08:08:88 H=(example.com) [196.172.0.188] F= temporarily rejected RCPT user@example.com: Could not complete sender verify
2007-08-05 08:08:88 H=mail.example.com [196.172.0.188] F= rejected RCPT : relay not permitted

The reason for the error message is the domain “example.com” is missing from the /etc/localdomains file of your server.
The difference between the /etc/localdomains and /etc/remotedomains files is that, they decide whether the email has to be delivered locally OR to a remote server respectively and is checked by the exim mail server.
------------------------------------------------------------------------------------------------------------
To fix the issue, edit the file:

# vim /etc/localdomains

and place the domain name entry there. There is no need to restart the ‘exim’

Thursday 18 April 2013

Export and import MySQL databases using phpMyAdmin


You can use phpMyAdmin to import and export your database, as long as it is relatively small (10MB or less). If your database is larger than 10MB, Please skip to Method 2 - command line.

First, log into phpMyAdmin :
Once you're logged into phpMyAdmin, follow the steps outlined below :

Export

In phpMyAdmin, select your database from the list on the left :



 Click on Export from the top set of tabs.


Click the radio button for "Custom" to view all available options. Select the tables from the list that you would like to back up. If you want to back up the entire database, click Select All.  




By default, your database name will be used to name the exported database file. You can change this by entering your desired file name in the File name template box. You can also select a compression option (such as "gzipped") if you want to compress the backup before downloading it from the server. 

  
Make sure radio button for "structure and data" is selected from the "Dump Table" option list. This should be the default setting.

In the Structure section, check the box for "Add DROP TABLE / DROP VIEW / PROCEDURE / FUNCTION / EVENT statement" if you want this export to be able to replace existing tables of the same name. If you want to merge this backup with another database, do not select this.

 
Click the Go button to save the file to your local computer. 

Import

Make sure the database you need has already been created. If it has not, please first create the database

CAUTION:
If you import a backup file to a database that already has content, it will replace the existing content.

In phpMyAdmin, select your database from the list on the left.


Click on "Import" from the top set of tabs. 


Click on the "Choose File" button.

Browse to your local SQL file and click "Open." If it is a zipped file, be sure to unzip the file first.
Click the "Go" button towards the bottom of the page. Wait while your database imports. Depending on the size, this can take a few minutes.


You should get a message like this:

"Import has been successfully finished, X queries executed."


Wednesday 17 April 2013

Recursive Php.ini in Ngnix servers


The PHP settings defined in your php.ini file are not recursive. What this means is that they do not modify settings in any child folders (which are subdirectories of the current directory).

Still confused, here's an example.

Let's say you have a php.ini file in your public_html folder. That php.ini file has the PHP memory_limit set to 256M. Only scripts that run directly in your public_html folder will have the memory_limit set to 256M. If you have a folder named public_html/employees, that "employees" folder will not be affected by the public_html/php.ini file, it would only be affected by a php.ini file located in its own folder, public_html/employees

If you have many folders, creating a php.ini file for each folder would be quite tedious. What you can do is update your .htaccess to tell the server that the public_html/php.ini file should apply not only to public_html, but to any folders within that folder (such as public_html/employees or public_html/about-us).

Updating your suPHP_ConfigPath value in your .htaccess file :

Making your php.ini file affect all child folders as well is referred to as making the file "recursive". To make your public_html/php.ini file recursive, edit (or create the file if it doesn't exist) your public_html/.htaccess file and add the following code :

suPHP_ConfigPath /home/username/public_html

This line you entered is specifying the directory where the php.ini is located that you want to make recursive. Be sure to replace username with your cPanel username.

This change is immediate, so you should see the update right away.

After saving the changes, be sure to create a phpinfo page in one of your subdirectories and test the results. When looking at your phpinfo page, the "Loaded Configuration File" should reflect the php.ini file that you wanted to make recursive.

Installing OpenJDK in Ubuntu


Run the Command :

apt-get install openjdk-7-jdk

Inorder to verify the installation of java in Linux :

$ which java

   or

$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.3) (7u9-2.3.3-0ubuntu1~12.10.1)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
mkyong@yong-ubuntu:/usr/lib/jvm/java-7-openjdk-amd64/bin$





Wednesday 3 April 2013

vzquota : (warning) Incorrect quota shutdown for id VEID, recalculating disk usage



If you are getting following messages while starting your VE then quota for particular VPS was not shutdown properly.

==============================================
vzquota : (warning) Incorrect quota shutdown for id VEID, recalculating disk usage
vzquota : (error) quota check : lstat `ssl_scache.dir': Input/output error
==============================================

vzquota off <VEID>
vzctl start <VEID> 

And then again start quota for that VPS :

vzquota on <VEID> 

Please make sure to replace <VEID> with actual VPS ID you are facing problem with.

Your problem will be fixed

Cpanel FIX: Error from domain wrapper: domain.com is owned by another user


I got this error when I was trying to add subdomains to one of my cPanel accounts. This happens when cPanel doesn’t remove the subdomain correctly and then it thinks it’s still there so when you try to add it back on you get an error. Here’s how to fix it :

1. Remove domain.com from /var/cpanel/users/cpanel-username

2. Run /scripts/updateuserdomains as root user on the server because you changed the above file   manually, this will create adjusted cache files

3. Remove /var/named/domain.com.db if the file exists (it doesn’t always)

4. Remove the virtualhost for domain.com on /usr/local/apache/conf/httpd.conf

5. Remove domain.com from /etc/named.conf

Now you can add the domain back on in cPanel with no problems.

Monday 25 March 2013

Railgun Cloudfare plugin Installation


Railgun is a single daemon that runs on a 64-bit system which uses alternative compression techniques to dramatically speed up WAN performance. It proxies traffic through a special protocol that would normally travel between CloudFlare and your origin server over HTTP. Typically, the markup of websites does not change that frequently from one request to the next. Instead of transferring the entire request between CloudFlare and your environment, Railgun will transfer only the changes in markup from one request to the next. This cuts down on bandwidth, transfer time, and overall page load times. Railgun caches these differences in memory to make page processing as fast as possible.

----------------------------------------------------------------
Railgun is available only for 64-bit systems.
---------------------------------------------------------------

Downloads
========
Ubuntu (Quantal 12.10) : https://www.cloudflare.com/static/misc/railgun/ubuntu/railgun-quantal.latest.deb
Centos/RHCEL (6): https://www.cloudflare.com/static/misc/railgun/centos/railgun-el6.latest.rpm
Centos/RHCEL (5) : https://www.cloudflare.com/static/misc/railgun/centos/railgun-el5.latest.rpm
Debian  :  https://www.cloudflare.com/static/misc/railgun/debian/railgun-squeeze.latest.deb
FreeBSD (9) : https://www.cloudflare.com/static/misc/railgun/freebsd/railgun-freebsd9.latest.tar.gz
FreeBSD(8) : https://www.cloudflare.com/static/misc/railgun/freebsd/railgun-freebsd8.latest.tar.gz


RPM-based :
execute with root privileges :

rpm -Uvh railgun-stable.X.X.x86_64.rpm

DEB-based
execute with root privileges :

dpkg -i railgun-stable.X.X.amd64.deb

FreeBSD
execute with root privileges :

tar -xzvpf railgun-stable.X.X.tar.gz
cd railgun-stable.X.X && gmake install

For getting activation token for Railgun :

curl -s https://www.cloudflare.com/api/v2/railgun/init -d "host_key=[host key]" | python -mjson.tool

Run this command for getting public IP for Railgun :

curl icanhazip.com

Next you need to install Memcache  :

yum install memcached.x86_64 php-pecl-memcache.x86_64

Configuration file :

vi /etc/sysconfig/memcached

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="

For busy servers you need to increase the values as follows:

MAXCONN : Use 1024 max simultaneous connections; the default is 1024. For busy server             increase this number as per requirements.
 
CACHESIZE : Use 64 MB memory max to use for object storage; the default is 64 megabytes. For busy server you can set it to 512MB or 1GB (1024).

OPTIONS :  You can set server IP address (listen on address) here so that apache/php/nginx based serer can connect to the server. By default it is set to INADDR_ANY. This is an important option to consider as there is no other way to secure the installation. Binding to an internal or firewalled network interface is suggested.
                
Here is my sample update file:


PORT="11211"
USER="memcached"
MAXCONN="4096"
CACHESIZE="512"
OPTIONS="-l 192.168.1.15"

Inorder to Start / Stop / Restart Memcached Server :

# /etc/init.d/memcached start
# /etc/init.d/memcached stop
# /etc/init.d/memcached restart
# /etc/init.d/memcached status

Inorder to verify that Memcached is Running and Working :

pgrep memcached
netstat -tulpn |grep :11211

sample outputs :

tcp        0      0 192.168.1.15:11211           0.0.0.0:*                   LISTEN      24964/memcached
udp        0      0 192.168.1.15:11211           0.0.0.0:*                               24964/memcached

You need add port 2048 in csf and restart it.

Monday 18 March 2013

Installing Google Apps Wizard Cpanel Plugin



Version Status

2.0.1 Stable Release


System Requirements

* cPanel/WHM server
* Security Tokens = on "WHM >> Main >> Server Configuration >> Tweak Settings >> Security

Installation

Run the following shell commands as root via SSH:

# wget http://google-apps-wizard-cpanel-plugin.googlecode.com/files/gaw-2.0.tar
# tar -xf gaw-2.0.tar
# cd gaw-2.0
# ./gawinstall.sh
# cd ..
# rm -Rfv gaw-2.0/ gaw-2.0.tar
Go to WHM >> Main >> Plugins >> Google Apps Wizard and click Update Now.

Upgrade

If you running version 2+ please skip this part.

# wget http://google-apps-wizard-cpanel-plugin.googlecode.com/files/gaw-2.0.tar
# tar -xf gaw-2.0.tar
# cd gaw-2.0
# ./gawupdate.sh
# cd ..
# rm -Rfv gaw-2.0/ gaw-2.0.tar

Templates support

The Google Apps Wizard plugin support third party cPanel templates.
All you need to do is to copy the default template to your third party template folder.
Template path: /usr/local/cpanel/base/frontend/x3/gaw
Example command: # cp /usr/local/cpanel/base/frontend/x3/gaw /usr/local/cpanel/base/frontend/{Your custom template folder name}/

Multi languages support

The language files folder is located at: /usr/local/cpanel/base/3rdparty/GoogleAppsWizard/lang/
The en.php is the default fallback language file so do not delete it!
To create new language files you must use an existing cPanel prefix.
You can see your available languages by navigating to: Main >> Locales >> View Available Locales.

Uninstall

# wget http://google-apps-wizard-cpanel-plugin.googlecode.com/files/gaw-2.0.tar
# tar -xf gaw-2.0.tar
# cd gaw-2.0
# ./gawuninstall.sh
# cd ..
# rm -Rfv gaw-2.0/ gaw-2.0.tar

Installing ImageMagic on Centos 6


Install ImageMagick and ImageMagick-devel using yum because we need all the dependency installed:

yum install ImageMagick
yum install ImageMagick-devel

Then continue to install Imagick php module (Edit: If you are running php 5.4.x, then you need to install imagick 3.1.0RC2, 3.0.1 will give errors, find it here:

cd /root
wget http://pecl.php.net/get/imagick-3.0.1.tgz
tar zxf imagick-3.0.1.tgz
cd imagick-3.0.1
phpize
./configure
make
make install

Find the loaded php.ini configuration using command :

php --ini

Now we have to add the extension to the php.ini file.

extension=imagick.so

Then restart Apache :

/etc/init.d/httpd restart


Cpanel log to check when hosting created and deleted


In the recent days, we all are facing the hacking issue at that time, we always see problem like account termination from the server.
At that time, we can use the following log file to investigate the issue as its providing when hosting account was created, owner changed or account deleted from the server.
For example we are checking logs for the domain test123.com and as per the following logs the hosting account for domain test123.com is created by using the root owner on dated Wed Jan 11 08:19:40 2012 and onwership is under root.

root@linux7802 [~]# cat /var/cpanel/accounting.log | grep test123.com
Wed Jan 11 08:19:40 2012:CREATE:root:root:test123.com:115.124.103.126:admin111

Now we have changed the ownership for the domain test123.com hosting account to linux780 reseller ownership therefore check the following logs

root@linux7802 [~]# cat /var/cpanel/accounting.log | grep test123.com

Wed Jan 11 08:22:51 2012:CHANGEOWNER:root:root:test123.com:admin111:root:linux780

Now we have terminated the hosting account for the domain test123.com by using the root user and its also recorded in the accounting.log

root@linux7802 [~]# cat /var/cpanel/accounting.log | grep test123.com
Wed Jan 11 08:25:14 2012:REMOVE:root:root:test123.com:admin111

So we can similarly check the logs for all the domains when they have created/modified or removed from the server and its always to better to maintain the accounting.log for future reference.

Removing Particular IP address from Cphulk bruteforce database


When your IP got blocked in cphulk database you can not remove it from WHM as cPanel has not offer this feature yet. You will have to flush cphulk database for this but this will remove other IPs too that is not recommended as far as security is concerned.

In order to remove particular IP from cphulk bruteforce database you will have to access database and has to remove that IP.

You can do this by two methods

1)Access database through shell
2)Access database through phpmyadmin

I will explain you first method as second one is relatively easy.

Access server with root user. Type in mysql as you will login to mysql shell. Now to connect database cphulkd type in

mysql> use cphulkd;

You will now connect to database cphulkd. Now type in sql query
just to confirm if your IP is really blocked there.

mysql> SELECT * FROM `brutes` WHERE IP=’x.x.x.x’;

If you are able to see your IP in brutes then simply remove it by

mysql> DELETE FROM `brutes` WHERE IP=’x.x.x.x’;

Once it done quit the mysql by typing

mysql> quit

In this way your IP will be removed from brute force and you will enjoy cPanel browsing.


Monday 11 February 2013

Creating Email accounts in webmin



First you have to look if Postfix and Dovecot are propely configured.

Step 1 >> Add a Webmin user. By going to System > Users and Groups.
               Then click create a new user at the bottom of the listing of users.


Click Save and move on to the next step.

Step 2 >>

Now that you have the user and new password created, you are ready to setup the new user mailbox on the server. You now want to go over to Servers > Postfix Mail Server.  Now in order to use your new user as an outgoing email you must next click on the icon labeled “Virtual Domains” then. Next simply go to “Add New Mapping”


  But, when you click save mappings, if your are receiving such an error :

 ========================================
 Error while saving a mapping : No map file defined
========================================

 Then you need to create the map file or define one in your config

Check to see if virtual_mailbox_maps or virtual_alias_maps exists in the main.cf file. if it's not there, then   create the file if it is there then check to make sure it's been created on your file system.

You need to edit your main.cf and add:

virtual_alias_domains = DomainOne.com DomainTwo.com
virtual_alias_maps = hash:/etc/postfix/virtual

You then need to run 'postmap' and you may need to restart postfix

You need to create a file called virtual, if it does not exists.
And you have to add the email address and respected User to the file for eg : -
=======================================
postmaster@example.com     postmaster
info@example.com           joe
sales@example.com          jane
===========================================


The virtual_alias_domains setting tells Postfix that example.com is a called virtual alias domain.
If you omit this setting then Postfix will reject mail or will not be able to deliver it.

NEVER list a virtual alias domain name as a mydestination domain

The /etc/postfix/virtual file contains the virtual aliases.
With the example abovemail for postmaster@example.com goes to the local postmaster.
While mail for info@example.com goes to the UNIX account joe 
and mail for sales@example.com goes to the UNIX account jane.
You then need to run 'postmap' and you may need to restart postfix.
Now you have created the required settings.
In order to create the mailboxfor the user,You have to go to System > Users and Groups >> module config at the bottom


Then tick the box having the option  >>  automatically create the mailbox when a user is created in the system.

Then take the option 'Read user mail' and check whether the mailbox have been created




Defualt Address (Catch-all Email Address)



The default or catch-all address is the one to which all e-mails, addressed to a non-available or mistakenly entered email account at your domain name are routed to.

In case someone sends an email to info@yourdomain.com and you do not have such mailbox, the catch-all option will forward this email to your default email address.

Step 1 : To access the auto responders menu, click on the Default Address icon on the main screen of your cPanel interface.

Step 2 : From the drop-down menu select the (sub)domain for which you would like to set up a default address.

Step 3 : Now you have several options

>> You can forward all unrouted mail to an email address; in this case, you should type in the address in the field.
>> You can discard all unrouted mail with an error to the senders; in this case you should type in the message which will be sent to the senders.
>> From the Advanced Options you can discard all unrouted mail, pipe it to a program or forward it to the system account.

Step 4 : Click Change to apply your settings.



Thursday 7 February 2013

Configuring Spamassassin to show Spam Score in Spam taged messages


To enable and disable Spam Assassin please do the following:

1. Login to cPanel and look in the Mail section
2. Click Spam Assassin™
3. Click Enable SpamAssassin to enable
4. Click Disable SpamAssassin to disable
5. You have now just enabled / disabled Spam Assassin.

Required Score:
0 means everything will be marked as Spam
5 is the default
10 means nothing will be marked as Spam

Just setup Spam Assassin once, and it works for all of the emails on your account.
Spam Assassin will mark your spam so it is easy to notice.
You may not be able to save the Required Score in the drop-down feature.
Instead, you must click the "Configure SpamAssassin" button at the very bottom, change the value for required_score, and then click the "Save" button at the bottom.

Email Filtering with Spam Assassin
=========================
NOTE: You can use Spam Box or Email Filtering to move the spam from your Inbox to another folder.

 1. In your webmail, create a folder called Spam.
 2. In cPanel, go to User Level Filtering.
 3. Next to your email address, click Manage Filters.
 4. Click the Create a new Filter button.
 5. Give the filter a name like SpamAssassin Rule.
 6. Change the "From" drop down to "Spam Status".
 7. Change the "equals" drop down to "begins with".
 8. In the large blank below, type Yes
 9. Change the "Discard Message" drop down to "Deliver to folder".
10. Click the Change button and choose your new Spam folder.
11. Click the Activate button.

Now you can use IMAP and subscribe to the new Spam folder.

Showing the spam score in the subject line of spam taged messages
==============================================
 Go to :
 Exim configuration manager >> filters >> SpamAssassin™: X-Spam-Subject/Subject header prefix for spam emails [?]
 Change the default value to ***SPAM*** Score:$spam_score
 You could also use $spam_score_int if you do not want to see the decimal value.



Spamd and Mailman services Constantly failing !!!




SpamAssassin service (spamd) service is failing due to some reason. When cpanel monitoring service finds spamd down, it restarts spamd and then send you alert email.But spamd is failing too often and so you get a lot of alerts.

You can start the service using the command /scripts/restartsrv_spamd from SSH.
Another possibility is that spamd is broken. Update cpanel software with /scripts/upcp --force from root SSH.

If the issue is still persisting, the main reason seems to be,If it is in a VPS when some resources (mainly memory and buffers) exhaust.
It would be better to check if the VPS is running out of resources.
If it is an OpenVZ vps you can check the file /proc/user_beancounters yourself.
Check if there is any non-zero failcount values. Failcount represents the number of times corresponding resource ran out.

You can cat the logs from the main hardware node :

(Hardwarenode)#cat /var/log/messages |grep 403 (Vps ID) |grep OOM |wc -l

It gives the number of times the vps 403 had ran out of resources(Memory)

You can also cat the logs inorder to further check the issue by :

(Hardwarenode)#cat /var/log/messages |grep 403 (Vps ID)

You can see logs as follows :
========================================================================
Feb 3 13:41:54 linux7 kernel: [939759.629367] OOM killed process spamd (pid=671490, ve=403) exited, free=36243.
Feb 3 13:41:54 linux7 kernel: [939759.815495] OOM killed process spamd (pid=39470, ve=403) exited, free=32484.
Feb 3 13:41:54 linux7 kernel: [939759.851935] OOM killed process spamd (pid=671448, ve=403) exited, free=43210.
Feb 3 13:41:55 linux7 kernel: [939760.480391] OOM killed process mysqld (pid=428345, ve=403) exited, free=42749.
Feb 3 13:41:56 linux7 kernel: [939761.626820] OOM killed process named (pid=201837, ve=403) exited, free=40153.
Feb 3 13:41:57 linux7 kernel: [939762.734085] OOM killed process php (pid=428175, ve=403) exited, free=39938.
Feb 3 13:41:58 linux7 kernel: [939763.665735] OOM killed process spamassassin (pid=428435, ve=408) exited, free=50507.
Feb 4 16:58:50 linux7 kernel: [1037823.607551] OOM killed process spamd (pid=548164, ve=408) exited, free=35391.
435456 [0] DCSZ: 4639363 / 134217728 [0] OOMG: 242382 / inf [189] Dirty 0 Wback 0 Dche 4087 Prnd 966749
Feb 6 22:45:39 linux7 kernel: [1231132.091743] OOM killed process spamd (pid=721601, ve=408) exited, free=84250.
Feb 6 22:45:39 linux7 kernel: [1231132.091768] RAM: 130782 / 131072 [1147] SWAP: 127216 / 131072 [1147] KMEM: 37081088 / 268435456 [0] DCSZ: 4639363 / 134217728 [0] OOMG: 242382 / inf [190] Dirty 0 Wback 0 Dche 4088 Prnd 966749
========================================================================

Sunday 13 January 2013

Rewrite Rules (URL Rewriting, mod_rewrite)



(1) Redirect site from http to https :

add the below in .htaccess file in public_html

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


(2) Redirecting a domain to another domain via .htaccess

Example :- redirect vivek.com to google.com

RewriteEngine on
RewriteCond %{HTTP_HOST} ^vivek\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.vivek\.com$
RewriteRule ^/?$ “http\:\/\/www\.google\.com\/” [R=301,L]

(3)  Redirect users to access the site with WWW

Example :- redirect vivek.com to www.vivek.com

add the below in .htaccess file

RewriteEngine on
RewriteCond %{HTTP_HOST} ^vivek\.com$ [NC]
RewriteRule ^(.*)$ http://www.vivek.com/$1 [L,R=301]


(4)  Redirect page to another page within public_html

Example1 :- to redirect home.html to index.php

RewriteEngine on
RewriteRule ^home.html$ index.php


Example2 :-   rewrite site  vivek.com/kb/index.php  to   vivek.com/blog/index.html

Go to kb directory and create a .htaccess file

#cd public_html/kb
#touch .htaccess
#vi .htaccess

RewriteEngine on
RewriteRule ^index.php$ /blog/index.html

Installing Rkhunter


Rkhunter (Rootkit Hunter) is a Unix-based tool that scans for rootkits, backdoors and possible local exploits


Installation :

cd /tmp
wget http://ncu.dl.sourceforge.net/project/rkhunter/rkhunter/1.4.0/rkhunter-1.4.0.tar.gz
tar -xvf rkhunter-1.4.0.tar.gz
cd rkhunter-1.4.0
./installer.sh --layout default --install

Updating rkhunter

Run the RKH updater to fill the database properties by running the following command :

/usr/local/bin/rkhunter --update
/usr/local/bin/rkhunter --propupd




To add cron:


Create a file called rkhunter.sh under /etc/cron.daily/, which then scans your file system every day and sends email notifications to your email id. Create following file with the help of your favourite editor.

vi /etc/cron.daily/rkhunter.sh


Add the following lines of code to it and replace “YourServerNameHere” with your “Server Name” and “your@email.com” with your “Email Id“.

#!/bin/sh
(
/usr/local/bin/rkhunter --versioncheck
/usr/local/bin/rkhunter --update
/usr/local/bin/rkhunter --cronjob --report-warnings-only
) | /bin/mail -s 'rkhunter Daily Run (PutYourServerNameHere)' your@email.com

Set execute permission on the file :

chmod 755 /etc/cron.daily/rkhunter.sh

To scan the entire file system, run the Rkhunter as a root user :

rkhunter --check

 
The above command generates log file under /var/log/rkhunter.log,
With the checks results made by Rkhunter.
 
For more information and options please run the following command.

rkhunter --help
 
 

Linux Kernel /etc/sysctl.conf Hardening


# Turn on execshield

kernel.exec-shield=1
kernel.randomize_va_space=1

# Enable IP spoofing protection
net.ipv4.conf.all.rp_filter=1

# Disable IP source routing
net.ipv4.conf.all.accept_source_route=0

# Ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.icmp_ignore_bogus_error_messages=1

# Make sure spoofed packets get logged
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# Disable ICMP routing redirects
sysctl -w net.ipv4.conf.all.accept_redirects=0
sysctl -w net.ipv6.conf.all.accept_redirects=0
sysctl -w net.ipv4.conf.all.send_redirects=0
sysctl -w net.ipv6.conf.all.send_redirects=0

# Disables the magic-sysrq key
kernel.sysrq = 0

# Turn off the tcp_sack
net.ipv4.tcp_sack = 0

# Turn off the tcp_timestamps
net.ipv4.tcp_timestamps = 0

# Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1

# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1

Securing Linux Cpanel server


WHM

WHM >> Security Center

1. Compiler Access >> make sure it is disabled for all users except "root".

2. Configure Security Policies >> Password Strength

3. cPHulk Brute Force Protection >> Enable it. White List known IPs if required (say if customer has static IP from ISP).

4. Traceroute Enable/Disable >> Disable it.

5. Shell Fork Bomb Protection >> Enable.

 OS and kernel

6. find / ( -perm -a+w ) ! -type l >> world_writable.txt : Look at world_writable.txt to see all world writable files and directories. This will reveal locations where an attacker can store files on your system. NOTE: Fixing permissions on some PHP/CGI scripts that are not properly coded will break them.

7. find / -nouser -o -nogroup >> no_owner.txt : Look at no_owner for all files that do not have a user or group associated with them. All files should be owned by a specific user or group to restrict access to them.

8. Make Sure No Non-Root Accounts Have UID Set To 0

    awk -F: '($3 == "0") {print}' /etc/passwd (you should only see one o/p) like:

    root:x:0:0:root:/root:/bin/bash

9. Tripwire – Monitors checksums of files and reports changes.
    http://tripwire.com or http://sourceforge.net/projects/tripwire
 
10. Chrookit – Scans for common rootkits, backdoors, etc.

    http://www.chkrootkit.org

11. Rkhunter – Scans for common rootkits, backdoors, etc.

    http://www.rootkit.nl/projects/rootkit_hunter.html

  Now create a cronjob so it will email you with notifications to the root mailbox:
  #crontab -e

    At the bottom add the following line
   16 0 * * * /usr/local/bin/rkhunter -c --nocolors --cronjob --report-mode --createlogfile --skip-keypress --quiet

   Press control x to save

12. Logwatch – Monitors and reports on daily system activity.

    http://logwatch.org

13. Change SSH port to non-standard port.

14. Change SSH Protocol 2,1 to Protocol 2

15. Enable Email Alert on root login

    cd /root ; vi  .bashrc

   Scroll to the end of the file then add the following:

   echo 'ALERT - Root Shell Access (YourserverName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" admin@domain.com

 Firewall and mis security

17. Install CSF firewall and make sure test mode is disabled after opening all used ports.

   IMP: Make sure SSH port set in #14 is opened in firewall.

   CSF Connection Limit
   There is in csf.conf CT option, configure it like this
   CT_LIMIT = “100″
   It means every IP with more than 100 connections is going to be blocked.
   CT_PERMANENT = “1″
   IP will blocked permanenty
   CT_BLOCK_TIME = “1800″
   IP will be blocked 1800 secs(1800 secs = 30 mins)
   CT_INTERVAL = “60″
   Set this to the the number of seconds between connection tracking scans.
   After csf.conf editing, restart csf

18. Tweak LFD and CSF to prevent DOS.

19. Secure /tmp, /dev/shm and /var/tmp

 PHP security

20. Disable vulnerable PHP functions. Find the disable_functions in php.ini file and

    disable_functions = system, show_source, symlink, exec, dl,
    shell_exec, passthru, phpinfo, escapeshellarg,escapeshellcmd

21. Enable suPHP if the server is for shared hosting.

22. WHM >> Configure PHP and suEXEC > set suPHP handler and suexec

Apache

22. Install mod_security and cmc to manage the mod sec rules via WHM. See http://configserver.com/cp/cmc.html

23. Install dos_evasive.

FTP

24. WHM >> Service Configuration >> FTP Server Configuration

   Make sure Anonymous logins and uploads are disabled.

MySQL

25. Disable networking if you don't need anyone to remotely connect to MySQL server.

     Add the below line to my.cnf

    skip-networking

Saturday 12 January 2013

Enabling Second-Level Quotas for Openvz containers

The parameter that controls the second-level disk quotas is QUOTAUGIDLIMIT in the Container configuration file. By default, the value of this parameter is zero and this corresponds to disabled per-user and per-group quotas.

If you assign a non-zero value to the QUOTAUGIDLIMIT parameter, this action brings about the two following results:

Second-level (per-user and per-group) disk quotas are enabled for the given Container;
The value that you assign to this parameter will be the limit for the number of file owners and groups of this Container, including Linux system users. Note that you will theoretically be able to create extra users of this Container, but if the number of file owners inside the Container has already reached the limit, these users will not be able to own files.
Enabling per-user and per-group quotas for a Container requires restarting the Container. The value for it should be carefully chosen; the bigger value you set, the bigger kernel memory overhead this Container creates. This value must be greater than or equal to the number of entries in the Container /etc/passwd and /etc/group files. Taking into account that a newly created Red Hat Linux-based Container has about 80 entries in total, the typical value would be 100. However, for Containers with a large number of users this value may be increased.

When managing the quotaugidlimit parameter, please keep in mind the following:

If you delete a registered user but some files with their ID continue residing inside your Container, the current number of ugids (user and group identities) inside the Container will not decrease.
If you copy an archive containing files with user and group IDs not registered inside your Container, the number of ugids inside the Container will increase by the number of these new IDs.
The session below turns on second-level quotas for Container 101:

# vzctl set 101 --quotaugidlimit 100 --save
Unable to apply new quota values: ugid quota not initialized
Saved parameters for Container 101

You have to stop the container and start it again to reflect the changes as the values cannot be updated to a running container.

# vzctl stop 101;
Stopping Container ...
Container was stopped
Container is unmounted
#vzctl start 101
Starting Container ...
Container is mounted
Adding IP address(es): 192.168.1.101
Hostname for Container set: ct101
Container start in progress...

Inorder to check if the parameter is correctly enabled in the container, Issue the command in the hardware node :

grep -i QUOTAUGIDLIMIT /etc/sysconfig/vz-scripts/CT_ID.conf

If you get the respected qoutaaugidlimt value it is enabled
If you get an empty result, or a result of zero, second-level quotas are not supported by this environment.


Migrating SSL certificate from old server to new one

1 .Login as root via SSH

You Will find the cert,CA bundle and the private key at /etc/ssl folder.

root@server[/etc/ssl]ls
./ ../ certs private/

Inside certs folder you will find domain.crt and domain.cabundle.

 Inside private folder you will see the domain key.

2 .Copy those to a notepad.

3 .Login to WHM of new server > make sure that the site is on dedicated Ip.

 If not, >> change site Ip address to dedicated Ip.

4 .Via WHM >> Install an SSL certificate and Setup the Domain >> enter the cert,key and bundle.

Make sure that the username, Ip and Domain name is in the respective fields.

5 .Submit and you are done.

6 .Make sure that https://domain.com works before updating the customer.