Enable IP Forwarding in Linux

echo 1 > /proc/sys/net/ipv4/ip_forward
 #This is temporary
 #for permanent >>
 
 
#vim /etc/sysctl.conf
 
net.ipv4.ip_forward = 1
 <save it>
 
#sysctl -p or 
#service network restart 
 
Configure iptables :
-----------------  
 
# /sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE    
 
 
 
--optional---next--> 

# /sbin/iptables -A FORWARD -i eth0 -o eth1 -m state   --state RELATED,ESTABLISHED -j ACCEPT 

# /sbin/iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT 
 
 

Configure Static Route in linux

Task: Display Current Routing Table Using ip command

By using the ip command, you can setup and view static route. For example, to display current routing table you can type command:
# ip route show
Sample output:
192.168.2.0/24 dev eth1 proto kernel  scope link  src 192.168.2.1
192.168.1.0/24 dev eth0  proto kernel  scope link  src 192.168.1.2
default via 192.168.1.254 dev eth0
You can add static route using following command:
ip route add {NETWORK} via {IP} dev {DEVICE}
For example network 192.168.55.0/24 available via 192.168.1.254:
  

# ip route add 192.168.55.0/24 via 192.168.1.254 dev eth1

 Alternatively, you can use old good route command:

# route add -net 192.168.55.0 netmask 255.255.255.0 gw 192.168.1.254 dev eth1

Linux Persistence Routes

The drawback of 'ip' or 'route' command is that, when Linux reboots it will forget static routes. So store them in configuration file. Static routing describes a system that does not implement adaptive routing. In these systems routes through a data network are described by fixed paths (statically). These routes are usually entered into the router by the system administrator

Red Hat (RHEL) / CentOS / Fedora Linux Persistence Static Routing

You need to open /etc/sysconfig/network-scripts/route-eth0 file to define static routes for eth0 interface:
# cat /etc/sysconfig/network-scripts/route-eth0
Sample Output:
GATEWAY0=192.168.1.254
NETMASK0=255.255.255.0
ADDRESS0=192.168.55.0
GATEWAY1=10.164.234.112
NETMASK1= 255.255.255.240
ADDRESS1=10.164.234.132

How do I define static routing for network 10.0.0.0/8 via 10.9.38.65 router?

Open /etc/sysconfig/network-scripts/route-eth0:
# vi /etc/sysconfig/network-scripts/route-eth0
Append following line:
10.0.0.0/8 via 10.9.38.65
Save and close the file. Restart networking:
# service network restart
Verify new routing table:
# route -n

Debian / Ubuntu Linux Persistence Static Routing

Open configuration file /etc/network/interfaces
# cat /etc/network/interfaces
Output:
auto eth0
iface eth0 inet static
address 192.168.1.2
netmask 255.255.255.0
gateway 192.168.1.254
up route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.2.1
down route del -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.2.1
Debian / Ubuntu Linux static routing for two interfaces:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
        address 10.9.38.76
        netmask 255.255.255.240
        network 10.9.38.64
        broadcast 10.9.38.79
 ### static routing ###
        post-up route add -net 10.0.0.0 netmask 255.0.0.0 gw 10.9.38.65
        pre-down route del -net 10.0.0.0 netmask 255.0.0.0 gw 10.9.38.65
auto eth1
iface eth1 inet static
        address 204.186.149.140
        netmask 255.255.255.240
        network 204.186.149.128
        broadcast 204.186.149.143
        gateway 204.186.149.129
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 10.0.80.11 10.0.80.12
        dns-search nixcraft.in

Securing GRUB

1. Boot to the single usermode (edit kernel menu by adding 1 or Single and boot) ##Optional / if root     password lost##


2. cd /sbin/                                      ##changing directory to /sbin and do ls -ltr for grub-md5-crypt
3. ./grub-md5-crypt
    Password : ***********
    @#$345dfdsdfre#$%@$%dsfe

paste it beneath timeout section in grub.conf (/etc/grub.conf  or /boot/grub/grub.conf)

password --md5  @#$345dfdsdfre#$%@$%dsfe


-------------------------------------------------------------------


# grub-crypt Password: GrbPwd4SysAd$
Retype password: GrbPwd4SysAd$  
^9^32kwzzX./3WISQ0C
#### 
#Just copy the output of the grub-crypt command, 
#and paste it after the “–encrypted” 
#argument in the password entry.
#### 
$ cat /etc/grub.conf
default=0
timeout=15
password --encrypted ^9^32kwzzX./3WISQ0C
##done
 
By default, the grub-crypt command encrypts the password using SHA-512 algorithm. You can also encrypt the password either using SHA-256 or MD5 alrogithms as shown below.
# grub-crypt --sha-256
# grub-crypt --md5
 You can also use md5crypt to encrypt the password. In that case, you should use
 “password --md5 encrypted-password”  
in your grub.conf file.

Port Forwarding

Port Forwarding

SSH tunnels can be created in several ways using different kinds of port forwarding
mechanisms. Ports can be forwarded in three ways.
  1. Local port forwarding
  2. Remote port forwarding
  3. Dynamic port forwarding  

Tunnelling with Local port forwarding

Let’s say that yahoo.com is being blocked using a proxy filter in the University.
(For the sake of this example. :) . Cannot think any valid reason why yahoo would be blocked). A SSH tunnel can be used to bypass this restriction. Let’s name my machine at the university as ‘work’ and my home machine as ‘home’. ‘home’ needs to have a public IP for this to work. And I am running a SSH server on my home machine. Following diagram illustrates the scenario.
To create the SSH tunnel execute following from ‘work’ machine.
1
ssh -L 9001:yahoo.com:80 home
The ‘L’ switch indicates that a local port forward is need to be created. The switch syntax is as follows.
1
-L <local-port-to-listen>:<remote-host>:<remote-port>
Now the SSH client at ‘work’ will connect to SSH server running at ‘home’ (usually running at port 22) binding port 9001 of ‘work’ to listen for local requests thus creating a SSH tunnel between ‘home’ and ’work’. At the ‘home’ end it will create a connection to ‘yahoo.com’ at port 80. So ‘work’ doesn’t need to know how to connect to yahoo.com. Only ‘home’ needs to worry about that. The channel between ‘work’ and ‘home’ will be encrypted while the connection between ‘home’ and ‘yahoo.com’ will be unencrypted.
Now it is possible to browse yahoo.com by visiting http://localhost:9001 in the web browser at ‘work’ computer. The ‘home’ computer will act as a gateway which would accept requests from ‘work’ machine and fetch data and tunnelling it back. So the syntax of the full command would be as follows.
ssh -L <local-port-to-listen>:<remote-host>:<remote-port> <gateway>

The image below describes the scenario.
Here the ‘host’ to ‘yahoo.com’ connection is only made when browser makes the
request not at the tunnel setup time.
It is also possible to specify a port in the ‘home’ computer itself instead of
connecting to an external host. This is useful if I were to set up a VNC session
between ‘work’ and ‘home’. Then the command line would be as follows.
1
ssh -L 5900:localhost:5900 home (Executed from 'work')
So here what does localhost refer to? Is it the ‘work’ since the command line is executed from ‘work’? Turns out that it is not. As explained earlier is relative to the gateway (‘home’ in this case) , not the machine from where the tunnel is initiated. So this will make a connection to port 5900 of the ‘home’ computer where the VNC client would be listening in.
The created tunnel can be used to transfer all kinds of data not limited to web browsing sessions. We can also tunnel SSH sessions from this as well. Let’s assume there is another computer (‘banned’) to which we need to SSH from within University but the SSH access is being blocked. It is possible to tunnel a SSH session to this host using a local port forward. The setup would look like this.
As can be seen now the transferred data between ‘work’ and ‘banned’ are encrypted end to end. For this we need to create a local port forward as follows.
1
ssh -L 9001:banned:22 home
Now we need to create a SSH session to local port 9001 from where the session
will get tunneled to ‘banned’ via ‘home’ computer.
1
ssh -p 9001 localhost
With that let’s move on to next type of SSH tunnelling method, reverse tunnelling.

Reverse Tunnelling with remote port forwarding

Let’s say it is required to connect to an internal university website from home.
The university firewall is blocking all incoming traffic. How can we connect from ‘home’ to internal network so that we can browse the internal site? A VPN setup is a good candidate here. However for this example let’s assume we don’t have this facility. Enter SSH reverse tunnelling..
As in the earlier case we will initiate the tunnel from ‘work’ computer behind the firewall. This is possible since only incoming traffic is blocking and outgoing traffic is allowed. However instead of the earlier case the client will now be at the ‘home’ computer. Instead of -L option we now define -R which specifies
a reverse tunnel need to be created.
1
ssh -R 9001:intra-site.com:80 home (Executed from 'work')
Once executed the SSH client at ‘work’ will connect to SSH server running at home creating a SSH channel. Then the server will bind port 9001 on ‘home’ machine to listen for incoming requests which would subsequently be routed through the created SSH channel between ‘home’ and ‘work’. Now it’s possible to browse the internal site
by visiting http://localhost:9001 in ‘home’ web browser. The ‘work’ will then create a connection to intra-site and relay back the response to ‘home’ via the created SSH channel.
As nice all of these would be still you need to create another tunnel if you need to connect to another site in both cases. Wouldn’t it be nice if it is possible to proxy traffic to any site using the SSH channel created? That’s what dynamic port forwarding is all about.

Dynamic Port Forwarding

Dynamic port forwarding allows to configure one local port for tunnelling data to all remote destinations. However to utilize this the client application connecting to local port should send their traffic using the SOCKS protocol. At the client side of the tunnel a SOCKS proxy would be created and the application (eg. browser) uses the SOCKS protocol to specify where the traffic should be sent when it leaves the other end of the ssh tunnel.
1
ssh -D 9001 home (Executed from 'work')
Here SSH will create a SOCKS proxy listening in for connections at local port
9001 and upon receiving a request would route the traffic via SSH channel
created between ‘work’ and ‘home’. For this it is required to configure the
browser to point to the SOCKS proxy at port 9001 at localhost.

Screen Command Examples to Manage Linux Terminals

Install:

# yum install screen (On RedHat based Systems)
 

Start screen for the first time

Just type screen at the command prompt. Then the screen will show with interface exactly as the command prompt.
pungki@mint ~ $ screen

Show screen parameter

When you enter the screen, you can do all your work as you are in the normal CLI environment. But since the screen is an application, so it have command or parameters.
Type “Ctrl-A” and “?” without quotes. Then you will see all commands or parameters on screen.

                                                           
To get out of the help screen, you can press “space-bar” button or “Enter“. (Please note that all shortcuts which use “Ctrl-A” is done without quotes).

Detach the screen

One of the advantages of screen that is you can detach it. Then, you can restore it without losing anything you have done on the screen. Here’s the sample scenario:
You are in the middle of SSH-on your server. Let’s say that you are downloading 400MB patch for your system using wget command.
The download process is estimated to take 2 hours long. If you disconnect the SSH session, or suddenly the connection lost by accident, then the download process will stop. You have to start from the beginning again. To avoid that, we can use screen and detach it.
Take a look at this command. First, you have to enter the screen.
pungki@mint ~ $ screen
Then you can do the download process. For examples on my Linux Mint, I am upgrading my dpkg package using apt-get command.
pungki@mint ~ $ sudo apt-get install dpkg
Sample Output
Reading package lists... Done
Building dependency tree      
Reading state information... Done
The following packages will be upgraded:
  dpkg
1 upgraded, 0 newly installed, 0 to remove and 1146 not upgraded.
Need to get 2,583 kB of archives.
After this operation, 127 kB of additional disk space will be used.
Get:1 http://debian.linuxmint.com/latest/ testing/main dpkg i386 1.16.10 [2,583 kB]
47% [1 dpkg 1,625 kB/2,583 kB 47%]                                        14,7 kB/s
While downloading in progress, you can press “Ctrl-A” and “d“. You will not see anything when you press those buttons. The output will be like this:
[detached from 5561.pts-0.mint]
pungki@mint ~ $

Re-attach the screen

After you detach the screen, let say you are disconnecting your SSH session and going home. In your home, you start to SSH again to your server and you want to see the progress of your download process. To do that, you need to restore the screen. You can run this command:
pungki@mint ~ $ screen -r
And you will see that the process you left is still running.
When you have more than 1 screen session, you need to type the screen session ID. Use screen -ls to see how many screen are available.
pungki@mint ~ $ screen -ls
Sample Output
pungki@mint ~ $ screen -ls
There are screens on:
        7849.pts-0.mint (10/06/2013 01:50:45 PM)        (Detached)
        5561.pts-0.mint (10/06/2013 11:12:05 AM)        (Detached)
2 Sockets in /var/run/screen/S-pungki
If you want to restore screen 7849.pts-0.mint, then type this command.
pungki@mint ~ $ screen -r 7849

Using Multiple Screen

When you need more than 1 screen to do your job, is it possible? Yes it is. You can run multiple screen window at the same time. There are 2 (two) ways to do it.
First, you can detach the first screen and the run another screen on the real terminal. Second, you do nested screen.

Switching between screens

When you do nested screen, you can switch between screen using command “Ctrl-A” and “n“. It will be move to the next screen. When you need to go to the previous screen, just press “Ctrl-A” and “p“.
To create a new screen window, just press “Ctrl-A” and “c“.

Logging whatever you do

Sometimes it is important to record what you have done while you are in the console. Let say you are a Linux Administrator who manage a lot of Linux servers.
With this screen logging, you don’t need to write down every single command that you have done. To activate screen logging function, just press “Ctrl-A” and “H“. (Please be careful, we use capital ‘H’ letter. Using non capital ‘h’, will only create a screenshot of screen in another file named hardcopy).
At the bottom left of the screen, there will be a notification that tells you like: Creating logfile “screenlog.0“. You will find screenlog.0 file in your home directory.
This feature will append everything you do while you are in the screen window. To close screen to log running activity, press “Ctrl-A” and “H” again.
Another way to activate logging feature, you can add the parameter “-L” when the first time running screen. The command will be like this.
pungki@mint ~ $ screen -L

Lock screen

Screen also have shortcut to lock the screen. You can press “Ctrl-A” and “x” shortcut to lock the screen. This is handy if you want to lock your screen quickly. Here’s a sample output of lock screen after you press the shortcut.
Screen used by Pungki Arianto  on mint.
Password:
You can use your Linux password to unlock it.

Add password to lock screen

For security reason, you may want to put the password to your screen session. A Password will be asked whenever you want to re-attach the screen. This password is different with Lock Screen mechanism above.
To make your screen password protected, you can edit “$HOME/.screenrc” file. If the file doesn’t exist, you can create it manually. The syntax will be like this.
password crypt_password
To create “crypt_password” above, you can use “mkpasswd” command on Linux. Here’s the command with password “pungki123“.
pungki@mint ~ $ mkpasswd pungki123
l2BIBzvIeQNOs
mkpasswd will generate a hash password as shown above. Once you get the hash password, you can copy it into your “.screenrc” file and save it. So the “.screenrc” file will be like this.
password l2BIBzvIeQNOs
Next time you run screen and detach it, password will be asked when you try to re-attach it, as shown below:
pungki@mint ~ $ screen -r 5741
Screen password:
Type your password, which is “pungki123” and the screen will re-attach again.
After you implement this screen password and you press “Ctrl-A” and “x” , then the output will be like this.
Screen used by Pungki Arianto  on mint.
Password:
Screen password:
A Password will be asked to you twice. First password is your Linux password, and the second password is the password that you put in your .screenrc file.

Leaving Screen

There are 2 (two) ways to leaving the screen. First, we are using “Ctrl-A” and “d” to detach the screen. Second, we can use the exit command to terminating screen. You also can use “Ctrl-A” and “K” to kill the screen.
That’s some of screen usage on daily basis. There are still a lot of features inside the screen command. You may see screen man page for more detail.


 

Linux Demilitarized Zone (DMZ)

Linux Demilitarized Zone (DMZ) Ethernet Interface Requirements and Configuration


Q. Can you tell me more about Linux Demilitarized Zone and Ethernet Interface Card Requirements for typical DMZ implementation? How can a rule be set to route traffic to certain machines on a DMZ for HTTP or SMTP?
A. Demilitarized zone, used to secure an internal network from external access. You can use Linux firewall to create DMZ easily. There are many different ways to design a network with a DMZ. The basic method is to use a single Linux firewall with 3 Ethernet cards. The following simple example discusses DMZ setup and forwarding public traffic to internal servers.

Sample Example DMZ Setup

Consider the following DMZ host with 3 NIC:
[a] eth0 with 192.168.1.1 private IP address - Internal LAN ~ Desktop system
[b] eth1 with 202.54.1.1 public IP address - WAN connected to ISP router
[c] eth2 with 192.168.2.1 private IP address - DMZ connected to Mail / Web / DNS and other private servers

(Fig 01: A typical Linux based DMZ setup [ Image modified from Wikipedia article] )

Routing traffic between public and DMZ server

To set a rule for routing all incoming SMTP requests to a dedicated Mail server at IP address 192.168.2.2 and port 25, network address translation (NAT) calls a PREROUTING table to forward the packets to the proper destination.
This can be done with appropriate IPTABLES firewall rule to route traffic between LAN to DMZ and public interface to DMZ. For example, all incoming mail traffic from internet (202.54.1.1) can be send to DMZ mail server (192.168.2.2) with the following iptables prerouting rule (assuming default DROP all firewall policy):
========================================================================
### end init firewall .. Start DMZ stuff ####
# forward traffic between DMZ and LAN
iptables -A FORWARD -i eth0 -o eth2 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth2 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# forward traffic between DMZ and WAN servers SMTP, Mail etc
iptables -A FORWARD -i eth2 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth2 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
# Route incoming SMTP (port 25 ) traffic to DMZ server 192.168.2.2
iptables -t nat -A PREROUTING -p tcp -i eth1 -d 202.54.1.1 --dport 25 -j DNAT --to-destination 192.168.2.2
# Route incoming HTTP (port 80 ) traffic to DMZ server load balancer IP 192.168.2.3
iptables -t nat -A PREROUTING -p tcp -i eth1 -d 202.54.1.1 --dport 80 -j DNAT --to-destination 192.168.2.3
# Route incoming HTTPS (port 443 ) traffic to DMZ server reverse load balancer IP 192.168.2.4
iptables -t nat -A PREROUTING -p tcp -i eth1 -d 202.54.1.1 --dport 443 -j DNAT --to-destination 192.168.2.4
### End DMZ .. Add other rules ###
 
==================================================================================
 
Where,
  • -i eth1 : Wan network interface
  • -d 202.54.1.1 : Wan public IP address
  • --dport 25 : SMTP Traffic
  • -j DNAT : DNAT target used set the destination address of the packet with --to-destination
  • --to-destination 192.168.2.2: Mail server ip address (private IP)

Multi port redirection

You can also use multiport iptables module to matches a set of source or destination ports. Up to 15 ports can be specified. For example, route incoming HTTP (port 80 ) and HTTPS ( port 443) traffic to WAN server load balancer IP 192.168.2.3:

iptables -t nat -A PREROUTING -p tcp -i eth1 -d 202.54.1.1 -m multiport --dport 80,443 -j DNAT --to-destination 192.168.2.3

Pitfalls

Above design has few pitfalls:
  1. Single point of failure - The firewall becomes a single point of failure for the network.
  2. Hardware - The firewall Host must be able to handle all of the traffic going to the DMZ as well as the internal network.

Linux / BSD Firewall Distros

If you find above discussion little hard to digest, I suggest getting a Linux / BSD distribution which aims to provide a simple-to-manage firewall appliance based on PC hardware to setup DMZ and gateways:

 Ref:http://www.cyberciti.biz/faq/linux-demilitarized-zone-howto/

Linux Routing Real world example

Here is the link to the document ..dual isp link and traffic splitting environment


For first link you need to have 4 shared a/c :-
advanced routing.docx   <<first link


advanced routing.docx Link 2   << second link


Scenario :









Automate Rsync CRON SSH with keychain really works !!

Tested on rhel 6.X and centos 6.X and on production.
First install keychain
Auto mate keychain ssh rsync
[root@backupsrv ~]# cat .bash_profile
# .bash_profile
##script start keychain
/usr/bin/keychain $HOME/.ssh/id_rsa
source $HOME/.keychain/$HOSTNAME-sh
##keychain stop
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin

export PATH
[root@backupsrv ~]# crontab -l
SHELL=/bin/bash
BASH_ENV=~/.bashrc
55 11,17 * * *  /backup/bc.sh >> /backup.log  2>&1


43 11,17 * * *  /cloudmysql/backupmysql.sh >> /rsyncmysql.log 2>&1


Backup script
[root@backupsrv backup]# cat backup.sh
#!/bin/bash
source  /root/.keychain/$HOSTNAME-sh
/usr/bin/rsync -avz --progress -e "/usr/bin/ssh -i /root/.ssh/id_rsa" root@192.168.0.101:/var/www/owncloud1/ /backup/owncloud1/
mysql backup script
[root@backupsrv cloudmysql]# cat mysqlbackup.sh
#!/bin/bash
mysqldump  -u  root  -pyourP@ssword cloud | gzip > /mysqldump/cloud_db_`date '+%m-%d-%Y'`.sql.gz

Linux Network Load Balancer For Multiple ISP Links

This article explains how to configure a Redhat/CentOS (and many other Linux distributions) Linux server as a load balancer. For this example, there are two routers each with a different ISP although they could be the same ISP.
This was tested on a CentOS 6.3 64bit server.
In the script below, the load balancer has three interfaces: Eth0 is on the inside while Eth1 and Eth2 are connected to the routers.
Server addresses:
Eth0 = 192.168.0.10 (connected to inside network)
Eth1 = 192.168.1.10 (connected to router1/ISP1)
Eth2 = 192.168.2.10 (connected to router2/ISP2)
Router addresses:
Router1 = 192.168.1.1
Router2 = 192.168.2.1
Create a script file called “/usr/bin/lb.sh” with the following contents:
#!/bin/bash

# By Andrew Galdes, AGIX, 4 April 2013
# Remember to turn off (or customise) SELinux and add the ROUTER1/2 in
# the "/etc/iproute2/rt_tables" file.
# Do NAT on this server.

service network restart

ip route flush cache

ip route add 192.168.1.0/24 dev eth2 src 192.168.1.10 table ROUTER1
ip route add default via 192.168.1.1 table ROUTER1

ip route add 192.168.2.0/24 dev eth1 src 192.168.2.10 table ROUTER2
ip route add default via 192.168.2.1 table ROUTER2

ip rule add from 192.168.1.10 table ROUTER1
ip rule add from 192.168.2.10 table ROUTER2

# the following command is one line:
ip route append default scope global nexthop via 192.168.1.1 dev eth1 weight 1 nexthop via 192.168.2.1 dev eth2 weight 1

route del default gw 192.168.1.1
route del default gw 192.168.2.1

ip route
Make the script executable:
chmod 755 /usr/bin/lb.sh
Add the script to the boot process:
vi /etc/rc.local
Use the following command to make sure the firewall is set correct.
system-configure-firewall
The firewall should trust the Eth+ devices. It should masquerade the Eth+ devices.
Add the following to the end of the “/etc/iproute2/rt_tables” file:
1 ROUTER1
2 ROUTER2
Consider turning off SELinux as follows or make considered changes:
setenforce 0
Set it permanently in the “/etc/sysconfig/selinux” file if you like.
Make sure to configure static routes on the routers so they know their way back to the inside network.
 From >>>
http://agix.com.au/blog/?p=3173