Sunday, March 25, 2012

connecting MySQL database using php script

Advertisements

We have seen a lot of php scripts accessing mysql databases. But ever wondered how they work? Here we will discuss a small php script which can access mysql database(test) and list some columns of the table(people). After reading this you wil know how to connect to mysql using php script from CLI or command line interface. You will need mysqli php module loaded for the php script to work. We will discuss these in detail. In this example we have one Centos 5.2 os installed on a vmware workstation.

Pre-requisites:
you must have mysql server installed and running in your system.
And the php rpms installed

Checking the mysql status:
[root@server ~]# /etc/init.d/mysqld status
mysqld (pid 5601) is running...
[root@server ~]#

Checking the php rpms:
[root@server ~]# rpm -qa | grep -i php
php-cli-5.1.6-20.el5
php-common-5.1.6-20.el5
php-5.1.6-20.el5
php-mysql-5.1.6-20.el5
php-pdo-5.1.6-20.el5
[root@server ~]#

You must have mysqli module installed and loaded. Then only php script can connect to mysql.
[root@server ~]# php -m | grep mysql
mysql
mysqli
pdo_mysql
[root@server ~]#

If not loaded, install it using the following command
[root@server ~]# yum install php-mysql

Now in this example, we will connect to mysql and list the first_name and last_name of the users in people table of the databases test.
This is what we have in mysql.
[root@server ~]# mysql -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.0.45-log Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
3 rows in set (0.08 sec)

mysql> use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql>

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| people         |
+----------------+
1 row in set (0.00 sec)

mysql> select * from people;
+---------------------+-----------+------------+
| first_name          | last_name | mob_number |
+---------------------+-----------+------------+
| Randeep Raman 1234  | NULL      | NULL       |
| Nibul Roshan  5678  | NULL      | NULL       |
| Afilaj Hussain 1357 | NULL      | NULL       |
| Renjith             | menon     | 1234       |
+---------------------+-----------+------------+
4 rows in set (0.00 sec)
mysql>

This will be our result for the script we are going to make.
mysql> select first_name, last_name from people;
+---------------------+-----------+
| first_name          | last_name |
+---------------------+-----------+
| Randeep Raman 1234  | NULL      |
| Nibul Roshan  5678  | NULL      |
| Afilaj Hussain 1357 | NULL      |
| Renjith             | menon     |
+---------------------+-----------+
4 rows in set (0.00 sec)
mysql>

The script is as follows.
[root@server ~]# cat test.php
<?php
/* Connection object */
/* now we will define the connection object */
/* syntax is as follows */
/* $conn_object_name = new mysqli("hostname", "user_name", "Password", "Database_name");*/
$conn1 = new mysqli("localhost","root","redhat","test");

/* Defining the Query to be executed */
/* We want to list the first_name and the last_name entries from the table people */
$query1 = "select first_name,last_name from people";

/* Now executing the query and storing the result */
$result1 = $conn1->query($query1);

/* Printing the output */
while($obj1 = $result1->fetch_object())
        {
        printf("%s %s\n",$obj1->first_name, $obj1->last_name);
        }
?>
[root@server ~]#

Now testing the script as follows.
[root@server ~]# php -q test.php
Randeep Raman 1234
Nibul Roshan  5678
Afilaj Hussain 1357
Renjith menon
[root@server ~]#

It woorks :)

Thursday, March 22, 2012

Integrating apache tomact with mod_jk

Advertisements

This tutorial explains how to install and configure web-servers Apache or httpd 2 and tomcat 7 and integrate them with mod_jk or jk_module in Centos operating system. All the traffic to the apache will be redirected to tomcat.

We have one Centos 5.2 32 bit vmware instance
IP : 192.168.137.65
Hostname : modjk.lap.work

Wednesday, March 21, 2012

MySQL replication in Linux

Advertisements

Database replication is the frequent copying data from a database in one server to a database in another server to make the data in all servers consistent. Usually one database server(master) maintains the master copy of the database and other servers(slaves) maintain slave copies of the database. Database writes are written to the master database server and are then replicated by the slave database servers. MySQL replication is asynchronous - slaves need not be connected permanently to receive updates from the master. This means that updates can occur over long distance connections and even over temporary or intermittent connections such as a dial-up service. Depending on the configuration, we can replicate all databases, selected databases, or even selected tables within a database.

There are mainly three types of replication: 
Snapshot replication: Data on one server is simply copied to another server, or to another database on the same server.
Merging replication: Data from two or more databases is combined into a single database.
Transactional replication: Users receive full initial copies of the database and then receive periodic updates as data changes.

Benefits of replication:
Scale-out solutions - spreading the load among multiple slaves to improve performance. In this environment, all writes and updates must take place on the master server. Reads, however, may take place on one or more slaves. This model can improve the performance of writes (since the master is dedicated to updates), while dramatically increasing read speed across an increasing number of slaves.
Data security - because data is replicated to the slave, and the slave can pause the replication process, it is possible to run backup services on the slave without corrupting the corresponding master data.
Analytics - live data can be created on the master, while the analysis of the information can take place on the slave without affecting the performance of the master.
Long-distance data distribution - if a branch office would like to work with a copy of your main data, you can use replication to create a local copy of the data for their use without requiring permanent access to the master.

In this tutorial we are using the following version of mysql
mysql-server-5.0.45-7.el5

We have two systems with Centos 5.2 os
192.168.137.100 server.lap.work server (Master)
192.168.137.55 apache.lap.work apache (Slave)

On both systems install mysql server.
yum install mysql*

In master system in the mysql ocnfiguration file and the log-bin variable and server-id entries
Master side:
[root@server mysql]# cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
log-error=/var/log/mysqld.log
log-bin
server-id=1
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[root@server mysql]#

And restart the mysql service
/etc/init.d/mysqld restart

You can see the status of the master process as
mysql> show master status;
+-------------------+----------+--------------+------------------+
| File                      | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| mysqld-bin.000003 |      342   |                       |                            |
+-------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
mysql>

And can check the server id and log-bin entries as
mysql> show variables like 'server%';
+---------------+-------+
| Variable_name | Value  |
+---------------+-------+
| server_id          | 1         |
+---------------+-------+
1 row in set (0.00 sec)
mysql> show variables like 'log%';
+---------------------------------+---------------------+
| Variable_name                            | Value                       |
+---------------------------------+---------------------+
| log                                              | OFF                        |
| log_bin                                        | ON                         |
| log_bin_trust_function_creators    | OFF                       |
| log_error                                     | /var/log/mysqld.log   |
| log_queries_not_using_indexes    | OFF                        |
| log_slave_updates                       | OFF                        |
| log_slow_queries                         | OFF                        |
| log_warnings                               | 1                              |
+---------------------------------+---------------------+
8 rows in set (0.00 sec)
mysql>

We have to make a user and give him replication permissions. Here we  are using root user
mysql> grant replication slave on *.* to 'root'@'%' identified by 'redhat';
mysql> grant select,super,reload on *.* to 'root'@'%' identified by 'redhat';

Now checking the grants for root user:
mysql> show grants for root;
+------------------------------------------------------------------------------------------------------+
| Grants for root@%                                                                                             |
+------------------------------------------------------------------------------------------------------+
| GRANT SELECT, RELOAD, SUPER, REPLICATION SLAVE ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD '27c30f0241a5b69f' |
+------------------------------------------------------------------------------------------------------+
1 row in set (0.04 sec)
mysql>

Now we can take the backup of databases in master server and copy to slaves. before copying lock the tables with read lock. So that writes wont happen when we take backup and transfer
mysql> flush tables with read lock;

You can unlock it aftet the transfer as
mysql> unlock tables;

Checking the log status
mysql> show binary logs;
+-------------------+-----------+
| Log_name              | File_size    |
+-------------------+-----------+
| mysqld-bin.000001 |       117    |
| mysqld-bin.000002 |       117    |
| mysqld-bin.000003 |       342    |
+-------------------+-----------+
3 rows in set (0.04 sec)
mysql>

Checking the log events
mysql> show binlog events;
+-------------------+-----+-------------+-----------+-------------+--------------------------------+
| Log_name              | Pos  | Event_type  | Server_id   | End_log_pos | Info                                          |
+-------------------+-----+-------------+-----------+-------------+--------------------------------+
| mysqld-bin.000001 |   4   | Format_desc |              1 |          98       | Server ver: 5.0.45-log, Binlog ver: 4 |
| mysqld-bin.000001 |  98  | Stop              |         1      |         117      |                                                        |
+-------------------+-----+-------------+-----------+-------------+--------------------------------+
2 rows in set (0.00 sec)
mysql>

Client side:
In client server also we have to set the server id, but different that the id of the master server.
[root@apache mysql]# cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
server-id=100
log-error=/var/log/mysqld.log
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[root@apache mysql]#

Restart the mysql server and check the id
mysql> show variables like 'server%';
+---------------+-------+
| Variable_name | Value  |
+---------------+-------+
| server_id          | 100     |
+---------------+-------+
1 row in set (0.00 sec)
mysql>

First you have tostop the slae service
mysql> stop slave;
Query OK, 0 rows affected (0.01 sec)

and have to set the master details. The data to be given here will be obtained by running" show master status" on master. File name and position will be there in the output.
mysql> change master to master_host='server', master_user='root',  master_password='redhat', master_log_file='mysqld-bin.000003', master_log_pos=342;
Query OK, 0 rows affected (0.01 sec)

now starting the slave service
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

Checking the slave status
mysql> show slave status;

mysql> show processlist;
+----+-------------+-----------+------+---------+------+-----------------------------+------------------+
| Id | User        | Host      | db   | Command | Time | State                                                         | Info             |
+----+-------------+-----------+------+---------+------+-----------------------------+------------------+
| 27 | root        | localhost | NULL | Query   |    0 | NULL                                                 | show processlist |
| 30 | system user |           | NULL | Connect |   60 | Waiting for master to send event         | NULL             |
| 31 | system user |           | NULL | Connect |   60 | Has read all relay log; waiting for the slave I/O thread to update it | NULL             |
+----+-------------+-----------+------+---------+------+-----------------------------+------------------+
3 rows in set (0.00 sec)
mysql>

In this example we have a database named test and a table people in it. in the table we have three entries..
mysql> use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql>

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| people               |
+----------------+
1 row in set (0.00 sec)
mysql> select * from people;
+---------------------+-----------+------------+
| first_name                | last_name | mob_number |
+---------------------+-----------+------------+
| Randeep Raman 1234  | NULL      | NULL       |
| Nibul Roshan  5678  | NULL      | NULL       |
| Afilaj Hussain 1357 | NULL      | NULL       |
+---------------------+-----------+------------+
3 rows in set (0.00 sec)
mysql>

Now on the master server we update the table by insertting a new raw
mysql> INSERT INTO people (first_name,last_name,mob_number) VALUES ('Renjith','menon','1234');
Query OK, 1 row affected (0.00 sec)

mysql> select * from people;
+---------------------+-----------+------------+
| first_name                 | last_name | mob_number |
+---------------------+-----------+------------+
| Randeep Raman 1234  | NULL      | NULL       |
| Nibul Roshan  5678  | NULL      | NULL       |
| Afilaj Hussain 1357 | NULL      | NULL       |
| Renjith             | menon     | 1234       |
+---------------------+-----------+------------+
4 rows in set (0.00 sec)
mysql>

It should be reflected in the slave machine
Before
mysql> select * from people;
+---------------------+-----------+------------+
| first_name          | last_name | mob_number |
+---------------------+-----------+------------+
| Randeep Raman 1234  | NULL      | NULL       |
| Nibul Roshan  5678  | NULL      | NULL       |
| Afilaj Hussain 1357 | NULL      | NULL       |
+---------------------+-----------+------------+
3 rows in set (0.00 sec)
mysql>

After
mysql> select * from people;
+---------------------+-----------+------------+
| first_name          | last_name | mob_number |
+---------------------+-----------+------------+
| Randeep Raman 1234  | NULL      | NULL       |
| Nibul Roshan  5678  | NULL      | NULL       |
| Afilaj Hussain 1357 | NULL      | NULL       |
| Renjith             | menon     | 1234       |
+---------------------+-----------+------------+
4 rows in set (0.00 sec)

You can check the logs in slave machine if there is any errors
mysql>
[root@apache ~]# tail /var/log/mysqld.log
120321 21:05:42 [Note] Slave I/O thread killed while reading event
120321 21:05:42 [Note] Slave I/O thread exiting, read up to log 'mysqld-bin.000003', position 342
120321 21:05:42 [Note] Error reading relay log event: slave SQL thread was killed
120321 21:05:54 [Note] Slave SQL thread initialized, starting replication in log 'mysqld-bin.000003' at position 342, relay log '/var/run/mysqld/mysqld-relay-bin.000002' position: 480
120321 21:05:54 [Note] Slave I/O thread: connected to master 'root@server:3306',  replication started in log 'mysqld-bin.000003' at position 342
120321 21:05:57 [Note] Slave I/O thread killed while reading event
120321 21:05:57 [Note] Slave I/O thread exiting, read up to log 'mysqld-bin.000003', position 342
120321 21:05:57 [Note] Error reading relay log event: slave SQL thread was killed
120321 21:06:05 [Note] Slave SQL thread initialized, starting replication in log 'mysqld-bin.000003' at position 342, relay log '/var/run/mysqld/mysqld-relay-bin.000001' position: 4
120321 21:06:05 [Note] Slave I/O thread: connected to master 'root@server:3306',  replication started in log 'mysqld-bin.000003' at position 342
[root@apache ~]#

In the salve system there are some files which has information related to replication details
[root@apache ~]# ll /var/lib/mysql/
total 20536
-rw-rw---- 1 mysql mysql 10485760 Mar 21 20:23 ibdata1
-rw-rw---- 1 mysql mysql  5242880 Mar 21 20:23 ib_logfile0
-rw-rw---- 1 mysql mysql  5242880 Mar 20 18:16 ib_logfile1
-rw-rw---- 1 mysql mysql       67 Mar 21 21:21 master.info
drwx------ 2 mysql mysql     4096 Mar 20 18:16 mysql
srwxrwxrwx 1 mysql mysql        0 Mar 21 20:23 mysql.sock
-rw-rw---- 1 mysql mysql       66 Mar 21 21:21 relay-log.info
drwx------ 2 mysql mysql     4096 Mar 21 12:33 test
[root@apache ~]#
[root@apache ~]# cat /var/lib/mysql/master.info
14
mysqld-bin.000003
491
server
root
redhat
3306
60
0
0
[root@apache ~]#
[root@apache ~]# cat /var/lib/mysql/relay-log.info
/var/run/mysqld/mysqld-relay-bin.000002
385
mysqld-bin.000003
491
[root@apache ~]#

Tuesday, March 20, 2012

Configuring samba swat in linux

Advertisements

Samba is a linux software helps to transfer files between a linux box and windows box. Using NFS you can share files between two linux systems, but not with a linux system and windows system. Using WinSCP you can transfer files between linux and windows. But it is very slow and very time consuming. Samba is fast. Samba-swat is a web interface (or samba web administration tool) for samba. Using samba swat, one can configure samba, define shares, configure printers, edit smb.conf parameters, we status of the samba services, stop and restart services, view the current samba configuration and even change passwords and add samba users. This blog post tutorial explains how to install and configure samba swat in centos linux.

Friday, March 16, 2012

ubuntu default root password

Advertisements

You may not login as root user in newly installed ubuntu or debian desktop server because you don't know the default root password. The thing is there is no default root password. You can set the root password as.

Login as the normal user u created doing the installation with the password you specified. Then run

$sudo passwd root
then it will prompt for your logged users password. Entering the password the system will prompt for the credentials for the root password. Give the password you want to set.

Wednesday, March 14, 2012

Securing tmp in centos linux

Advertisements


Securing /tmp is very important. /tmp is world writable directory. So if some intruders get acces to /tmp, its a potential threat. The main thing we have to do is disabling running of scripts in this directory. Now we will see how to harden or secure /tmp /vr/tmp and /dev/shm in centos linux. This tutorial has examples also.

First of all before doing any changes, create a back up file. Make this a habit
cp /etc/fstab /etc/fstab.bak

Securing /tmp:
Create a 5Gb file for /tmp partition (you can adjust the size according to your needs)
dd if=/dev/zero of=/var/tempFS bs=1024 count=5000000

Make ext3 filesystem in the file we just created. Because we are going to use this file to store data.
mkfs.ext3 /var/tempFS

Create  current bckup of the /tmp directory
cp -Rpf /tmp /tmp.bkp

Now mount the newly created file as /tmp
mount -o loop,noexec,nosuid,rw /var/tempFS /tmp

Because /tmp directory is universly writable and nobody can delete files created by others we will set permission 777 + sticky bit =1777
chmod 1777 /tmp

Copy the old data to new /tmp
cp -Rpf /tmp.bkp/* /tmp/
If the old /tmp was empty, it might throw some errors. Don't worry.

Now you can edit fstable and make changes for the /tmp entry
vi /etc/fstab
/var/tempFS  /tmp ext3 loop,nosuid,noexec,rw 0 0

Remount the /tmp for making effects.
mount -o remount /tmp

Securing /var/tmp:
move the /var/tmp directory to some other name
mv /var/tmp /var/tmp.bkp

Now create a link /var/tmp and point it to /tmp. The command is as follows
ln -s /tmp /var/tmp

cp /var/tmp.bkp/* /tmp/
If the old /var/tmp was empty, it might throw some errors. Don't worry

Securing /dev/shm:
vi /etc/fstab
add nosuid and noexec to mount options
tmpfs     /dev/shm    tmpfs   defaults,nosuid,noexec     0 0
save the file

Remount to make the effect
mount -o remount /dev/shm

Monday, March 12, 2012

configuring iptables in linux

Advertisements


iptables is a user space application program that allows a system administrator to configure the tables provided by the Linux kernel firewall (implemented as different Netfilter modules) and the chains and rules it stores.

This article is a tutorial regarding how to configure or implement firewall using Linux security firewall iptables. This article explains and give examples of default and user defined iptables tables, chains, acl syntax, writing deleting and replacing iptables rules, blocking or allowing hosts or ip addresses and ports, port or ip redirection, logging options, using linux box as router using iptables, Masquerading, Network address translation (NAT), source-nat (SNAT), destination-nat (DNAT) and netmap

iptables mainly operates at Layers 3 & 4. Layer 3 deals with Source & Destination IP addresses and layer 4 deals with protocols and ports

To Check whether IPTables is enabled or not in the kernel,
#cat /boot/config* | grep CONFIG_NETFILTER
CONFIG_NETFILTER=y

The Main structure of the iptables is as follows.
Tables->Chains->Rules
Tables may contains a number of chains and each chain may contail a number of rules.

Main Tables
There are mainly three tables.

Mangle  -   Allows altering of packats TOS,TTL etc
NAT     -   Network Address Translation. Allow changing sourse destination IP addresses and ports.
Filter     -   Allows IP Packet filtering. [INPUT,FORWARD,OUTPUT]

Iptables rule syntax
1. command
2. tables
3. chain
4. protocol
5. source or destination
6. Jump target

eg:
iptables -t filter -I INPUT -p tcp -s 192.168.1.100 -j ACEEPT

Example :
Blocks any communication to OUR machine from source 192.168.1.77.
iptables -A INPUT -s 192.168.1.77 -j DROP

[root@vm1 ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --  192.168.1.77         anywhere

Saving and restoring iptables rules :
Rules will go if we restart without saving it . So we have to save those rules.
To save the IPTables rules
iptables-save > iptables_rules.txt

To restore the IPTables rules
iptables-restore < iptables_rules.txt

Flushing iptables rules
iptables -F

or you can save the rules by just run
service iptables save
or
/etc/init.d/iptables save
it will save the rules tp /etc/sysconfig/iptables permenantly. if you restart iptables it'll read the rules from this file

Filter table has three chains
1. INPUT
2. OUTPUT
3. FORWARD

Nat table has  three chains
1. PREROUTING
2. POSTROUTING
3. OUTPUT

Filter table has four chains
1. PREROUTING2. INPUT
3. OUTPUT
4. FORWARD
-----------------------------------------------------
[root@vm1 ~]# iptables -L -t filter
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
-----------------------------------------------------
[root@vm1 ~]# iptables -L -t nat
Chain PREROUTING (policy ACCEPT) --before routing occurs -nat
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT) --aftet routing deteremined
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
-----------------------------------------------------
[root@vm1 ~]# iptables -L -t mangle
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
-----------------------------------------------------

-t option is for listing a particular table chains and rules.
filter table is the default one.

[root@vm1 ~]# iptables -L -v
list packet details to and from through a chain

[root@vm1 ~]# iptables -L -v --line-numbers
list the rules with line numbers

[root@vm1 ~]# iptables -L -n
lists the numeric values (IP), Disables the resolutions.[Host and Service]

iptables rule for accepting ssh connections
[root@vm1 ~]# iptables -A INPUT -p tcp --dport 22 -j ACCEPT    

iptables rule for blocking telnet connections
[root@vm1 ~]# iptables -A INPUT -p tcp --dport telnet -j DROP

iptables rule for blocking telnet connections and insert it as rule 1
[root@vm1 ~]# iptables -I  INPUT 1 -p tcp --dport telnet -j DROP

Appending adds the rule to the end. But with inserting you can insert a rule to anywhere in the list. Means to any position[number] in the list.

Deleting an iptables Rule
-D INPUT NUM

[root@vm1 ~]# iptables -D INPUT 3
deletes the rule number 3 from INPUT chain of defalt table.

Or we can delete like this.
iptables -D INPUT -p tcp --dport 22 -j ACCEPT

Replacing an iptables Rule
-R Chain_name NUM

To replace the 1st rule
[root@vm1 ~]# iptables -R INPUT 1 -p tcp --dport telnet -j ACCEPT
IPTables rules are Dynamic. The ssh/telnet connection will be freezed if rules applied in b/w.

Flushing the rules
iptables -F
Flushing will erase all the existing rules in iptables. If you don't save the rules before flushing all rules will be lost.

[root@vm1 ~]# iptables -L INPUT -v
listing rules only in the INPUT chain with packet counts

iptables -Z INPUT
will  zero all the packet counters

Creating  new chains and Renaming exsisting ones
To create User defined chains
-N Chain_name

[root@vm1 ~]# iptables -N ITS
Created a new chain ITS

Rename chains
-E Old_name New_name

[root@vm1 ~]# iptables -E ITS SPARTANZ

Drop Policy of iptables.
Dropping a policy will drop all the traffic through that chain

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

Writing rules for only one ethernet device:
To filter all the input through eth0
iptables -A INPUT -i eth0 -j DROP

Negation: (!)
iptables -A INPUT -s ! 192.168.1.55 -j DROP
it Drops all other inputs except from 192.168.1.55

example of TCP:
iptables -A INPUT -i eth+ -p tcp --dport telnet -j DROP
Blocks telnet though both or all ethernet devices

example of UDP:
TFTP, SysLog, NTP, DHCP
-p udp, --protocol udp
--sport 123 --dport 123 for NTP

ICMP (Internet Control Messaging Protocol):
Echo request -PING
Echo reply - Pong

-p icmp, --protocol icmp
--icmp-type name/number

iptables -p icmp --help
for getting help about icmp-types

Disabling ping using iptables.
To deny echo-replies from all hosts
iptables -A INPUT -p icmp --icmp-type echo-reply -j DROP

To drop echo-replies from our host
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j DROP

MULTIPORT: (-m multiport)
-p tcp --dport 8080 or --dport web-cache

iptables -A INPUT -p tcp -m multiport --dport 8080,23 -j DROP

MAC ADDRESS FILTERING: ( -m mac --mac-source or --mac-destination )
Better than using IP addresses because ip addresses can be changed but not mac

Denying a host by mac address using iptables
iptables -I INPUT -m mac --mac-source 00:00:00:00:00:00 -j REJECT

Iptables and states :

in INPUT
iptables -I ITS  -m state --state ESTABLISHED -j ACCEPT
Allows communication in already established services

in INPUT
iptables -I ITS  -m state --state NEW,ESTABLISHED -j ACCEPT
Allows new connections and established connections from the system

Jump Targets in iptables :
ACCEPT -> Sends packets to other rules or processes
DROP -> Packet will be dropped
REJECT -> Sends a courtesy message back
REDIRECT -> Redirect from one destination to another. must be used with pre-routing in NAT. Local ports only.
LOG -> Allows us to log using SysLog

Logging  :
Creating and enabling iptables log using syslog

iptables logs are kernel logs type. So we have to enable this in syslog.conf as follows
vi /etc/syslog.conf
kern.* /var/log/firewall

Create the log file.
touch /var/log/firewall

Restart the syslog service.
service syslog restart

and logging can be enabled as
iptables -I ITS 1 -p tcp --dport ssh -j LOG

ROUTING
You can use linux box as  router with the help of iptables. First we have to enable packet forwarding in the server we are using as router. This can be done by setting  the sysctl variable as follows

vi /etc/sysctl.conf
net.ipv4.ip_forward = 1
Save the file

Reload the sysctl.conf
sysctl -p

NETWORK ADDRESS TRANSLATION [NAT]

Three types:
Basic NAT. This involves IP address translation only, not port mapping.
PAT : Port Address Translation. This involves the translation of both IP addresses and port numbers.
NAPT : Network Address Port Translation.

SNAT and Masquerading can be done in POSTROUTING chain in nat table.
But DNAT is done in PREROUTING chain in nat table.

SNAT - Source NAT: Translation of Source IP Address. Use when u've only one static IP Address and many systems in local network.

DNAT - Destination NAT: Translation of the destination IP address. Used when traffice comes from internet to local systems.

Three default chains are there in nat table which cannot be deleted.
PREROUTING    - Packet that are destined to a system that is accessible to the local router. [DNAT] Internet to Local area network
POSTROUTING   - If we want to change the local ips to something that is routable. [SNAT/MASQUERADING]
OUTPUT        - Locally sourced!!

Masquerading:
this is also similar to snat but uses when dhcp is used rather having static local ip address.

iptables -t nat -A POSTROUTING -j MASQUERADE -s 10.0.0.0/8 -d 192.168.1.0/24
now if u r pinging for 10.0.0.10 to 192.168.1.100 it appears to be pinging from 192.168.1.37 [Ip address of  the system in network 192.168.1.0]

Note:
Masquerading listen to the interface. if dhcp changes the ip of interface, it automatically changes the affect.
Masquerading uses primary interface. Not sub[duplicate] ip addresses.

iptables -t nat -R POSTROUTING 1 -p tcp -j MASQUERADE --to-ports 1024-10240
allows communication only through that port range.

Some examples of nat
iptables -t nat -R POSTROUTING 1 -p tcp -j SNAT --to-source 192.168.1.37:1024-10240 -s 10.0.0.0/8
Do same as the last rule in Masquerading. Uses only if u've a static ip. It fails when ip changes.

iptables -t nat -A POSTROUTING -p tcp -j SNAT --to-source 192.168.1.37 -d 10.0.0.10 -s 192.168.1.100
iptables -t nat -A POSTROUTING -p tcp -j SNAT --to-source 10.0.0.1 -d 192.168.1.100 -s 10.0.0.10

Destination Network Address Translation: INBOUND

DNAT - permits connection to unexposed hosts. Its exact reverse of SNAT.
Rules will be written in PREROUTING.
iptables -t nat -A PREROUTING -j DNAT -p tcp --dport 3389 -to-destination 192.168.1.101 -d 192.168.1.37 -s 10.0.0.10
this will redirect the connection to port 3389@192.168.1.37 to same port @ 192.168.1.101 from 10.0.0.10

Tuesday, March 6, 2012

make: yacc: Command not found

Advertisements

You may get this error while running make
Error:
make: yacc: Command not found

Solution:
yum install bison
yum install byacc

configure: error: C++ preprocessor "/lib/cpp" fails sanity check

Advertisements

You  may get this error while running ./configure
Error:
configure: error: C++ preprocessor "/lib/cpp" fails sanity check

Solution:
Redhat Distributions
yum install gcc gcc-cpp gcc-c++

Debian Distributions:
apt-get install gcc gcc-cpp gcc-c++

Monday, March 5, 2012

Nessus Vulnerability Scanner

Advertisements


Nessus  is the world’s most widely-deployed vulnerability and configuration assessment product. Features includes high-speed discovery, configuration auditing or misconfiguration check (e.g. open mail relay, missing patches, etc), asset profiling, sensitive data discovery, patch management integration, PCI DSS audits and vulnerability analysis. Nessus mainly check for vulnerabilities rather than rootkits by chkrootkit, rkhunter or LMD.

You can download the rpm from nessus.org

Install nessus using rpm
[root@server src]# rpm -ivh Nessus-5.0.0-es5.i386.rpm
Preparing...                ########################################### [100%]
   1:Nessus                 ########################################### [100%]
nessusd (Nessus) 5.0.0 [build R23018] for Linux
(C) 1998 - 2012 Tenable Network Security, Inc.
Processing the Nessus plugins...
[##################################################]
All plugins loaded
 - You can start nessusd by typing /sbin/service nessusd start
 - Then go to https://server.lap.work:8834/ to configure your scanner
[root@server src]#

Start the nessus service
[root@server src]# /sbin/service nessusd start
Starting Nessus services:                                  [  OK  ]
[root@server src]#

Nessus defaultly binds to 8834.
[root@server src]# netstat  -ntpla | grep 8834
tcp        0      0 0.0.0.0:8834                0.0.0.0:*                   LISTEN      5754/nessusd
tcp        0      0 :::8834                          :::*                            LISTEN      5754/nessusd
[root@server src]#

Now you can access the nessus through web interface by accessing
https://IP_address_of_the_nessus_server:8834

You have to get free or enterprise license from nessus.org. Then you can create the admin account for making scans and reports.

configuring nfs in centos linux

Advertisements

NFS is abreviation for network filesystem. It is used in linux unix platform for sharing directories between linux or unix machines over a network. It is more like folder sharing in windows systems. It was originally developed by Sun Microsystems. We will see how to install and configure nfs, How to mount a nfs share. What are the processes associated with nfs, why portpmap is needed for nfs, how to list the nfs shares of a system etc.

Advantages of NFS are:
Local systems needs only less disk space because commonly used data can be stored on a single server system and can be accessed by others over the network usin nfs.
We can mount all removable devices such as dvd, cdrom, floppy etc on one single system and made them available to other systems by sharing those via nfs.

The package name is nfs-utils. We can check whether the nfs package is installed using the following command.
[root@server ~]# rpm -qa | grep -i nfs
nfs-utils-1.0.9-33.el5
[root@server ~]#

Checking the status of the nfs service
[root@server ~]# /etc/init.d/nfs status
rpc.mountd is stopped
nfsd is stopped

Starting the nfs service
[root@server ~]# /etc/init.d/nfs start
Starting NFS services:                                     [  OK  ]
Starting NFS quotas:                                       [  OK  ]
Starting NFS daemon:                                       [  OK  ]
Starting NFS mountd:                                       [  OK  ]

NFS defaultly binds to the tcp port 2048
[root@server ~]# netstat -ntpla | grep 2049
tcp        0      0 0.0.0.0:2049                0.0.0.0:*                   LISTEN      -

You can find all the sub processes and binded ports of nfs by rpcinfo command. NFS takes the ports assigned by portmapped. Soportmapped needs tobe running for nfs to work.
[root@server ~]# rpcinfo -p
   program vers proto   port
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100011    1   udp    832  rquotad
    100011    2   udp    832  rquotad
    100011    1   tcp    835  rquotad
    100011    2   tcp    835  rquotad
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    4   udp   2049  nfs
    100021    1   udp  32773  nlockmgr
    100021    3   udp  32773  nlockmgr
    100021    4   udp  32773  nlockmgr
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100003    4   tcp   2049  nfs
    100021    1   tcp  35223  nlockmgr
    100021    3   tcp  35223  nlockmgr
    100021    4   tcp  35223  nlockmgr
    100005    1   udp    872  mountd
    100005    1   tcp    875  mountd
    100005    2   udp    872  mountd
    100005    2   tcp    875  mountd
    100005    3   udp    872  mountd
    100005    3   tcp    875  mountd
[root@server ~]#

/etc/exports is the main file for nfs. We specify the directories to be shared in this file with the information for whom it is shared and with which permissions it is shared.
* - means it is shared to all ip addresses.
ro - means read only
rw - means read write

[root@server ~]# cat /etc/exports
#Directory_path   IP_address(Permissions)
/media/CentOS *(ro)
/kick *()
[root@server ~]#

To activate all shares specified in /etc/exports run the following command
[root@server ~]# exportfs -a

If u made any changes in /etc/exports you can reload it using the following command
[root@server ~]# exportfs -r

You can list the permissions of the shares by running
[root@server ~]# exportfs -v
/media/CentOS   <world>(ro,wdelay,root_squash,no_subtree_check,anonuid=65534,anongid=65534)
/kick           <world>(ro,wdelay,root_squash,no_subtree_check,anonuid=65534,anongid=65534)

For checking the shares in a system with ip address  192.168.137.100
[root@server ~]# showmount -e 192.168.137.100
Export list for 192.168.137.100:
/kick         *
/media/CentOS *
[root@server ~]#

From a remote machine you can mount the share /media/CentOS in the machine 192.168.137.100 to /mnt as
[root@server ~]# mount 192.168.137.100:/media/CentOS /mnt
[root@server ~]# mount
*** OUTPUT TRUNCATED ***
192.168.137.100:/media/CentOS on /mnt type nfs (rw,addr=192.168.137.100)
[root@server ~]#

[root@server ~]# cat /var/lib/nfs/etab
/media/CentOS   *(ro,sync,wdelay,hide,nocrossmnt,secure,root_squash,no_all_squash,no_subtree_check,secure_locks,acl,mapping=identity,anonuid=65534,anongid=65534)
/kick   *(ro,sync,wdelay,hide,nocrossmnt,secure,root_squash,no_all_squash,no_subtree_check,secure_locks,acl,mapping=identity,anonuid=65534,anongid=65534)

Some of the important nfs files are

/var/lib/nfs/etab contains information about what filesystems should be exported to whom at the moment.
/var/lib/nfs/rmtab contains a list of which filesystems actually are mounted by certain clients at the moment.
/proc/fs/nfs/exports contains information about what filesystems are exported to actual client (individual, not subnet or whatever) at the moment.
/var/lib/nfs/xtab is the same information as /proc/fs/nfs/exports but is maintained by nfs-utils instead of directly by the kernel. It is only used if /proc isn't mounted.

[root@server ~]# cat /var/lib/nfs/rmtab
192.168.137.200:/media/CentOS:0x00000002
192.168.137.200:/kick:0x00000002
192.168.137.248:/media/CentOS:0x00000003
192.168.137.20:/media/CentOS:0x00000001
[root@server ~]#