Thursday, 28 February 2013

MySql and Apache

MySql & Apache


Hardening MySql :

1. Secure the server

It is advisable to have the application server and the database server on different machines as many known attacks are possible only once physical access to a machine has been acquired. An attacker may be able to harm our database even without permissions. For this reason, any service running on the same machine as the database should be granted the lowest possible permission that will still allow the service to operate.

Other important works to be taken care of :

·         Install Antivirus and Antispam software

·         Configure the operating system’s firewall

·         Consider the safety of your server's physical location

·         Install the services you intend the machine to run

·         Harden the production server and services

·         Disable unnecessary services

·         Follow services vendors’ recommendations regarding patches and updates needed for the safe and secure operation of their services


2. Disable or restrict remote access

It is suggested to restrict MySQL from opening a network socket. For that, following parameter should be added in the [mysqld] section of my.cnf or my.ini:

skip-networking

The file is located in the "C:\Program Files\MySQL\MySQL Server 5.1" directory on the Windows operating system or "/etc/my.cnf" or "/etc/mysql/my.cnf" on Linux.

This line disables the initiation of networking during MySQL startup.

Another possible solution is to force MySQL to listen only to the localhost by adding the following line in the [mysqld] section of my.cnf

bind-address=127.0.0.1

Use proper GRANT restrictive syntax


3. Disable the use of LOCAL INFILE

We can disable the use of the "LOAD DATA LOCAL INFILE" command, which will help to prevent unauthorized reading from local files. This is especially important when new SQL Injection vulnerabilities in PHP applications are found.

In addition, in certain cases, the "LOCAL INFILE" command can be used to gain access to other files on the operating system, for instance "/etc/passwd", using the following command:

mysql> LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE table1

Or even simpler:

mysql> SELECT load_file("/etc/passwd")

To disable the usage of the "LOCAL INFILE" command, the following parameter should be added in the [mysqld] section of the MySQL configuration file.

set-variable=local-infile=0


4. Change root username and password

The default administrator username on the MySQL server is "root". Hackers often attempt to gain access to its permissions. To make this task harder, rename "root" to something else and provide it with a long, complex alphanumeric password.

To rename the administrator’s username, we can use the rename command in the MySQL console:

mysql> RENAME USER root TO new_user;

To change a user’s password, use the following command-line command:

mysql> SET PASSWORD FOR 'username'@'%hostname' = PASSWORD('newpass');


5. Remove the "test" database

MySQL comes with a "test" database intended as a test space. It can be accessed by the anonymous user, and is therefore used by numerous attacks.

To remove this database, use the drop command as follows:

mysql> drop database test;

Or use the "mysqladmin" command:

shell> mysqladmin -u username -p drop test


6. Remove Anonymous and obsolete accounts

The MySQL database comes with some anonymous users with blank passwords. As a result, anyone can connect to the database To check whether this is the case, do the following:

mysql> select * from mysql.user where user="";

In a secure system, no lines should be echoed back. Another way to do the same:

mysql> SHOW GRANTS FOR ''@'localhost';
To remove the account, execute the following command:

mysql> DROP USER "";



7. Lower system privileges

A very common database security recommendation is to lower the permissions given to various parties. To protect our database, make sure that the file directory in which the MySQL database is actually stored is owned by the user "mysql" and the group "mysql".


8. Lower database privileges

·         Add " --skip-show-database" to the startup script of MySQL or add it to the MySQL configuration file

·         Grant the SHOW DATABASES privilege only to the users you want to use this command

To disable the usage of the "SHOW DATABASES" command, the following parameter should be added in the [mysqld] section of the /etc/my.cnf:

[mysqld]
skip-show-database


9. Change the root directory

By using the chroot environment, the write access of the MYSQL processes (and child processes) can be limited, increasing the security of the server.

Ensure that a dedicated directory exists for the chrooted environment.


10. Remove History

During the installation procedures, there is a lot of sensitive information that can assist an intruder to assault a database. This information is stored in the server’s history and can be very helpful if something goes wrong during the installation. By analyzing the history files, administrators can figure out what has gone wrong and probably fix things up. However, these files are not needed after installation is complete.

Therefore, we should remove the content of the MySQL history file (~/.mysql_history).



Creating backup for MySql :


For backup, mysqldump can be used to dump a database or a collection of databases for backup or transfer to another SQL server.  There are three general ways to invoke mysqldump:

shell> mysqldump [options] database_name [table_name ...]

This method creates a backup of the specified table of the specified database.

shell> mysqldump [options] --database_name database_name ...

This method creates a backup of the specified databases .

shell> mysqldump [options] –all-databases

This method creates a backup of all the databases.


Reset MySql Password:


Step 1: Log on to the system as the Unix user such that the mysqld server runs.
Step 2: Locate the .pid file that contains the server's process ID. The exact location and name of this file depends on distribution, host name, and configuration. Common locations are
/var/lib/mysql/, /var/run/mysqld/, and /usr/local/mysql/data/. Generally, the file name has an extension of .pid and begins with either mysqld or the system's host name.
Stop the MySQL server by sending a normal kill to the mysqld process, using the path name of the .pid file in the following command:
shell> kill 'cat /mysql-data-directory/host_name.pid'
Step 3: Create a text file containing the following statements. Set the new password 'inctfmysql' using following command.
UPDATE mysql.user SET Password=PASSWORD('inctfmysql') WHERE User='root';
FLUSH PRIVILEGES;
The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
Step 4: Save the file named as  /home/me/mysql-init.
Step 5: Start the MySQL server with the special --init-file option:
shell> mysqld_safe --init-file=/home/me/mysql-init &
The server executes the contents of the file named by the --init-file option at startup, changing each root account password. After the server has started successfully, delete
/home/me/mysql-init. You should now be able to connect to the MySQL server as root using the new password. Stop the server and restart it normally.

Checking whether Apache is running or not:


A simple script to check whether Apache is running :

#!/bin/sh
run=`ps ax | grep /usr/sbin/httpd | grep -v grep | cut -c1-5 | paste -s -`
if [ "$run" ];
then
echo "Apache is running"
else
/etc/init.d/httpd start
fi

 In addition to this, the problems provided in http://hackthissite.org/. invoked basic knowledge related to HTML and SQL Injection. The tricks provided in https://www.staysecureonline.com/staying-safe-online/  provided a sound knowledge towards the detection of unsecured sites and their webpages.

http://samsclass.info/124/flashcards/index.html gave a good overview of the terminologies related to ethical hacking.


Friday, 25 January 2013

Unix Shell scripting examples


 Some Unix Shell scripting examples


(Q1.) Write a script to calculate the factorial of a number entered by the user .


$vi factorial.sh

echo "Enter the number : "

read a

fact=1

while((a>0))

do

fact=$(($fact * a))

a=$(($a - 1))

done

echo "The factorial of the given number is " $fact

For Output : $sh factorial.sh

                    Enter the number : 5

                    The factorial of the given number is 120


*********************************************************************************

 (Q2.) Write a script to check whether the number entered by user is palindrome or not.


$vi palindrome.sh

echo "Enter the number :"

read num

n=$num

sum=0

while((num>0))

do

rem=$(($num%10))

num=$(($num/10))

sum=$(($sum*10+$rem))

done

if(($sum==$n))

then

echo "The given number is a palindrome"

else

echo "The given number is not a palindrome"

fi

For Output : $sh palindrome.sh

                    Enter the number : 221122

                    The given number is a palindrome


*********************************************************************************

 (Q3.) Write a script to check whether the number entered by the user is Armstrong or not.


$vi armstrong.sh

echo "Enter the number : "

read num

sum=0

n=$num

while((num>0))

do

rem=$(($num%10))

num=$(($num/10))

sum=$(($sum + $rem*$rem*$rem))

done

if(($sum==$n))

then

echo "The number is armstrong"

else

echo "The number is not armstrong"

fi

For Output : $sh armstrong.sh

                    Enter the number : 153

                    The number is armstrong


*********************************************************************************


 (Q4.) Write a script to generate a Fibonacci series where number of terms will be entered by the user .


$vi fibonacci.sh

echo "Enter the number of terms in fibonacci series : "

read a

fo=0

f1=1

echo "The series is shown below :"

echo -n $fo " " $f1 " "

for((i=1; i<$a-1; i++))

do

sum=$(($fo+$f1))

fo=$f1

f1=$sum

echo -n $sum " "

done

For Output : $sh fibonacci.sh

                    Enter the number of terms in fibonacci series : 8       

                    The series is shown below :

                    0  1  1  2  3  5  8  13


*********************************************************************************

 (Q5.) Write a script to check whether the number entered by the user is prime or not .


$vi prime.sh

echo "Enter the number : "

read n

c=0

for((i=2; i<=$n/2; i++))

do

if(($n%i==0))

then

c=1

fi

done

if(($c==o))

then

echo "The number is prime"

else

echo "The number is not prime"

fi

For Output : $sh prime.sh

                    Enter the number : 7

                    The number is prime


*********************************************************************************

 (Q6.) Write a script to generate the following pattern where maximum limit is entered by the user .

                          1
                          1 2
                          1 2 3
                          1 2 3 4 ...
$vi pattern.sh

echo "Enter the maximum limit : "

read n

for((i=1; i<$n+2; i++))

do

for((j=1; j<i; j++))

do

echo -n $j

done

echo " "

done

For Output : $sh pattern.sh

                    Enter the maximum limit : 4

                          1
               1 2
               1 2 3
               1 2 3 4

                  

*********************************************************************************

(Q7.) Write a script to generate the multiplication table of the number entered by the user.


$vi table.sh

echo "Enter the number : "

read n

for((i=1; i<11; i++))

do

echo $n " * " $i " = " $(($n*$i))

done

For Output : $sh table.sh

                    Enter the number : 7

                    7 * 1 = 7

                    7 * 2 = 14

                    7 * 3 = 21

                    7 * 4 = 28

                    7 * 5 = 35

                    7 * 6 = 42

                    7 * 7 = 49

                    7 * 8 = 56

                    7 * 9 = 63

                    7 * 10 = 70


*********************************************************************************

(Q8.) Write a script to check whether the filename entered by the user exists or not. If it exists then check whether it is empty or not.


$vi filecheck.sh

echo "Enter the file name : "

read a

if test -e $a

then

echo "File Exists"

if test -s $a

then

echo "File is not empty"

else

echo "File is empty"

fi

else

echo "File does not exist"

fi

For Output : $sh filecheck.sh

                    Enter the filename : frndz

                    File Exists

                    File is not empty

*********************************************************************************

 (Q9.) Write a script to check whether the string entered by the user exists in the filename entered by the user.


$vi strchk.sh

echo "Enter String :"

read a

echo "Enter filename :"

read b

if grep -c $a $b

then

echo "The given string is found ."

else

echo "The given string is not found ."

fi

For Output : $sh strchk.sh

                    Enter string : make

                    Enter filename : frndz

                    The given string is found .

*********************************************************************************
(Q10.) Write a script to run a C program .

$vi cprog.c

#include<stdio.h>

void main()

{int a;

printf("Enter a number : ");

scanf("%d",&a);

if(a%2==0)

printf("The number is even");

else

printf("The number is odd");

}

To compile the program :   $cc cprog.c

 To run the program :  ./a.out

Output :       Enter a number : 28

                    The number is even

*********************************************************************************


Connection of Java program with PostgreSql database

Connection of Java program with PostgreSql database

For connecting a Java program to PostgreSql, we need the following software :
1) Jdk (any version)
2) PostgreSql database
3) PostgreSql Driver (postgresql-jdbc3.jar)
   
Download the  postgresql-jdbc3.jar  from the internet.

Set CLASSPATH of MySql Driver :
Set the classpath  i.e the location of  postgresql-jdbc3.jar  in the environment variable named CLASSPATH .

However the Java Program shown below creates the table student from the program itself and inserts values in it. If we don't want to create the table in the program and like to use the table student already created in database, then skip the 8th line of the program containing the create table statement.          
In the following program,
         table name = student        (table to be connected)
         username = postgres       (username is set by user during installation)
         password = postgres        (password is set by user during installation)
         database = postgres        (default database of PostgreSql)

Java Program :

import java.sql.*;
public class DBCpostgresql
{public static void main(String args[]) throws Exception
{Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres","postgres","postgres");
Statement st= con.createStatement();
int i1= st.executeUpdate("create table student(sid integer, sname text, marks integer)"); //create table
int i2=st.executeUpdate("insert into student values(7,'mayank',97)");                   //insertion of values
int i3=st.executeUpdate("insert into student values(14,'vikash',97)");                     //insertion of values
ResultSet rs = st.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getString(1)+"    "+rs.getString(2)+"    "+rs.getString(3));  //printing data on console
rs.close();
st.close();
con.close();
}
}

   
Note :  In case of database like PostgreSql, we need to download the jar file containing Driver class (postgresql-jdbc3.jar) separately and then set its classpath as it is not supplied along with the PostgreSql database software.