Showing posts with label Linux Commands. Show all posts
Showing posts with label Linux Commands. Show all posts

Tuesday, January 18, 2011

Slow SSH connection in Ubuntu

There is always a problem with Ubuntu’s i.e. very slow SSH connection. For some reasons, there’re some options are being enabled by default and causing either the incoming or outgoing SSH connection very slow or hanged in a range from 15 to 60 seconds.

There’re two major contributors which I know of, than can causing the abovementioned problem.

[1] GSSAPIAuthentication

GSSAPI is a ITEF standard for doing strong encrypted authentication in network based applications. OPENssh uses this API and the underlying kerberos 5 code to provide a alternative means of authentication other than ssh_keys.

For some reasons, this feature is enabled by default since Ubuntu Fiesty, you can disable them globally affecting all users in the /etc/ssh/ssh_config

# SendEnv LANG LC_*
# HashKnownHosts yes
# GSSAPIAuthentication yes
# GSSAPIDelegateCredentials no

[2] Slow or Broken DNS Lookup

Everytime when you log into the OpenSSH server, it would actually perform a reverse-lookup on your IP address. If the DNS lookup timed out, then you’ll having big time of delaying as typically OpenSSH will perform 3 times trying.

All you need to do is add the following line in /etc/ssh/ssh_config

sudo echo "UseDNS no" >> /etc/ssh/sshd_config

Remember to restart the ssh services upon change.

Sunday, April 25, 2010

How to : Quagga Routing Suite

Quagga, a routing software that run on Linux based on Zebra router, the last Zebra release was 2005. Quagga is able to act as your open-source BGPv4+, OSPFv2, OSPFv3, RIP router installed on Linux system with kernel 2.4 or higher. The best part is you can own a Cisco-IOS look alike router less than RM5K !! Strongly recommend this for your personal study and experimental use.

There’re few daemons that built-up this router :

  • zebra – routing manager
  • ospfd - implementing OSPFv2
  • ripd - implementing RIP v1 and V2
  • ospf6d - implementing OSPFv3 (IPv6)
  • ripngd - implementing RIPng (IPv6)
  • bgpd - implementing BGPv4+ (including address family support for multicast and IPv6)

Download the package from Quagga website, HERE or use Aptitude :

#apt-get install quagga

Here’re some good tips on configuring Debian/Kubuntu based Quagga upon completion of package installation.

To start/stop/restart Quagga service

#/etc/init.d/quagga <start|stop|restart>

To enable/disable the daemons:

#vim /etc/quagga/daemons

zebra=yes
bgpd=no
ospfd=yes
ospf6d=no
ripd=no
ripngd=no

To create configuration files

Firstly, you must create a configuration file, even it is not exist, and each daemons are associated with different configuration files. For example :

    • zebra – zebra.conf
    • ospfd – ospfd.conf
    • bgpd – bgpd.conf

Copy the template or sample configuration files from /usr/share/doc/quagga/examples/.. to /etc/quagga/..

#cp /usr/share/doc/quagga/examples/zebra.conf.sample /etc/quagga/zebra.conf
#cp /usr/share/doc/quagga/examples/ospfd.conf.sample /etc/quagga/ospfd.conf
#cp /usr/share/doc/quagga/examples/bgpd.conf.sample /etc/quagga/bgpd.conf

Add a password to all the newly copied files :

# echo 'password YourPassHere' > /etc/quagga/bgpd.conf
# echo 'password YourPassHere' > /etc/quagga/ospfd.conf
# echo 'password YourPassHere' > /etc/quagga/zebra.conf

You must always ensure the file permissions are correct, it may be vary from your machine/permission settings :

#chown quagga.quaggavty /etc/quagga/*.conf
#chmod 640 /etc/quagga/*.conf

Then, try to restart the Quagga.

debian.conf Configuration Guide

By default, the Quagga daemons are listening to the loopback interface 127.0.0.1 only with different ports for bgpd, ospfd, and zebra respectively, and cannot access remotely. For example, bgpd daemon is using port 2605. Which also means that you can access to the BGP router by executing the following command :

#telnet localhost 2605

If you want to access the Quagga routers remotely from specific IP address, then you may need to modify the /etc/quagga/debian.conf file.

If you want your OSPF router listen to loopback interface and 10.10.10.1, then your configuration will be like :

ospfd_options=" --daemon -A 127.0.0.1 10.10.10.1"

If you wish to let your BGP router to be access from all interfaces IP address, the configuration will be as below :

*For security measurement, I recommend you shouldn’t not allow this.

bgpd_options=” –daemon”

You may need to restart your Quagga services to take effective.

How to configure VTYSH, an integrated shell for Quagga

By instance, if you wish to access to your BGP router :

#telnet localhost 2605

If you found it is not practical or troublesome to telnet into the zebra, ospf and bgp routers separately, you can enable this feature, VTYSH. It has created an interface to access and save the configuration using a single UI, and it looks like your Cisco router!

To use this feature, you need to create the configuration by copy the sample :

#cp /usr/share/doc/quagga/examples/vtysh.conf.sample /etc/quagga/vtysh.conf

Then, edit the configuration /etc/quagga/vtysh.conf and here’s the sample configuration :

 
!
! Sample
!
! service integrated-vtysh-config
hostname quagga-router
username root nopassword
!

In the sample above, “service integrated-vtysh-config” is remarked and disabled. It would save your configuration separately into the protocol you have updated. Let’s see the example below when OSPF and BGP routers configuration are changed and saved :

#vtysh
quagga-router#write
Configuration saved to /etc/quagga/ospfd.conf
Configuration saved to /etc/quagga/bgpd.conf

If you have enabled “service integrated-vtysh-config” in the config, the configuration will be saved into another file namely, /etc/quagga/quagga.conf. By using this configuration, you will look into quagga.conf first followed by it own protocol files i.e. ospfd.conf when you telnet into it. My recommendation is to disable this feature for easier maintenance and avoid confusion.

#vtysh
quagga-router#write
Configuration saved to /etc/quagga/quagga.conf

Make sure you have enabled “vtysh_enable=yes” settings in the /etc/quagga/debian.conf.

In addition, it’s recommended to add “VTYSH_PAGER=more” in your /etc/environment file, or else you will be annoying by the blinking “END” at the left down corner & requires you to type “q” to continue.

Some of the machine may not works by adding the abovementioned, then you shall need to it in your /home/username/.profile

Ensure the file permission and restart the Quagga service :

#chown quagga.quaggavty /etc/quagga/*.conf
#chmod 640 /etc/quagga/*.conf
#/etc/init.d/quagga restart

Additional Info, IP Forwarding

By default, Linux does not allowed IP forwarding between interfaces. It’s required to enable this by executing the following configurations :

#echo "1" > /proc/sys/net/ipv4/ip_forward

Tuesday, April 20, 2010

How to change date/time in Ubuntu?

Linux always have two types of clocks, which are Hardware Clock and System Clock. Hardware Clock, also known as CMOS Clock or Real-time Clock (RTC). System Clock is the software clock used by Linux.

When the system boots up, it would get the time/date from Hardware Clock and set it to System Software Clock. This System Clock may not often accurate, and will experience some clock slipping especially high hardware resources during too many processes running. There’re only two ways to ensure the clock is accurate according NTP, either reboot your system or perform manual synchronization.

ntp_time

To check your current date & time

root:/home# date
Tue Apr 20 07:45:44 PDT 2010

To change the system software clock manually

root:/home# date 042022462010.00
Tue Apr 20 22:46:00 PDT 2010

Format : date <MMDDHHmmYYYY.ss>

To ensure if your system time zone is configured correctly

( Only perform these steps if time/date is NOT CRITICAL on your system, else skip this step )

root:/home# /etc/network/if-up.d /ntpdate
root:/home#  date
Tue Apr 20 07:50:41 PDT 2010

It seems like the time zone is not configured properly, change your folder to /usr/share/zoneinfo and select the most appropriate region in the following steps

To change the system time zone

root:/home# ln -sf /usr/share/zoneinfo/Asia/Kuala_Lumpur /etc/localtime

To perform synchronization to NTP using rdate

The time server can be any public NTP server that comply to RFC868

root:/home# /usr/bin/rdate -s time-a.nist.gov

To set your hardware clock time and verify

root:/home# /sbin/hwclock --show
Tue 20 Apr 2010 03:59:03 PM MYT  -0.987237 seconds
root:/home# /sbin/hwclock --systohc
root:/home# /sbin/hwclock --show
Tue 20 Apr 2010 10:58:26 PM MYT  -0.782410 seconds
root:/home# /etc/network/if-up.d /ntpdate

Refers : Man Page for hwclock

Cesium Atomic Clock, maintain an accuracy of 10−9 seconds per day!!  beamtube

Monday, September 15, 2008

How to send messages within a shell terminal in Linux ?

There are TWO(2) common methods that you can communicate and send messages between users in shell terminal in Linux. Most of the kernel is compiled with the package, i.e. wall and write.

Wall is a command to send message to everyone in the shell terminal, in the other word means broadcast the message.

( Refer Wall Manpage )

Example :

root@localhost:/# wall    ( press Enter )
Hello Testing...broadcast using wall
   
( Ctrl-D to broadcast )

Broadcast Message from josephlee@localhost
        (/dev/pts/2) at 22:21 ...

Hello Testing...broadcast using wall
root@localhost:/#

Write is a command to send message to a specify user in the shell terminal. Normally you will also need "who" or "w" command to find out who is in the terminal.

( Refer Write Manpage )

Example :

root@localhost:/#
write testuser    ( press Enter )
Testing 123...     ( Ctrl-D to send )

Message from josephlee@localhost on pts/2 at 22:26 ...
Testing 123...
EOF
root@localhost:/#

Friday, May 16, 2008

Linux Policy Routing : ip rule

Policy based routing is actually an act of having a multiple routing table in a single machine. Normally, it is used when involving different routes and gateways.

Your kernel must be ready compiled with IP Advanced Router and IP Policy Routing in order to use this features.

To show the ip rule

# /sbin/ip rule show
0:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default

To show the main routing table

# /sbin/ip route list table main

203.158.11.16/29 dev eth2  proto kernel  scope link  src 203.158.11.17
192.168.0.0/24 dev eth0  proto kernel  scope link  src 192.168.0.254
10.100.100.0/24 dev eth1  proto kernel  scope link  src 10.100.100.2
default via 203.158.11.22 dev eth2

The above shown, main table is actually refers to the main routing table when you type /sbin/ip route, whereas the local and default table is a new one.

You can generate rules which point to different tables ( i.e. xyz table ) which allow us to override system wide routing rules.

The first rule specifies that any packet from any where should first be matched against routes in the local routing table.The local routing table is for broadcast addresses on link layers, network address translation, and locally hosted IP addresses.

When a packet that bound for x.x.x.x IP address

  1. The packet that bound for x.x.x.x would first pass thru the local routing table.
  2. If there is no a local hosted IP address, it would look the main routing table to select a destination route.
  3. If there is no host nor network match for this destination, thus the packet will match the default route in the main routing table.

To add a new table

# /sbin/ip route add 192.168.1.0/24 via 192.168.0.254 table 200

# /sbin/ip route add default via 10.100.100.1 table 200

To apply a rule to the newly added table 200

It means all the traffic from 192.168.0.0/26 will be routed via routing table 200

# /sbin/ip rule add from 192.168.0.0/26 table 200

# /sbin/ip route flush cache

*** Remember to flush the routing table cache ***

Therefore, you may have the followings results when you show your ip rules :

# /sbin/ip rule show
0:      from all lookup local
32765:  from 192.168.0.0/26 lookup 300
32766:  from all lookup main
32767:  from all lookup default

To delete a ip rule

# /sbin/ip rule del from 192.168.0.0/26 table 200

# /sbin/ip route flush cache

*** Remember to flush the routing table cache ***

It is quite troublesome if you need to type so many lines each and everytime the system is booted, thus you can actually put in a scripts. Below is some sample scripts :

#!/bin/sh
/sbin/ip route flush table 200
# Copy main routing table to 200
/sbin/ip route list table main |while read ROUTE ; do /sbin/ip route add table 200 $ROUTE ; done
/sbin/ip route replace default via 10.100.100.1 table 200
/sbin/ip rul add from 192.168.0.0/26 table 200
/sbin/ip route flush cache

Some other useful ip rule commands :

To change the preferences of the routing table

# /sbin/ip ru add from 192.168.0.0/26 pref 3500 table 200

0:      from all lookup local
3500 :  from 192.168.0.0/26 lookup 300
32766:  from all lookup main
32767:  from all lookup default

To create a NAT rule with ip rule

# /sbin/ip ru add nat 203.158.11.20 from 192.168.0.188


0:      from all lookup local
3500 :  from 192.168.0.0/26 lookup 300
32765:  from 192.168.0.188 lookup main map-to 203.158.11.20
32766:  from all lookup main
32767:  from all lookup default

 

Usage: ip rule [ list | add | del | flush ] SELECTOR ACTION
SELECTOR := [ from PREFIX ] [ to PREFIX ] [ tos TOS ] [ fwmark FWMARK ]
            [ dev STRING ] [ pref NUMBER ] [ prio NUMBER ]
ACTION := [ table TABLE_ID ]
          [ prohibit | reject | unreachable ]
          [ realms [SRCREALM/]DSTREALM ]
TABLE_ID := [ local | main | default | NUMBER ]

Thursday, May 15, 2008

How to minicom serial console in Linux ?

Firstly, you need to get ready with the tools as below :

  1. RS232 Console Serial Cable
  2. USB to RS232 Serial Cable convertor

usbtoSerialOLYMPUS DIGITAL CAMERA

Then, you will need to install minicom package into your linux. For debian user, you can install using aptitude or apt.

# apt-get install minicom

Then plug your USB to RS232 Serial Convertor into your USB port. The type # dmesg and you should see the followings text at the bottom.

usb 5-1: new full speed USB device using uhci_hcd and address 2
usb 5-1: configuration #1 chosen from 1 choice
usbcore: registered new interface driver usbserial
/build/buildd/linux-source-2.6.22-2.6.22/drivers/usb/serial/usb-serial.c: USB Serial support registered for generic
usbcore: registered new interface driver usbserial_generic
/build/buildd/linux-source-2.6.22-2.6.22/drivers/usb/serial/usb-serial.c: USB Serial Driver core
/build/buildd/linux-source-2.6.22-2.6.22/drivers/usb/serial/usb-serial.c: USB Serial support registered for pl2303
pl2303 5-1:1.0: pl2303 converter detected
usb 5-1: pl2303 converter now attached to ttyUSB0
usbcore: registered new interface driver pl2303
/build/buildd/linux-source-2.6.22-2.6.22/drivers/usb/serial/pl2303.c: Prolific PL2303 USB to serial adaptor driver

Identify where you USB convertor is attached to. From the example above, it is connected to /dev/ttyUSB0 *( Remember it, as you will be using this info later ).

Now, start to configure your minicom using su privileges by :

# sudo minicom -s

Then, select theSerial port setup.

minicom-1

Change your settings for Serial Device to /dev/ttyUSB0 ( or whichever is shown when you did # dmesg just now ) and also change the item (E), Bps/Parity/Bits to suite to your device. You may need to change other settings as per your requirements. Press ENTER upon complete.

minicom-2  Then, select Save setup as dfl and exit.

Now, you may start with your serial console communication by issue the following command :

# minicom

minicom-3

Done!

Tuesday, May 13, 2008

VLAN for linux

What is VLAN ?

VLAN, Virtual Local Area Network, is somehow a several virtual network co-exist in a same switch port or interface by using the software configurations but not using hardware interface.

In the case whereby all workstations which connected to a same L2 switch in LAN X, are able to communicate within each other. If a workstation from LAN X is wish to communicate with LAN Y, then a router is needed.

VLAN, is actually an act of dividing the communications between few different network virtually by using a single switch device. A single switch port in a VLAN-capable switch can carry packets from multiple virtual LANs and linux can understand the format of these Ethernet frames.

VLAN, is known as IEEE 802.1Q and aslo known as VLAN tagging. More info on Wikipedia.

What are the advantages using VLAN ?

  • Performance
  • Easy to manage
  • Security
  • Trunks
  • Save the work of 'hardware configurations' whenever there is any changing of physical location for any device.

How to configure VLAN ?

The 802.1Q package has been pre-patch in kernel 2.4. Any distributions which are earlier than this, should download and compile/patch the kernel before proceed.

First of all, you need/must to modprobe the module by :

# modprobe 8021q

Then you should make sure the interface where you want to add the VLAN is UP and RUNNING.

For example,

2: eth0: <BROADCAST,MULTICAST,UP,10000> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 00:02:44:73:ed:64 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.254/24 brd 192.168.0.255 scope global eth0
    inet6 fe80::202:44ff:fe73:ed64/64 scope link
       valid_lft forever preferred_lft forever

To bring up the interface

# ifconfig eth0 up

# ip link set eth0 up

To bring down the interface

# ifconfig eth0 up

# ip link set eth0 up

Case 1 : You will want to add an VLAN 8 to interface eth0 and configure as 10.10.10.10/25 for this VLAN interface. Then remove it.

To add a new VLAN

# vconfig add eth0 8

To bring up the VLAN interface and configure IP

# ifconfig eth0.8 up

# ifconfig eth0.8 10.10.10.10 netmask 255.255.255.128 broadcast 10.10.10.127

To remove the VLAN interface

# vconfig rem eth0.8

Friday, May 9, 2008

How to dial PPPoE in Linux

There are a few simple steps to make a pppoe connection in Linux.

** The following commands is based on Kubuntu distributions

First, you need to configure the pppoe configurations at the very first time using the following command using root provileges.

# pppoeconf

Then following the text-based menu screen will be shown and follow the instructions as below :

  1. Confirm that your Ethernet card is going to connect to ADSL modem.
  2. Enter your username ( i.e. justk2@streamx )
  3. Enter your password.
  4. If you have configured it before, you will be asked if it may be modified.
  5. Popular options: you are asked if you want the “noauth” and “defaultroute” options and to remove “nodetach” - choose Yes.
  6. Use peer DNS - choose Yes.
  7. Limited MSS problem - choose Yes.
  8. Then you are asked if you want to connect at start up.
  9. Finally you are asked if you want to establish the connection immediately.
  10. Once you have finished these steps, your connection should be working.

Next time, you may use the following command

To start the adsl dial up

# pon dsl-provider

To stop the adsl dial up

# poff dsl-provider

Thursday, May 8, 2008

Linux Firewall : iptables - NAT

What is NAT ?

NAT, refers to Network Address Translations, also known as network masquerading, native address translation or IP masquerading, is a method to translate/change the source or destination IP address when traffic passing through. It may also used for the TCP and UDP port  of the passing IP packet.

Most of the time it is used to provide Internet access to a multiple LAN hosts by using a single Public IP.

 

What you must know ?

MASQUERADING

Masquerading is to translate all IP to a single IP and it is done with NAT. It is to fake the outgoing packet. The incoming packet should be translated too.

Masquerading works based on the specified interface.

Source NAT ( SNAT )

SNAT is when you alter the source address of the first packet: i.e. you are changing where the connection is coming from. Source NAT is always done post-routing, just before the packet goes out onto the wire. Masquerading is a specialized form of SNAT.

For dynamic Public IP case, whenever the source IP is changed, the source port numbers may changed too. Therefore, it is more easier to do SNAT on all outgoing packets on this interface. Also bear in mind, it would implicit DNAT as well and somehow.

Destination NAT ( DNAT )

DNAT is when you alter the destination address of the first packet: i.e. you are changing where the connection is going to. Destination NAT is always done before routing, when the packet first comes off the wire. Port forwarding, load sharing, and transparent proxying are all forms of DNAT.

What is important ?

The most important option here is the table selection option, `-t'. For all NAT operations, you will want to use `-t nat' for the NAT table.

You may need to specify the source ( `-s' or `--source' ) and destination ( `-d' or `--destination' ) of the packets you want to NAT. These options can be followed by a single IP address ( e.g. 192.168.1.1 ), a domain name ( e.g. www.justk2.com ), or a network address ( e.g. 192.168.1.0/24 or 192.168.1.0/255.255.255.0 ).

Lastly, you also need to specify the incoming ( `-i'  ) or outgoing ( `-o' ) interface to match, but which you can specify depends on which chain you are putting the rule into: at PREROUTING you can only select incoming interface, and at POSTROUTING you can only select outgoing interface.

**If you use the wrong one, iptables will give an error.

Chains in NAT table

There are three (3) different chains in NAT table, which are PREROUTING, POSTROUTING and OUTPUT.

PREROUTING Chain

It is for Destination NAT, as packets first come in.

Destination NAT is specified using " -j DNAT ", and the " --to-destination " option specifies an IP address, a range of IP addresses, and an optional port or range of ports (for UDP and TCP protocols only).

Case 1 :

To DNAT all incoming packet at 203.158.26.29 at eth2 to the single LAN station 192.168.10.22.

# /sbin/iptables -t nat -A PREROUTING -i eth2 -d 192.168.10.22 -j DNAT --to 203.158.26.29

Case 2 :

To DNAT the incoming port 8080 at 203.158.26.29 at eth2 to the DMZ station 192.168.10.188 web server ( port 80 )

# /sbin/iptables -t nat -A PREROUTING -i eth2 -d 192.168.10.188 -j DNAT --to 203.158.26.29:8080

** This is known as Port forwarding.

POSTROUTING Chain

It is for Source NAT, as packets leave.

Source NAT is using " -j SNAT " and " --to-source " option specifies an IP address, a range of IP addresses, and an optional port or range of ports (for UDP and TCP protocols only).

Case 1 :

To NAT the LAN station ( 192.168.92.62 ) from eth0 to a static public IP or WAN IP ( 203.158.26.29 ) at eth2

# /sbin/iptables -t nat -A POSTROUTING -o eth2 -s 192.168.92.62 -j SNAT --to 203.158.26.29

Case 2 :

To NAT the entire LAN network ( 10.10.10.0/24 ) from eth1 to a range of WAN IP ( 203.158.26.29 ~ 203.158.26.32 ) at eth2

# /sbin/iptables -t nat -A POSTROUTING -o eth2 -s 10.10.10.0/24 -j SNAT --to 203.158.26.29-203.158.29.32

Case 3 :

To NAT the LAN network to a dynamic WAN IP i.e. PPP connection.

# /sbin/iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE

OUTPUT Chain

It is for the firewall or router itself.

 

FOUR steps to makes your NAT works

Forward the traffic

If you are using the Linux kernel more than 2.6, the following commands should works.

Firstly, you should allow the traffic to forward ( passing ) through your firewall/router. By default, the value is 0 which is disabled.

# echo 1 > /etc/sys/net/ipv4/ip_forward

In some cases, you may need to edit /etc/sysctl.conf and change the line that says net.ipv4.ip_forward = 0 to net.ipv4.ip_forward = 1. This essentially tells your kernel to do step one on boot.

** Also remember to accept the traffic passing in your forward chains ( more info as my earlier post )

# /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

Post-route the traffic

# /sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Thursday, May 1, 2008

Linux Firewall : iptables - FILTER table

Further to the basic understanding on the iptables in my earlier post ( Linux Firewall : iptables - Basic ), now let's me continue with some example commands for FILTER table :

To list the iptables table/chain

#iptables -L

#iptables -t <table> -L

( use to list the specify table besides default - FILTER table )

#iptables -t <table> -L -vnx

( use this with verbose, show numeric output and expand the numbers )

To add a rule on top of the chain

#iptables -I <chain> -j [ACCEPT|DROP|REJECT|other]

e.g. # iptables -I FORWARD -j ACCEPT

To append a rule at the bottom of the chain

#iptables -A <chain> -j [ACCEPT|DROP|REJECT|other]

e.g. # iptables -I INPUT -j DROP

To delete a rule in a chain

#iptables -D <chain> <the row number of the rule started from 1>

e.g. # iptables -D FORWARD 2

To create a new chain

#iptables -N <chain>

e.g. # iptables -N CUSTOMFORWARD

To change the default policy of a chain

#iptables -P <chain> [ACCEPT|DROP|REJECT|other]

e.g. # iptables -P FORWARD DROP

# iptables -P CUSTOMFORWARD ACCEPT

To flush the iptables

#iptables -F

To flush specify TABLE

#iptables -t <table> -F

To delete a CHAIN

#iptables -X <chain>

So, have you warmed-up? Now let's go into more commands, try to understand and apply it wisely. :P

Case 1

To drop all the traffic from 192.168.0.0/24 which trying to ssh-ing to the firewall itself, 10.133.0.1

# iptables -I INPUT -p tcp --dport 22 -s 192.168.0.0/24 -d 10.133.0.1 -j ACCEPT

-I = to add this rule to the top of INPUT chain.

-p = protocol, specifically here is TCP.

--dport = destination port, specifying SSH port ( port 22 ).

-s = the source address, pertaining where this traffic from where is 192.168.0.0/24 for this rule.

-d = the destination address, here is the firewall itself (suppose) as it is INPUT chain.

-j = jump to targer. Here is to accept the traffic.

Case 2

To drop all the traffic from 192.168.0.0/24 passing thru the firewall and only allowed 192.168.0.188 to pass thru.

# iptables -P FORWARD DROP

# iptables -I FORWARD -s 192.168.0.188 -j ACCEPT

# iptables -I FORWARD -d 192.168.0.188 -j ACCEPT

Firstly, we set the FORWARD as "default drop policy" ( means drop everything! ). Then we add the 2 following rules on top of the FORWARD chain. In order to allows the traffic passing thru, it should be dual-way. Thus, two(2) different rules as above are created with specifying source and destination address respectively.

General Network Traffic rules

Next, we will want to use some standard rules for general network traffic. This goes a bit beyond the basic stuff, however iptables can determine the 'state' that a packet is in. This has to do with standard TCP communication. For example, the 3 way handshake between two hosts when transmitting data.

  • NEW => Server1 connects to Server2 issuing a SYN (Synchronize) packet.
  • RELATED => Server 2 receives the SYN packet, and then responds with a SYN-ACK (Synchronize Acknowledgment) packet.
  • ESTABLISHED => Server 1 receives the SYN-ACK packet and then responds with the final ACK (Acknowledgment) packet.

After this 3 way handshake is complete, the traffic is now ESTABLISHED. In order for this type of TCP communication, something similar to these three rules are necessary:

# iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT # iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT # iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

The last rule obviously allows any traffic the leave the server.

The result of the three rules and the previous commands in Case 1 and Case 2 above will be as follow respectively :

Chain INPUT (policy ACCEPT) target prot in out source destination ACCEPT tcp * * 192.168.0.0/24 10.133.0.1 tcp dpt:ssh ACCEPT all * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED

Chain FORWARD (policy DROP) target prot in out source destination ACCEPT * * * 0.0.0.0/0 1 92.168.0.188 ACCEPT ACCEPT * * * 192.168.0.188 0.0.0.0/0 ACCEPT ACCEPT * eth0 * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT) target prot in out source destination ACCEPT * * * 0.0.0.0/0 0.0.0.0/0 state NEW,RELATED,ESTABLISHED

From here you can add whatever rules you like depending on your server requirements :

To block some BAD source IP address

#iptables -A INPUT -s 10.10.132.2 -j DROP

To drop some spamming from a source IP address ( if you are using default accept policy or accepted SMTP port in other rule )

#iptables -A FORWARD -p tcp --dport 25 -s 192.168.0.111 -j DROP

To allow the LAN (eth0) to access your web while block all external access from WAN(eth1) to your web

#iptables -I INPUT -p tcp --dport 80 -j DROP

#iptables -I INPUT -p tcp --dport 80 -s 192.168.0.0/24 -j ACCEPT

The 1st rule should be execute before the 2nd rule as you are using the -I ( add ).

To drop all ICMP/Ping packet to the firewall

#iptables -A INPUT -p icmp -j DROP

If you are using the default ACCEPT policy, then you must be DROP anything else at the last of the rule. In our case here ( since FORWARD chain is default drop policy ), you should reject everything for the INPUT chain.

# iptables -A INPUT -j REJECT

There are more to explore besides the example shown above. But bear in mind, ***NEVER TRY ON A LIVE SYSTEM!!***

In the next post, I will proceed to NAT table.

Wednesday, April 23, 2008

Linux Firewall : iptables - Basic

Introductions

IPTABLES is an applications for linux in configuring netfiters, chains and rules. This command must be executed by the root privilege user. Normally this command is located at /usr/sbin/iptables or /sbin/iptables.

 

How iptables works ?

Every packet inspected by the iptables will be passing through a sequence of built in tables or queues for processing.

Basically the iptables is built up with THREE(3) tables which are MANGLE table which responsible for altering the TCP header, FILTER table for packet filtering and NAT table which responsible for network address translation(NAT).

FILTER Table

Filter table can be divided into 3 different chains, which are :-

INPUT Chain

This chain will filter all the packets which destinated to the firewall or the device itself.

FORWARD Chain

This chain responsible to filter all packets which passing through from one interface to another interface in firewall.

OUTPUT Chain

This chain filters all the packets which originated from the firewall or the device itself.

NAT Table

There are also 3 different chains in the NAT table, which are : -

PREROUTING Chain

This chain will translate the address before routing. Normally it is used with destination NAT or DNAT. Normally this chain be used when doing port forwarding.

POSTROUTING Chain

This chain will translate the address after routing. Normally it is used to change source NAT or SNAT IP.

OUTPUT Chain

Used to network address translate the firewall outgoing packets but it is rarely being used.

MANGLE Table

This table responsible in modify the TCP header to provide quality of service (QoS) before routing. It might be rarely used in a small SOHO network.

There are five chains in this table which are PREROUTING, POSTROUTING, INPUT, OUTPUT and FORWARD.

 

Everytime you create/remove/alter the iptables rules, you need to specify the TABLE and CHAIN. If there is no TABLE is being specify, the system will assume it is the default table, which is FILTER table as most rules are related to the FILTER table.

You will understand more when it comes to the command syntax, where I will touch on later.

 

How a packet flow through the iptables tables/chains ?

tables_traverse

When a packet hits the WAN to create a data connection, it will flow as accordingly as below :

  1. It will examined by MANGLE table's PREROUTING chain, if any.
  2. Followed by the NAT table's PREROUTING chain if it's required DNAT.
  3. Then it is routed.
  4. If the packet is destinated to the LAN network, it will be examined by the MANGLE table's FORWARD chain for QoS if any  followed by the FILTER table's FORWARD chain. Then it will examined by the MANGLE table's POSTROUTING chain for QoS if any followed by the FILTER table's POSTROUTING chain if any SNAT is needed.
  5. Then the packet will arrive to the LAN station. If the destinated LAN station is decided to reply, then it will go thru the same TABLES and CHAINS reversely.
  6. If the packet is destinated to the firewall itself, then it will be examined by the MANGLE table's INPUT chain followed by the FILTER table's INPUT chain. If it is success, then the packet will be reaching the firewall.
  7. If the firewall decided to reply then it will be examing through the MANGLE, NAT and FILTER table's OUTPUT sequencely. Then followed by the MANGLE and NAT table's POSTROUTING before the replying packet back to the WAN side.

 

What is iptables TARGET and JUMP ?

When each and every iptables rules examine the packet, it will tries to identify the user-defined target or jump for some sort of operations.

Basically there are few TARGET where we are commonly used as :

ACCEPT

As named, it is to accept and will pass it to the destinated applications or IP/network.

DROP

The packet will be blocked and will not be passing through/to. No notifications will be provided to the SENDER.

REJECT

There is slightly different between REJECT target and DROP target, reject will blocked the packet but will also provide an ERROR message to the SENDER.

DNAT

This is use to do destination network address translation whereby it will change the destination IP address of the packet.

SNAT

This is use to do source network address translation whereby it will rewrite the source IP address of the packet.

MASQUERADE

This is considered the dynamic way to do source network address translation whereby the source IP address will be rewrite as the firewall's WAN interface IP address.

 

Common iptables command switch operations

Before you able to create/remove/alter the iptables firewall rules, you need to understand the subnetting(CIDR), routing and TCP/IP concept very well. Else, you might be MESSED UP the firewall !!!

               *** Play and try at your own risk ***

- t  <table>

To specify the TABLE ( MANGLE, NAT or FILTER )

-j <target>

To jump to the specified target chain when the packet matches the current rule.

-A

To append a rule to the end of the chain.

-I

To add a rule to the top of the chain.

-D

To delete a specify rule in the chain.

-F

To flush the whole rules.   *** Dangerous command ***

-p <protocol type>

To match a protocol like udp, tcp, icmp etc.

-p udp/tcp --dport <destination port>

To match a protocol like udp/tcp with destination port number.

-p udp/tcp --sport <source port>

To match a protocol like udp/tcp with source port number.

-s <source address>

To match the source address / network.

-d <destination address>

To match the destination address / network.

-i <incoming interface>

To match the incoming interface like eth0, eth2 etc.

-o <outgoing interface>

To match the outgoing interface like eth0, eth2 etc.

Example command

/usr/sbin/iptables -A INPUT -i eth0 -p tcp --dport 22 -s 192.168.0.0/24 -j ACCEPT

This command will add a rule at the bottom of the FILTER table's INPUT chain to accept the TCP packet from 192.168.0.0/24 network thru eth0 interface which destinated to the firewall port 22.

There are still more advanced ways to create firewall rules using iptables. I will continue discuss it in the coming post.

Have a nice try and still the same advise....

                     *** Try at your own risk !!! ***

Sunday, April 20, 2008

Basic Linux IP Networking Command 1

Ifconfig - configures interface devices for use. It provides each device with its (IP) address, netmask, and broadcast address.

usage : ifconfig ${DEVICE} ${IPADDR} netmask ${NMASK} broadcast ${BCAST}

example : ifconfig eth0 192.168.0.1 netmask 255.255.255.0 broadcast 192.168.0.255

eth0  Link encap:Ethernet  HWaddr 00:C1:4E:7D:9E:25
      inet addr:172.16.1.1  Bcast:172.16.1.255  Mask:255.255.255.0
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:389016 errors:16534 dropped:0 overruns:0 rame:24522
      TX packets:400845 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100
      Interrupt:11 Base address:0xcc00

You  may also use this command as :

ifconfig -a - view all the interfaces either active or inactive.
ifconfig eth0 down - shut down eth0
ifconfig eth1 up - activate eth1
ifconfig eth0 arp - enable ARP on eth0
ifconfig eth0 -arp - disable ARP on eth0
ifconfig eth0 netmask 255.255.255.0 - set the eth0 netmask
ifconfig lo mtu 2000 - set the loopback maximum transfer unit
ifconfig eth1 172.16.0.7 - set the eth1 IP address

 

route - adds predefined routes for interface devices to the Forwarding Information Base (FIB).

usage : route add -net ${NETWORK} netmask ${NMASK} dev ${DEVICE}

example : route add -net 192.168.1.0 netmask 255.255.255.0 dev eth1

usage : route add -host ${IPADDR} ${DEVICE}

example : route add -host 192.168.2.2 eth2

This displays the Kernel IP routing table by using "route -n" :

Kernel IP routing table
Destination   Gateway     Genmask         Flags Metric Ref Use Iface
172.16.1.4    *           255.255.255.255 UH    0      0     0 eth0
172.16.1.0    *           255.255.255.0   U     0      0     0 eth0
127.0.0.0     *           255.0.0.0       U     0      0     0 lo
default       172.16.1.1  0.0.0.0         UG    0      0     0 eth0

You may also use this command to change your default gateway :

usage : route add default gw ${IPADDR}

example : route add default gw 172.16.1.2