Simple IPTABLES rules

List all iptables rules to display rules with line numbers

iptables -L --line-numbers

IPTABLES rule to allow all INCOMING SSH request on eth0 interface:

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

IPTABLES rule to allow all OUTGOING SSH request on eth0 interface:

iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
{Here we allow NEW & ESTABLISHED state on the OUTPUT chain and only ESTABLISHED state on the INPUT chain}

Multiport usage to allow more than one ports via single rule:

iptables -A INPUT -i eth0 -p tcp -m multiport --dport 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sport 22,80,443 -m state --state ESTABLISHED -j ACCEPT

Allow PING from External Network to Internal Network:

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

Allow PING from Internal Network to External Network:

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

Allow Loopback Access:

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

Allow Internal Network to External Network

eth0 => Internal Network 
eth1 => External Network (Internet)

iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

IPTABLES – Port Forwarding (Routes all traffic that comes to port 422 to port 22)

iptables -t nat -A PREROUTING -p tcp -d 192.168.10.14 --dport 422 -j DNAT --to 192.168.10.14:22
Now, you have to explicitly allow incoming connection on port 422 as follows:
iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT

IPTABLES – Port Forwarding (Routes all traffic that comes to port 80 to SQUID port 3128)

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3128
Advertisements

If condition – Shell script options

The following are the various options for checking the existence of a file via shell script

[ -a FILE ]	True if FILE exists.
[ -b FILE ]	True if FILE exists and is a block-special file.
[ -c FILE ]	True if FILE exists and is a character-special file.
[ -d FILE ]	True if FILE exists and is a directory.
[ -e FILE ]	True if FILE exists.
[ -f FILE ]	True if FILE exists and is a regular file.
[ -g FILE ]	True if FILE exists and its SGID bit is set.
[ -h FILE ]	True if FILE exists and is a symbolic link.
[ -k FILE ]	True if FILE exists and its sticky bit is set.
[ -p FILE ]	True if FILE exists and is a named pipe (FIFO).
[ -r FILE ]	True if FILE exists and is readable.
[ -s FILE ]	True if FILE exists and has a size greater than zero.
[ -t FD ]	True if file descriptor FD is open and refers to a terminal.
[ -u FILE ]	True if FILE exists and its SUID (set user ID) bit is set.
[ -w FILE ]	True if FILE exists and is writable.
[ -x FILE ]	True if FILE exists and is executable.
[ -O FILE ]	True if FILE exists and is owned by the effective user ID.
[ -G FILE ]	True if FILE exists and is owned by the effective group ID.
[ -L FILE ]	True if FILE exists and is a symbolic link.
[ -N FILE ]	True if FILE exists and has been modified since it was last read.
[ -S FILE ]	True if FILE exists and is a socket.
[ FILE1 -nt FILE2 ]	True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
[ FILE1 -ot FILE2 ]	True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not.
[ FILE1 -ef FILE2 ]	True if FILE1 and FILE2 refer to the same device and inode numbers.
[ -o OPTIONNAME ]	True if shell option "OPTIONNAME" is enabled.
[ -z STRING ]	True of the length if "STRING" is zero.
[ -n STRING ] or [ STRING ]	True if the length of "STRING" is non-zero.
[ STRING1 == STRING2 ]	True if the strings are equal. "=" may be used instead of "==" for strict POSIX compliance.
[ STRING1 != STRING2 ]	True if the strings are not equal.
[ STRING1  STRING2 ]	True if "STRING1" sorts after "STRING2" lexicographically in the current locale.
[ ARG1 OP ARG2 ]	"OP" is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if "ARG1" is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to "ARG2", respectively. "ARG1" and "ARG2" are integers.
Expressions may be combined using the following operators, listed in decreasing order of precedence:

Combining expressions

Operation	Effect
[ ! EXPR ]	True if EXPR is false.
[ ( EXPR ) ]	Returns the value of EXPR. This may be used to override the normal precedence of operators.
[ EXPR1 -a EXPR2 ]	True if both EXPR1 and EXPR2 are true.
[ EXPR1 -o EXPR2 ]	True if either EXPR1 or EXPR2 is true.

Load Balancing

What is Load Balancing?

Load Balancing is taking the overall hosting burden and spreading across multiple servers so at any given time, a single device or hardware is not overwhelmed. Load balancing also offers a level of redundancy. It allows you to have a scheduled maintenance work, and if a server should fail, there is already one there to take over that burden. It also allows end users to have a seamless, uninterrupted end user experience.

Who should use Load Balancing?

Medium to Large Businesses
eCommerce Businesses
Any mission critical application

Basically any business with the multi-service stratergy, which can’t afford a moment of downtime should consider implementing load balancing.

Few info on Server Clustering

What is Server Clustering?

A server clustering is a group of linked servers, working together as a single solution. They can be programmed to balance the overall processing load of the hosting solution or be designated to handle specific individual requirement within the whole solution.

Why do we need Clustering?

If you have a multi faceted or large solution, clustering is ideal for meeting these large solutions with high demands.

Enhanced Performance: By harnessing the power of several servers, speed and efficiency can be dramatically improved. Databases, which allows for vast data storage and utilization which is easily scalable. Furthermore, a cluster server is ideal for a busy e-commerce site. They can deliver faster and more reliable solution with less downtime. Also, they can be customized to deliver unique experience for each visitor.

What does a good provider offer?

First and foremost, the latest technology. This simply means increasing your clustered solution quickly without going offline or disrupting your end user experience and finally 24×7 expert support and guaranteed excellent response times.

Disaster Recovery Planning

What is Disaster Recovery Planning?

Disaster Recovery Planning is a technology-based process that ensures client’s solutions are returned to normal performance as soon as possible after a major event. It is a strategy to keep vital data safe and accessible even in the worst of situations. It also ensures applications stay online continuously to prevent the loss of business. Also, it ensures a continuity of service to the client’s customers so your good reputation remains intact.

Who should consider a Disaster Recovery Plan?

In reality Disaster Recovery Planning should be important for every business with an online presence. It’s vital for mission critical applications and crucial to any online business that stores client information and user data.

What does a good provider include in their Disaster Recovery Plan?

• Managed backups:
Expert managed backups of clients’ data are set at regular intervals, so in the event of disaster files and applications can be immediately restored.

• Offsite data backup:
For organisations storing vital or sensitive data offsite data backup adds a further level of security. Should disaster affect the primary storage location, data is therefore safe and accessible at all times in a secondary location.

• A Business Continuity Platform:
This plug-in-and-go service ensures that even in the most trying server situations, clients remain up, running and ready to do business.

Info on Backups – Rsnapshot configuration

Archive:

An archive is a complete mirror of a set of files at a certain point in time. An archive of a site includes all of the data in that site at the time the archive is created; because archives store a relatively large amount of information, they are often “compressed” into a single file (called a zip file) to reduce their total file size and make them faster to upload or download.

Onsite and Offsite Backups:

Onsite backups  is a way of backing up files/folders or even the entire server to a destination medium which is in the same physical vicinity as that of the source. For eg; a USB drive, an external hard drive etc.

Offsite backup backs up files to an entirely different physical location. For eg: Cloud backups. The best way is to have both Onsite and Offsite backup configured for your servers for ultimate data protection. Offsite protection should be configured so that in case of any physical disaster like fire, or earth quake, the data remains safe since it is in some other part of the planet. So, as a Disaster Recovery method, we should always configure Offsite backups. On the other hand, Onsite backup is required for quick recovery of data in case any files or database gets corrupted.

There are mainly two types of backups.

1. Image Backup

2. Snapshot Backup.

In an Image Backup, the volume being backed up won’t be available for other application.  The backup archive client is the only process with access to the volume. So, we can consider Image Backup as an Offline Backup. The main disadvantage of Image backup is we have to make the volume offline or lock it down to start the backup. Also, it does not provide a per file based backup.

In a Snapshot Backup, the file system or raw logical volume stays active and will be available for read and write operations during the backup. So, this is considered as an Online Backup. The main disadvantage of Snapshot backup is that it requires additional software to be installed.

Snapshot backup records changes to files at a certain point in time. Once the Snapshot Backups is enabled, it takes a snapshot of your web site files every few hours. Each snapshot records only changes that have been made to your site files; it does not take a snapshot of your entire web site again. So, it acts like an incremental backup. Because snapshots are taken every few hours, say four hours, changes you make to your site will not be recorded immediately, but rather at the end of the four hour window. In other words, a file must exist  for four hours to guarantee its inclusion in a snapshot. Snapshot backups also “roll over” after few weeks (as configured), which means that you cannot use this utility to restore a version of a file that’s beyond those few weeks.

Rsnapshot Backup:

I have been using rSnapshot backup utility to configure backups on Linux servers. This utility uses both hard links and rsync combinations to manage full and incremental backups. Rsnapshot backup is very easy to configure and once it’s setup and configured, it will take care of deleting and rotating the old backups. So less user intervention is required once it’s setup. It also uses very less disk space. The disk space required is just a little more than the space of one full backup, plus incremental. This comes as a criteria when your drive is lacking enough free space to accommodate 3 copies of backup.

Rsnapshot Installation:

Prerequisites: You require the following package installed on your Linux distro:

1. Perl

2. rsync

Download the latest source tar ball from: http://www.rsnapshot.org/downloads.html

Now, untar the source code package.

# tar xzvf rsnapshot-1.3.1.tar.gz

Change to the source directory and run the configure script:

# cd rsnapshot-1.3.1/

# ./configure –sysconfdir=/etc

# make install

Now rsnapshot is installed under /usr/local, with the config file in /etc

Rsnapshot Configuration – Specify the destination media / parition:

The major configuration changes to be done is to specify the backup destination / media and to specify what all to backup every few hours.

A sample copy of the rsnapshot config file is provided with the package. We need to just copy the file.
# cp /etc/rsnapshot.conf.default /etc/rsnapshot.conf

# vi /etc/rsnapshot.conf

The main directive that requires changes are as follows:

snapshot_root   /backupdrive/.snapshots/

Here the backup destination is a different partition /backupdrive and ‘.snapshot’ is the folder where all the backups are stored.

Now, modify the path to the various programs like rm for removing files, rsync, ssh etc. Usually, you won’t need to update anything here unless you have customized the path to your various utilities.

By default backup interval is set as follows:

interval hourly 6
interval daily 7
interval weekly 4

This means that rsnapshot is taken every four hours, or six times a day (these are the hourly intervals), 7 times a week, 4 times a month. Thus it covers the whole month (4 weeks). You don’t need to update anything here unless you want any changes in hourly backups.

Now, configure the backup points:

backup /home/soj/ localhost/
backup /etc/ localhost/
backup /usr/local/ localhost/

Here in the first line, “backup” parameter says what to backup, followed by “/home/soj”, which means the home folder of user “soj” should be backed up to a destination (third column) which is relative to the snapshot_root; in our case “/backupdrive/.snapshots/”
NOTE: In the above backup points is that each column is separated by tab delimiter and not spaces.

You can now test the snapshot configuration with the following command:

# rsnapshot configtest
Syntax OK

You can verify hourly backup configuration  as  follows:

# rsnapshot -t  hourly

The above command simulates an hourly backup and prints out the command that will be executes once it’s run for real.

Now, you can edit the cron job to automate the rsnapshot process:

# crontab -e

Add the following entries,

0 */4 * * * /usr/local/bin/rsnapshot hourly
30 23 * * * /usr/local/bin/rsnapshot daily

Cron should be timed in a way that the hourly backup is finished before performing the daily backup.

Also, rsnapshot can be used to perform remote backups. Check the configuration file for more information on it.

This is a video I have created when I setup a new partition for backup and then configured rsnapshot to start backing up files and folders every four hours.

Updating Password for MySQL server

These are some of the things that we have to keep in mine when installing MySQL and updating passwords for the root user.

First check if MySQL is installed or not.

rpm -qa | grep mysql
yum search mysql

Install MySQL Server:

yum install mysql
yum install mysql-server

Query list the installed package to check the contents:

rpm -ql mysql-server

Some of the important files to note are the data directory, log files and PID directory.

Data Directory – /var/lib/mysql
Log File – /var/log/mysqld.log
PID Directory – /var/run/mysql

You can query list the MySQL client package to enumerate the common user binaries

rpm -ql mysql

/usr/bin/mysqladmin
/usr/bin/mysqlcheck
/usr/bin/mysqldump
/usr/bin/mysqlimport

Also, worth checking the MySQL libs directory for system wide configuration file (/etc/my.cnf) which is read by both Client and MySQL server.

rpm -ql mysql-libs

vi /etc/my.cnf

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

:wq!

Now, enable MySQL service at startup as follows:

chkconfig –list mysqld
chkconfig mysqld on
service mysqld start

By default mysql maintains a root password which is UNDEFINED. So, you gotta change the password.

Before changing the password, you can connect to mysql server by typing ‘mysql’ at the command prompt.

[root@linuxgenius soj]# mysql

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
3 rows in set (0.10 sec)

mysql> select user,host,password from mysql.user;
+------+--------------------+-------------------------------------------+
| user | host               | password                                  |
+------+--------------------+-------------------------------------------+
| root | localhost          |                                           |
| root | linuxgenius.gemini |                                           |
| root | 127.0.0.1          |                                           |
|      | localhost          |                                           |
|      | linuxgenius.gemini |                                           |
+------+--------------------+-------------------------------------------+
5 rows in set (0.00 sec)

From the above table, you can see by default there are 3 root users without any password and 2 anonymous users.

MySQL represents users as user@host. So, in the first instance, we change password for the root user @ localhost and in the second instance, we change password for root user @ FQDN (root@linuxgenius.gemini).

There are two ways to change MySQL user password.

First option is using mysqladmin tool from the command line as follows:

/usr/bin/mysqladmin -u root password ‘word12’
/usr/bin/mysqladmin -u root -h linuxgenius.gemini password ‘word12’

mysql> select user,host,password from mysql.user;
+------+--------------------+-------------------------------------------+
| user | host               | password                                  |
+------+--------------------+-------------------------------------------+
| root | localhost          | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
| root | linuxgenius.gemini |                                           |
| root | 127.0.0.1          |                                           |
|      | localhost          |                                           |
|      | linuxgenius.gemini |                                           |
+------+--------------------+-------------------------------------------+
5 rows in set (0.00 sec)

From the above table, you can see that password is set only for root@localhost, but you will still be able to connect without any password for the 2nd root user as follows:

[root@linuxgenius soj]# mysql -u root -h linuxgenius.gemini

As a security measure, you have to update the password for all hosts.

Second way to change the password is by connecting to MySQL server.

Once you are in the MySQL prompt, issue the following command to update the password

mysql> set password for ‘root’@’linuxgenius.gemini’ = password(‘word12’);

mysql> select user,host,password from mysql.user;
+------+--------------------+-------------------------------------------+
| user | host               | password                                  |
+------+--------------------+-------------------------------------------+
| root | localhost          | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
| root | linuxgenius.gemini | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
| root | 127.0.0.1          |                                           |
|      | localhost          |                                           |
|      | linuxgenius.gemini |                                           |
+------+--------------------+-------------------------------------------+
5 rows in set (0.00 sec)

You can see that password is now updated for the 2nd root user. Update password for the 3rd root user or you can delete that user since we have already set the password for localhost.

Make sure you issue the command “flush privileges” whenever you change passwords so that the changed password is updated instantly.

Also, the two anonymous login should be deleted as follows:

mysql> delete from mysql.user where user = '';

Query OK, 2 rows affected (0.25 sec)

mysql> select user,host,password from mysql.user;
+------+--------------------+-------------------------------------------+
| user | host               | password                                  |
+------+--------------------+-------------------------------------------+
| root | localhost          | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
| root | linuxgenius.gemini | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
| root | 127.0.0.1          | *4E35FA4ABB37E8A43AD4C3C94CDA57ADD4B67B46 |
+------+--------------------+-------------------------------------------+
3 rows in set (0.00 sec)

Also, note that MySQL reads a hierarchy of configuration files upon invocation:

/etc/my.cnf – System wide file
$HOME/.my.cnf – User wide file
CLI – Command Line Interface

I’ll write a separate article later on MySQL tools and managing MySQL server.