Archive for July, 2010

Mysql database connection from php in different conditions

In this topic we will discuss about different types of mysql database connection in php.

The general configuration we do to connect a mysql database from PHP is


$dbhost = ‘localhost’;
$dbuser = ‘root’;
$dbpass = ‘password’;

$conn = mysql_connect(‘$dbhost’,’ $dbuser’, ‘$dbpass’) or die (‘Error connecting to mysql’);


So in my discussions below I will be changing the connection statement only in order to connect successfully.Rest will be the same as you know.

Conditions-1:mysql doesnot have password.

Lets say your mysql server does no have any password.So your coinnection statement will be

$conn = mysql_connect(‘$dbhost’,’ $dbuser’, ”) or die (‘Error connecting to mysql’);

Condition-2:-Mysql port changed

Mysql runs on a default port 3306.But for security reasons people change the mysql port.In our case let’s say I have changed the mysql port to 3309.Then my connect statement will be

$conn = mysql_connect(‘$dbhost:3309′,’ $dbuser’, ‘$dbpass’) or die (‘Error connecting to mysql’);

Condition-3:port same but mysql socket file changed.

If in some servers you need to change the default socket file location i.e /var/lib/mysql/mysql.sock

to some other location like /var/lib/mysql-databases/mysqld2/mysql.sock then how would be our connection statement?We get different location for mysql socket file as sometimes we change the mysql default data directory.

$conn = mysql_connect(‘$dbhost:/var/lib/mysql-databases/mysqld2/mysql.sock’,’ $dbuser’, ‘$dbpass’) or die (‘Error connecting to mysql’);

Condition-4:Port and socket changed

Lets say we changed both port and socket for some security reasons.port cahnged to 3309 and socket to /var/lib/mysql-databases/mysqld2/mysql.sock What will be our connection statement?

$conn = mysql_connect(‘$dbhost:/var/lib/mysql-databases/mysqld2/mysql.sock’,’ $dbuser’, ‘$dbpass’) or die (‘Error connecting to mysql’);

Categories: Database Tags: , ,

How To Run Multiple instances of Mysql Server on a Single Linux Server

Yesterday I faced a problem where our developer team wanted to have two mysql server with different root passwords.The problem was I am having only one redhat linux test server.After lots of thinking I searched for “multiple instances of mysql server” in Google.I found lots of different article on this and all are little bit confusing.Finally after lots of testing I succeeded in getting up and running two different instances of mysql in singleserver.Below are the steps you can follow to do the same.

Step-1:Login to your server as root user

Step-2:Login to your mysql server as root and execute the following command

mysql>GRANT SHUTDOWN ON *.* TO 'multi_admin'@'localhost' IDENTIFIED BY 'secret';

It means we are giving shutdown privileges to the user “multi_admin”

step-3:come out of mysql prompt and stop mysql server.To stop you can execute

[root@localhost ~]#	service mysql stop
[root@localhost ~]#/sbin/service mysql stop

Step-4:Now we need to locate the mysql config file “my.cnf” and change it as per our requirement which is located at /etc/my.cnf

N:B:-If you are not finding the my.cnf file then go to your mysql installation folder.In my case it is /usr/share/mysql.You will find four configuration files like “my-small.cnf”,” my-medium.cnf”,” my-large.cnf “,” my-huge.cnf”.You can take any one and put it in /etc and rename it to my.cnf.

You can also execute the command below to get all of the above file.

[root@localhost ~]# find / -name mysql*.cnf

Step-5:open my.cnf and comment out the following lines in [mysql] section

# The MySQL server
#port           = 3306
#socket         = /var/run/mysql/mysql.sock
# Change following line if you want to store your database elsewhere
#datadir        = /var/lib/mysql

Step-6:Now just below [mysqld] section put the following lines

mysqld     = /usr/bin/mysqld_safe
mysqladmin = /usr/bin/mysqladmin
log        = /var/log/mysqld_multi.log
user       = multi_admin
password   = admin123

Step -7:Then to create our desired two instances add the below lines after [mysql_multi] section. We have to define different unique values for each server instance or else the data and socket files for both servers collide and as a result mysql server will fail to start or your data could be corrupted.

port       = 3306
datadir    = /var/lib/mysql
pid-file   = /var/lib/mysql/
socket     = /var/lib/mysql/mysql.sock
user       = mysql
log-error  = /var/log/mysql1.err

port       = 3307
datadir    = /var/lib/mysql-databases/mysqld2
pid-file   = /var/lib/mysql-databases/mysqld2/
socket     = /var/lib/mysql-databases/mysqld2/mysql.sock
user       = mysql
log-error  = /var/log/mysql2.err

Step-8:Save the configuration file and now create the files and folders as we have mentioned in the above configuration.To do that execute the following commands.

[root@localhost ~]#  mkdir -P /var/lib/mysql-databases/myqld2

Step-9:For mysql instance 1 we are using the defaults for previously running mysql server But we need to Create the data directory for instance2.Create it by

[root@localhost ~]# mkdir /var/lib/mysql-databases/mysql

Step-10:Copy the mysql database files from the original instance to the second instances database directory and change the ownership of the data directory to the mysql user so the instance can read them.

[root@localhost ~]# cp -r /var/lib/mysql/mysql/ /var/lib/mysql-databases/mysqld2/mysql
[root@localhost ~]# chown -R mysql:mysql /var/lib/mysql-databases

Step-11:Now the two instances are ready to run.We can start them by the folowing command

[root@localhost ~]#mysqld_multi start
To view the status of the instances you can run
[root@localhost ~]# mysqld_multi report
Reporting MySQL servers
MySQL server from group: mysqld1 is running
MySQL server from group: mysqld2 is running

You can see that the mysqld_multi script has started multiple mysql processes with the following commands.

ps -e | grep "mysql"

To stop both instances just execute the below command.

rhys@linux-n0sm:~> mysqld_multi stop

We are also able to control individual instances by referring to the assigned number.

rhys@linux-n0sm:~> mysqld_multi stop 1

To verify this
rhys@linux-n0sm:~> mysqld_multi report

Reporting MySQL servers
MySQL server from group: mysqld1 is not running
MySQL server from group: mysqld2 is running

rhys@linux-n0sm:~> mysqld_multi start 1
rhys@linux-n0sm:~> mysqld_multi report
Reporting MySQL servers
MySQL server from group: mysqld1 is running
MySQL server from group: mysqld2 is running

Here you need to remember that both the instances running on different port and also having different socket files.You can refer to the topic how to connect to mysql in php in case you are facing any problem to connect ot mysql through some script

Pass command line arguments to perl in EPIC

I am really getting more and more involved to EPIC now a days for editing my perl programs as it has lots of killer features.I would say if you will use this you will really get addicted to it.Already I have discussed about the EPIC INTEGRATION WITH ECLIPSE . Before three days I had a nightmare in finding a solution in eclipse.The question was

Can we pass command line argument in EPIC?

I searched in google but not found any relevant topic.Then after going through the documentation of EPIC given in their website I got some clue and after some R&D I found out how to do.If you are facing the same problem please follow the following steps to pass command line argument in EPIC.

Step-1:Open Eclipse and write your program and save it using some name.For me its

Run–>Run Configurations as shown in fugure 1

Figure-1:Run command tool in EPIC

Step-2:Afer running the configuration you will get a screen like the below image.

Figure-2: EPIC Run tool configuration window

Here myproject name in testperl and file name is which will varry on your case.

Step-3:Now navigate to the Arguments tab and add your argument shown in figure-3

Figure-3:Argument passing window in EPIC

In my case I need to pass a filename as argument which is “abc.txt” .Keep in mind to provide the arguments under program arguments only.Now click on Apply and then click on Run.

Step-4:-Now you should be able to get your desired output.

Best Practices to secure a OPENSSH/SSH Server

What are you using for remote connection?
For linux users there are two protocols which regulate remote connection. One is telnet and the other is ssh.
People use telnet to connect to remote host but problem with telnet is the whole communication between the local host and the remote host is sent in clear text which any one can see if he will put a packet sniffer and start capture the packets. Hence Telnet is not secure.
To avoid this security risk we are using OpenSSH protocol. OpenSSH uses SSH (Secure Shell) protocol which is fully secure as it uses strong encryption like 3DES, Blowfish, AES and also it uses public/private key pair for authentication.
N:B-Whatever steps given below has to be done by following the steps given below.

a.Open two terminals, One for experiment and other for safety if sshd show some problem

b.Take the backup of configuration files

c.After each change reload SSH service only after testing the configuration. You can test it by executing

                         /usr/sbin/sshd –t

d.If you are finding some error in configuration file after executing the above command you should revert back to original config file in order to prevent yourself from getting disconnected.

When configuring SSH the default files we need to edit are

i. /etc/ssh/sshd_config –configuration file for SSH server side.

ii. etc/ssh/ssh_config – Configuration file for client side.

iii.~/.ssh/ -This is the directory where all ssh keypair and authorization file stays

iii./etc/nologin – If this file exists then sshd protocol refuses all login except root login

Now we will come to our topic on configuring a secure SSH server. To make your server secure you can follow the following points. Before changing anything in the default configuration file  always make a backup copy of config files you wish to edit.
1.Change the default port number

By default SSHD protocol runs on port 22. The vast majority of ssh attacks are directed by compromised zombie machines against ssh servers listening on the default port of “22”.Your first task is to change the port for ssh. To do this follow steps below

a. open /etc/ssh/sshd_config file

b. Search for line containing Port 22

c.  Edit that line as Port 2222  //here 2222 port is my choice you can use yours

d.  Save

2.Listen to specific IP Address

In most case you need to connect to your server from your office network or from some specific machine. If you can make your SSHD protocol to listen to those specific IP address and reject others then you will minimize risk of getting attacked from outside world. To do this

a. open /etc/ssh/sshd_config file

b. Search for the line which says

ListenAddress *

c.  Now comment the above line and make entry as per your criteria. Lets say if I will give access to and to access then I have to add following two line



3. Now you need to update IP table rule to allow your allowed IP’s (, to           communicate with the custom port (port 2222 in my case).

4. You can also use IP table throttling feature to throttle the incoming connections

5.    Limit the users(allow or deny) who can access by username
We have already seen how we can limit the number of IP address which can connect to SSH server. We may have multiple users in single system from which some users do not need to access. So we have to restrict that user’s access.  To do sowe can follow the steps

a. Open  /etc/ssh/sshd_config file

b. Add the following line to allow specific user.For example allow users root ,hari,prit

AllowUsers root hari prit

c.        Also we can allow specific groups. To allow a group called ssh access add the line

AllowGroups sshaccess

d. similarly if we want to deny some specific users or groups to use ssh we can add the deny lines .Ex:-If I want to deny users navin,amiya and group kopex then I have to add lines

     DenyUsers navin amiya

     DenyGroups kopex

It all depend upon you how you want to put user access control

6.    Do not allow root login
As we know the power of root we should not allow root users to log in rather we should create some sudo users and we can limit them to doing specific task. Also if someone needs to work as root they can use su command. To disable root login

a. Open /etc/ssh/sshd_config file

b.Uncomment the following line

        PermitRootLogin no

7.Disable Empty Passwords
You should not allow remote login from accounts with empty passwords. If you do this there is chance that some bots will try to log in continuously and damage your system.To do this

a.Open /etc/ssh/sshd_config file

b.Edit the line containing PermitEmptyPasswords  to no

        PermitEmptyPasswords no

8. Configure client idle Timeout Interval
You can set idle time interval for the users who are logging through SSH so that if someone has forgotten to logout from a session the system will log him out immediately. To do this

a. Open /etc/ssh/sshd_config file

b. Set these two lines as per your requirement

               ClientAliveInterval 180         //180 is in seconds
               ClientAliveCountMax 0

9.Disable Host-Based Authentication
Avoid using this method as if you add one host it does not ask for any kind of password to login.To disable host based authentication you can do the following steps

a. Open /etc/ssh/sshd_config file

b. Edit the entry HostbasedAuthentication in the file as below

                     HostbasedAuthentication   no

10. Always use Latest version of SSH as always latest version will be having patches and more security features which makes your job easy or else you have to patch with the latest patch from the vendor.

11. User strong SSH passwords and paraphrases so that it won’t be easy for someone to crack. You can check your password strength using john the ripper tool

12. Use Authentication based on only public/private keys
You can also disable the password and use public/private key pairs to login to remote system. But it is advisable to protect your keys by giving strong paraphrases so that if someone takes your key still he needs to know paraphrase to login

To disable password logins, add the following to sshd_config:
                                                   PasswordAuthentication no

13.  Restrict users to their home directories
Using some tools or chroot concept you can restrict users to their home directories so that they cannot move or delete the configuration and system files.

14. Allow/Deny using TCP Wrappers
As ssh is associated with the library we can implement TCP wrapper concept. So we can allow/deny some specific IP/Host by putting entries into /etc/hosts.allow and /etc/hosts.deny file. For that we need to put an entry at the end of the file like
               sshd : 192.168.1. 8

to allow or deny the IP and to connect the server using SSH.

15. Disable .rhosts Files
The rhosts file specifies which remote computer or users can access a local account using rsh or
rcp commands. So you can disable this. To disable this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing IgnoreRhosts and make it to yes

         IgnoreRhosts  yes

16. Reduce MaxStartups
MaxStartup means the ability of SSH server to handle unauthorized access to a server at a given instance. This will help in coordinated attack from different server at same time. To achieve this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing MaxStartup and replace it as

MaxStartups 4:10:8

Here the 4:10:8 tells the ssh server to, “allow 4 users to attempt logging in at the same time, and to randomly and increasingly drop connection attempts between 4 and the maximum of 8”. Note: this should be increased on servers with substantial numbers of valid ssh users logging in.

17. Hide openssh version
This step is not only applicable for SSH but also applicable for all the services running on the system. As no tools/software/packages is free of bugs. This is why people release different versions. If you are running an older version of SSH and hacker knows this he will first try to find out the bugs in this version and using those info he may attack on the particular port. To achive this you have to make changes in source code of ssh and recompile it.

18.  Forward X11 only  if needed
By default, the X11Forwarding directive is set to yes. If you don’t need this, set it to no. If you don’t need this you should disable this. To disable this

a.Open /etc/ssh/ sshd_config file

b.Search for X11Forwarding  and edit as

X11Forwarding   no

For X11 forwarding to work, the ForwardX11 declaration or the ForwardX11Trusted declaration must also be set to yes in /etc/ssh/ssh_config client configuration file.SO to disable you can make it no from this file.

19.  Enable a Warning Banner
Set a warning banner for ssh connection in consultation with your legal advisor in order to warn authorized user what legel action you can take against them. To do this defines a text file location in sshd_config file which contains the warning messages. To do this

a. Open /etc/ssh/ sshd_config file

b. Search for the line containing Banner and edit as given below

Banner /etc/issue

Now you can edit the /etc/issue file to put your warnings.

20. Use Logwatch
Make sure to set LogLevel to INFO or DEBUG in sshd_config. I recommend keeping it INFO as it will give you more details. You can use logwatch to manage the SSH logs. To do this

a.Open /etc/ssh/ sshd_config file

b.Change the line containing LogLevel to info

LogLevel INFO

What else you can do?

–Install some security tools to protect your server from brute force attack

–Patch your operating system

–Remove unnecessary packages / software.

–Harden the kernel against synflood and basic DOS attacks.

–Remove common user access to compilers and fetching software (wget, fetch, lynx, etc.).

— Ensure /tmp is in its own partition with noexec, nosuid.   

–Ensure kernel and software is up to date.

–Remove unnecessary users and groups.

–Install chkrootkit and tripwire.