Friday 28 June 2013

Mysql Master-Slave Replication after slave fails

1. From slave if we run mysql> mysql slave status;
   it will show last bin file slave reads from master 
 and all,so start from that bin file to sink with master to slave.

2. Set Master configuration on the Slave.
  Execute the following command on a MySQL prompt to sink slave with master:

mysql > CHANGE MASTER TO MASTER_HOST=’10.100.10.80’, MASTER_USER=’repl’, MASTER_PASSWORD=’slavepassword’, MASTER_LOG_FILE=’mysql-bin.000003’, MASTER_LOG_POS=106;

This is how you tell Slave how to connect to Master in order to replicate. Note the log coordinates. These are the coordinates you got from step 1 above.

[
Now we need to tell the slave where the master is located, which binlog file to use, and which position to start. Issue this CHANGE MASTER TO 
command on the slave server(s): (don’t forget to change the values to match your master server)

 mysql> CHANGE MASTER TO
    ->   MASTER_HOST='master IP address',
    ->   MASTER_USER='replication user',
    ->   MASTER_PASSWORD='replication user password',
    ->   MASTER_PORT=3306,
    ->   MASTER_LOG_FILE='mysql-bin.000015',
    ->   MASTER_LOG_POS=540,
    ->   MASTER_CONNECT_RETRY=10;

mysql> show warnings\G

Two values to note in the slave status shows us that our CHANGE MASTER TO statement worked:

    Master_Log_File: mysql-bin.000015
    Read_Master_Log_Pos: 540
]

3. Stop MySQL

4. Start MySQL normally

Checking out that everything is OK

Having started the slave MySQL node, you can log in and issue some commands to make sure that Slave is running OK.

On mysql prompt, give the following command:

mysql> show processlist;

You can see the SQL thread that gets data from Master (in the above output is the thread with Id 2) and the SQL thread that executes the statements on Slave (in the output is the thread with Id 1).

2. mysql> show slave status;

This will display the current status on slave. Pay attention to the *_Errno and *_Error columnsNormally, you shouldn’t see anything that indicates existence of errors there.

3. On mysql prompt, give the following command

mysql> show status like ‘Slave%’;

You should see an output like the following:
+----------------------------+-------+
| Variable_name              | Value |
+----------------------------+-------+
| Slave_open_temp_tables     | 0     |
| Slave_retried_transactions | 0     |
| Slave_running              | ON    |
+----------------------------+-------+

Pay attention to Slave_running being with value ON.

Important note on binary log time to live

As we have said before, you can have Slave down and
re-synchronize as soon as you bring it up again.But do not put it out of service for quite long because, then it will be impossible to synchronize its content with Master. 

This is because the binary logs on Master do not leave forever.

There is the variable with name expire_logs_days that determines the number of days for automatic binary log file removal. Check this out. This should be 10, meaning that if you ever have your Slave down for 10 days or more, it will not be able to do replication as soon as you bring it up, and you will have to  everything from the beginning.

How to install Linux Malware Detect (LMD) / Maldet

Malware can be trojans, viruses, spyware, adware, rootkits or any other malicious programs which can be very harmful to any computer user.
 

Linux Malware Detect (LMD) is an open source and free malware scanner and detector for Unix/Linux based operating systems.

Downloading latest LMD package
 

# wget http://www.rfxn.com/downloads/maldetect-current.tar.gz
 

Install the package

cd /opt
# gunzip maldetect-current.tar.gz
# tar -xvf maldetect-current.tar

# cd maldetect-1.4.2
./install.sh
 


Configuring LMD

By default all options are fully commented in the configuration file, so configure it according to your needs.

email_alert : If you would like to receive email alerts, then it should be set to 1.
email_subj : Set your email subject here.
email_addr : Add your email address to receive malware alerts.
quar_hits : The default quarantine action for malware hits, it should be set 1.
quar_clean : Cleaing detected malware injections, must set to 1.
quar_susp : The default suspend action for users wih hits, set it as per your requirements.
quar_susp_minuid : Minimum userid that can be suspended.

# cd /usr/local/maldetect/
vim conf.maldet


and enable the options you needed to check while running maldet

To scan it Manually

# maldet --scan-all /home

You performed a scan but failed to turn on the quarantine option, don’t worry just use the following command to turn on and quarantine all previous malware scan results.

# maldet --quarantine SCANID
OR
# maldet --clean SCANID

For Daily Scan

By default installation keeps LMD script under /etc/cron.daily/maldet and it is used to perform a daily scans, update of signatures, quarantine etc, and sends a daily report of malware scan to your specified emails.


If you need to add additional paths to be scanned, then you should edit this file accordingly to your requirements.

# vi /etc/cron.daily/maldet

How to find the least or busy time on an apache web server

# cut -d: -f 2 /var/log/httpd/*access_log* | sort | uniq -c

290873 00
184948 01
115479 02
84129 03
71059 04
67632 05
88071 06
149285 07
275537 08
431069 09
529708 10
586744 11
599993 12
591466 13
565942 14
585796 15
611814 16
639781 17
625244 18
622163 19
574962 20
558504 21
503386 22
412359 23


The first column is the number of hits on the webserver, the second column is the time of the day. In this example the 5th hour (05:00 - 05:59) is the least busy hour, the 18th hour (18:00 - 18:59) is the busiest hour.

Thursday 27 June 2013

How to block SSH Server Attacks Using DenyHosts

DenyHosts is an open source and free log-based intrusion prevention security program for SSH servers.(Brute Force Attacks).
It is intended to monitor and analyzes SSH server logs for invalid login attempts, dictionary based attacks and brute force attacks by blocking the originating IP addresses by adding an entry to /etc/hosts.deny file on the server and prevents the IP address from making any further such login attempts.

First add EPEL Repository
 

# wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm 

# rpm -ivh epel-release-5-4.noarch.rpm

Verify EPEL Repo
# yum repolist

Then install denyhost
 

# yum install denyhosts

Configuring DenyHosts for Whitelist IP Addresses
 

Once the Denyhosts installed, make sure to whitelist your own IP address, so you will never get locked out. To do this, open a file /etc/hosts.allow,

# vim /etc/hosts.allow
   sshd: public_ip_address
   sshd: local_ip_address

Add the each IP address one-by-one on a separate line, that you never want to block.

Configuring DenyHosts for Email Alerts
 

The main configuration file is located under /etc/denyhosts.conf. This file is used to send email alerts about suspicious logins and restricted hosts.

# vim /etc/denyhosts.conf
Search for the ‘ADMIN_EMAIL‘ and add your email address here to receive email alerts about suspicious logins.


SECURE_LOG = /var/log/secure
HOSTS_DENY = /etc/hosts.deny
BLOCK_SERVICE  = sshd
DENY_THRESHOLD_INVALID = 5 ---- block each host after the number of failed login attempts has exceeded this value.This value applies to invalid user login attempts
DENY_THRESHOLD_VALID = 10 ---  block each host after the number of failed login attempts has exceeded this value. This value applies to valid user login attempts
DENY_THRESHOLD_ROOT = 1 --- block each host after the number of failed login attempts has exceeded this value.This value applies to "root" user login attempts only.
DENY_THRESHOLD_RESTRICTED = 1 --- block each host after the number of failed login attempts has exceeded this value.This value applies to usernames that appear in the WORK_DIR/restricted-usernames file only.
WORK_DIR = /var/lib/denyhosts --- the path that DenyHosts will use for writing data to # (it will be created if it does not already exist).
SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES
HOSTNAME_LOOKUP=YES
LOCK_FILE = /var/lock/subsys/denyhosts
ADMIN_EMAIL = root
SMTP_HOST = localhost
SMTP_PORT = 25
SMTP_FROM = DenyHosts <nobody@localhost>
SMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]
DAEMON_LOG = /var/log/denyhosts
DAEMON_SLEEP = 30s
DAEMON_PURGE = 1h


save the entries in config file.

Restart the denyhost service
 

Once you’ve done with your configuration, restart the denyhosts service for new changes. We also add the denyhosts service to system start-up.

# chkconfig denyhosts on
# service denyhosts start

Watch DenyHosts Logs

To watch denyhosts ssh logs for how many attackers and hackers are attempted to gain access to your server. Use the following command to view the real-time logs.

# tail -f /var/log/secure

Remove Banned IP Address from DenyHosts

If you’ve ever blocked accidentally and want to remove that banned IP address from the denyhosts.
You need to stop the service.

# /etc/init.d/denyhosts stop

To remove or delete banned IP address completely. You need to edit the following files and remove the IP address.

# vim /etc/hosts.deny
# vim /var/lib/denyhosts/hosts
# vim /var/lib/denyhosts/hosts-restricted
# vim /var/lib/denyhosts/hosts-root
# vim /var/lib/denyhosts/hosts-valid
# vim /var/lib/denyhosts/users-hosts


After removing the banned IP Address, restart the service again.
# /etc/init.d/denyhosts start

[
The offending IP address added to all the files under /var/lib/denyhosts directory,so it’s makes very difficult to determine the which files contain the offending IP address.
One of the best way to find out the IP address using grep command. For example to find out IP address
162.10.25.127, do.

cd /var/lib/denyhosts
grep 162.10.25.127 *

]

Whitelist IP Addresses Permanently in DenyHosts

If you’ve list of static IP address that you want to whitelist permanently. Open the file /var/lib/denyhosts/allowed-hosts file.
Whatever IP address included in this file will not be banned by default (consider this as a whilelist).

# vim /var/lib/denyhosts/allowed-hosts
And add the each IP address on separate line. Save and close the file.

# We mustn't block localhost
127.0.0.1
162.10.25.127162.10.25.128
162.10.25.129

Tuesday 25 June 2013

How to configure a sudo user in linux

If a server needs to be administered by a number of people it is normally not a good idea for them all to use the root account.
This is because it becomes difficult to determine exactly who did what, when and where if everyone logs in with the same credentials. The sudo utility was designed to overcome this difficulty.

The sudo utility allows users defined in the /etc/sudoers configuration file to have temporary access to run commands they would not normally be able to due to file permission restrictions. The commands can be run as user "root" or as any other user defined in the /etc/sudoers configuration file.

When running the command with the sudo prefix, you will be prompted for your regular password before it is executed.
You may run other privileged commands using sudo within a five-minute period without being re-prompted for a password.
All commands run as sudo are logged in the 

 log file /var/log/messages.

say a user try to read the file /etc/sudoers, then normally it shows /etc/sudoers: Permission denied. Due to permission issue as normal users are not permitted to read this file. If we try the same faile with # sudo

# sudo more /etc/sudoers -- it will ask for your password
"ctechz not in the sudoers file. This incident will be reported".


This error will show because we didn't add the user 'ctechz' to sudo users list, so add the user into it.



the above is a normal user, switch as root user and try

# visudo

 General sudoers File Record Format
usernames/group servername = (usernames command can be run as) command
There are some general guidelines when editing this file:-

* Groups are the same as user groups and are differentiated from regular users by a % at the beginning. The Linux user group "users" would be represented by %users.


* You can have multiple usernames per line separated by commas.


* Multiple commands also can be separated by commas. Spaces are considered part of the command.


* The keyword ALL can mean all usernames, groups, commands and servers.


* If you run out of space on a line, you can end it with a back slash (\) and continue on the next line.


* The NOPASSWD keyword provides access without prompting for your password.

## Allow root to run any commands anywhere
root    ALL=(ALL) ALL 

ctechz  ALL=(ALL) ALL  -------> this user can run all commands
              run by root using sudo.

 Sudo shell

If you have sufficient rights configured in sudoers you can also open a root shell by using


# sudo -s
or
# sudo -i

 
If the user dont have any right to perform it shows that user is not in the sudoers file.

How to Limit SSH User Logins in linux

You have large number of user accounts on the systems, then it makes sense that we limit remote access to those users who really need it.
 

Open the config file

 # vim /etc/ssh/sshd_config

and Add an AllowUsers line at the bottom of the file with a space separated by list of usernames.

AllowUsers jeffin ctechz

Restart ssh service # service sshd restart


Note: If you are not able to login into the shell using root account after changing PermitRootLogin to YES, check AllowUsers either remove the line or add root also here.

How to Disable Root SSH Login on Linux

Open ssh config file # vim /etc/ssh/sshd_config
#PermitRootLogin yes

Replace this line by:
 PermitRootLogin no

In this file we can also change the "Port number" and "Banner" details as well and much more.

# service sshd restart


after when we login as "root" user it will show "Access denied" message.

Now login as a normal user and switch as root.

How to Decoding an SSL Certificate

Problem: You want to view information about a given SSL certificate, stored in a PEM file

Solution:
# openssl x509n-text -in filename

This is a quick way to learn who issued a certificate, its begin and end dates, and other pertinent details.

This is a quick way to learn who issued a certificate, its begin and end dates, and other pertinent details.

How to Validate an SSL Certificate

Problem: You want to check that an SSL certificate is valid,

Solution: IF your system's certificates are kept in a file ( as in Red Hat)

# openssl .... -CAfile file_of_CA_certificates.....

To check the certificate of a secure web site

# openssl s_client -quiet -CAfile /usr/share/ssl/cert.pem -connect www.comain.com:443

How to Generate an SSL Certificate Signing Request(CSR)

Problem: You want to obtain an SSL certificate from a trusted certifying authority(CA)
 

Solution: Generate a Certificate Signing Request(CSR)

# make -f /usr/share/ssl/certs/Makefile filename.csr

OR
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 
 -keyout mysitename.key -out mysitename.crt

and send filename.csr to the CA

Make sure that the certificate you have received is in PEM format. Suppose it's in the file cert.pem then decrypt your private key and append it to this file

# openssl rsa -in foo.key >> cert.pem

and then as root

# chown root.root cert.pem
# chmod 400 cert.pem


OR

First, generate a private key on the Linux server that runs Apache webserver using openssl command as shown below.

Generating RSA private key, 1024 bit long modulus.
 
# openssl genrsa -des3 -out www.ctechz.com.key 1024
 
Using the key generate above, you should generate a certificate request file (csr) using openssl as shown below.
 
# openssl req -new -key www.ctechz.com.key -out www.ctechz.com.csr

How to Create Access Control List using PAM

Problem: You need to apply an ACL to an existing service that does no explicitly support ACL's.
 

Solution: Use the listfile PAM module

First make ure the server in question uses PAM for

authentication, and find out which PAM service name it uses. This may be in the server documentation, or it may be clear from examining the server itself and perusing the contents of /etc/pam.d.

Suppose you are dealing with the IMAP mail server. First notice that there is a file called /etc/pam.d/imap Furhter the result of:

# locate imapd
.....
.......
/usr/sbin/imapd

shows that the IMAP server is in /usr/sbin/imapd, and:

# ldd /usr/sbin/imapd
libpam.so.0 => /lib/libpam.so.0 (0x40027000)

Shows that the server is dynamically linked against the PAM library(libpam.so).Create an ACL file for the IMAP service, let's say /etc/imapd.acl and make sure it is not world-writable:

# chmod o-w /etc/imapd.acl

Edit thsi file and place in it the usernames of those accounts authorized to use the IMAP server, one name per line. Then add the following to /etc/pam.d/imap

# account required /lib/security/pam_listfile.so file=/etc/imapd.acl item=user sense=allow onerr=fail

With this configuration, only those users listed in the ACL file will be allowed access to the IMAP service. If the ACL file is missing, PAM will deny access for all accounts. Entries in ACL file can be not only usernames, but also:

Terminal lines (item=tty)
Remote host(item=rhost)
Remote user(item=ruser)
Group membership(item=group)
Login shell(item=shell)

The sense keyword determines how the ACL file is interpreted. sense=allow means that access will be allowed only if the configured item is in the file, and denied otherwise. sense=deny means the opposite.

The onerr keyword indicates what to do if some unexpected error occurs during PAM processing of the "listfile" module-for instance if the ACL file does not exist.

NOTE: To debug problems with PAM modules, look for PAM-specific error messages in /var/log/messages and /var/log/secure
.

How to Enforce Password Strength using PAM

Problem: You want your users to employ strong passwords.
 

Solution: Use the pam_cracklib PAM module to test and enforce password strength requirements automatically. 

edit the parameters in the pam_cracklib module in 

/etc/pam.d/system-auth.

To increase the number of consecutive times a user can enter an incorrect password, change the retry parameter from its default of 3;

password required /lib/security/pam_cracklib.so retry=3

NOTE: PAM allows recursion via the pam_stack module that is, one PAM module can invoke another.

How to Prohibit root logins on Terminal Devices

Problem: You want to prevent the superuser,root from logging in directly over a terminal or pseudo-terminal

Soution: Edit /etc/securetty, this file contains device names, one per line, that permit root logins.Make sure there are no pseudo-ttys(pty) devices listed, so root cannot log in via the network, and remove any others of concern to you.

 /etc/securetty


 # serial lines
 tty1
 tty2
 # devfs devices
 vc/1
 vc/2
 

If possible dont permit root to log in directly.

Friday 21 June 2013

What is Vertical and Horizontal Scaling in a cloud

Vertical Scaling
 
Vertical scaling, also described as scale up, typically refers to adding more processors and storage to an SMP to pump up processing capability.Generally, this form of scaling employs only one instance of the operating system. 

Horizontal Scaling

Horizontal scaling, or scale out, usually refers to tying multiple independent computers together to provide more processing power.Horizontal scaling typically implies multiple instances of operating systems, residing on separate servers.

What is a Public Private and Hybrid Cloud

Public Cloud
 

A Public Cloud is one that’s based on the standard cloud
computing model where services, applications and storage 
are made available to users over the Internet 
‘as a service' typically on a Pay Per Use model.

Appealing to many businesses as they reduce complexity and lead times. Because the underlying architecture is fixed, 

there is less scope for customisation for security and performance.

There are many types of Public Cloud, the most common being Infrastructure as a service(IaaS),Platform as a service(PaaS), Software as a service(SaaS)and Desktop as a service(DaaS) platforms – all of which we make available to the channel through our proprietary Cloud services.

Suited to:– Companies that need to bring a service to market quickly,have less regulatory hurdles to overcome,

or are looking to outsource part or all of their organisational IT requirements.Under this scenario,the business can simply sign-up for and start using Cloud Computing,online storage and other services immediately.

Private Cloud

Private Clouds consist of cloud infrastructure 

that is deployed solely for a single organization, whether
managed internally or hosted by a third-party externally.

Private Clouds offer scope for advanced security, high availability or fault tolerant solutions that are not possible in a Public Cloud.

Suited to :– Businesses that must comply with strict regulations or that have highly critical applications will choose internal Private Clouds. With a private cloud, businesses install their own server and storage hardware but have the flexibility to shift workloads among servers as usage spikes or 

they deploy new applications.

Hybrid Cloud

As the name suggests, a hybrid cloud comprises both private

(internal) and public (external) cloud services.
Typically a business might run an application primarily on a private cloud, but rely on a public cloud to accommodate spikes in usage.

Suited to:- E-commerce, Because e-commerce sites must 

respond to fluctuations in traffic both on a daily and seasonal cycle, the actual work of processing the orders can benefit from the elastic characteristics of public cloud resources.

Thursday 20 June 2013

How to block Packets using iptables

iptables -F   ------ To flush all iptables rules

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


These permit outgoing traffic but drop incoming or forwarded packets.


1.Enabling Source Address Verification

Task: To prevent remote hosts from spoofing incoming packets as if they had come from your local machine.

Solution: Turn on source address verification in kernal.(ip spoofing protection)

echo 1 > /proc/sys/net/ipv4/conf/default/rp_filter

OR

change it in this file

# vi /etc/sysctl.conf
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1

 and run sysctl to reread the configuration immediately
# sysctl -p

Source address verifiction is a kernel-level feature that drops packets that appear to come from your internal network, but do not. Enabling this feature should be your first network-related security task. you can setup this same effect using firewall rules as well.


1.1 Blocking Spoofed Addresses

Task: Need to prevent remote hosts frrom pretending to be local to your network,

Solution: For a single machine to prevent remote hosts from pretending to be that machine,


# iptables -A INPUT -i external_interface -s your_IP_Address -j REJECT

If you have a linux machine acting as a firewall fir your internal network(say, 192.168.0.*) with two network interfaces, one internal and one external,and you want to prevent remote machines from spoofing internal IP address to the external interface, use the following

# iptables -A INPUT -i external_interface -s 192.168.0.0/24 -j REJECT


DROP v/s REJECT

DROP simply swallows the packet, never to be seen again and emits no response. REJECT in contrast responds to the packet with a friendly message back to the sender, something about REJECT the connection.

REJECT helps to understand why not able to connect to a network because of response message it sends, But DROP didnt give you any clue why not able to connect, it leaves you less chance to trouble shoot the error in connection.

REJECT can leave you open to denial of service attack(DOS). If a third party hack a system(victim) and sends message from victim to your machine and in response you reject the packets, returning them not to the third party but to victim, owner of the source address. You are unintentionally flooding victim with rejections.

 So better to choose DROP to prevent them from being abused in such a manner.(Better in a large network). If you are a home user REJECT is better.When Rejecting we can reject with different messages using --reject-with option.

2.3 Blocking all Network traffic

Problem: you want to block all network traffic by firewall

Solution:
iptables -F
iptables -A INPUT -j REJECT
iptables -A OUTPUT -j REJECT
iptables -A FORWARD -j REJECT

 
2.4 Blocking Incoming Traffic

Problem: You want to block all incoming network traffic, except from your system itself. Do not affect outgoing traffic,

iptables -F INPUT
iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -j REJECT

--------
# iptables -A INPUT -p tcp --syn -j REJECT
# iptables -A INPUT -p udp --dport 0:1023 -j REJECT
--------

Here in rule iptables takes advantage of statefulness, permitting incoming packets only if they are part of established outgoing connections. All other incoming packets are rejected.

Don't simply drop all input packets
 

# ipchains -F INPUT
# ipchains -A INPUT -j REJECT


as this will block responses returning from your legitimate outgoing connections,

iptables also supports the --syn flag to process tcp packets,
 

# iptables -A INPUT -p tcp --syn -j REJECT

2.5 Blocking outgoing traffic

Problem: Drop all outgoing network traffic, possible do not affect incoming traffic

Solution:
iptables -F OUTPUT
iptables -A OUTPUT -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -j REJECT


Here iptables takes advantage of statefulness, iptables can tell the difference between outgoing traffic initiated from the local machine and outgoing traffic in response to established incoming connections, The latter is permitted but the former is not.

 2.6 Blocking incoming service requests

Problem: Want to block connections to a particular network service, examp HTTP

Solution:

iptables -A INPUT -p tcp --dport www -j REJECT
TO BLOCK INCOMING http TRAFFIC BUT PERMIT LOCAL HTTP traffic,

iptables -A INPUT -p tcp -i lo --dport www -j ACCEPT
iptables -A INPUT -p tcp --dport www -j REJECT


2.7 Blocking Access from a remote host

Problem: Need to block incoming traffic from a particular host

Solution:

Block all access by that host
# iptables -A INPUT -s remote_ip_address -j REJECT

To block request for one particular service, say the SMTP mail service:

# iptables -A INPUT -p tcp -s remote_ip_address --dport 

  smtp -j REJECT

To admit some hosts but block all others:

# iptables -A INPUT -s ip_address_1 [-p protocol --dport service] -j ACCEPT
 

# iptables -A INPUT -s ip_address_2 [-p protocol --dport service] -j ACCEPT
 

# iptables -A INPUT -s ip_address_3 [-p protocol --dport service] -j ACCEPT
 

# iptables -A INPUT [-p protocol --dport service] -j REJECT
 
2.8 Blocking access to a remote host

Problem: You want to block outgoing traffic to a particular host,

Solution:

 To block all access,

# iptables -A OUTPUT -d remote_ip_address -j REJECT

To block a particular service, such as a remote web site:

# iptables -A OUTPUT -p tcp -d remote_ip_address --dport 

  www -j REJECT

2.9 Blocking outgoing access to all web servers on a 
    network

Problem: Want to prevent outgoing access to a network, eg all web servers at yahoo.com.

Solution: Figure out how to specify the yahoo.com network, eg: 64.58.76.0/24 and reject web access:

# iptables -A OUTPUT -p tcp -d 64.58.76.0/24 --dport 

  www -j REJECT

You can also specify hostname instead of ip address in your firewall rule. If DNS report multiple ip address for that  hostname, a seperate rule must create for each ip address.

# host www.google.com  ------ Will give all ip-address of

                       google.com

www.google.com has address 173.194.75.103
www.google.com has address 173.194.75.104
www.google.com has address 173.194.75.105
www.google.com has address 173.194.75.106
www.google.com has address 173.194.75.147
www.google.com has address 173.194.75.99
www.google.com has IPv6 address 2a00:1450:4013:c01::69

so better block access to www.google.com

# iptables -A OUTPUT -d www.google.com -j REJECT
# iptables -L OUTPUT

security experts recommend that you use only IP addresses in your rues, not hostnames. Since an attacker could poison your DNS and circumvent rules defined for hostnames. However the hostnames are relevent only at the moment you run iptables to define a rule, as the program looks up the underlying IP address immediately and

stores them in the rule.

2.10 Blocking Remote access, but permitting local

Problem: You want only local users to acces a TCP service: remote requests should be denied.

Solution: Permit connections via the loopback interface and reject all others

# iptables -A INPUT -p tcp -i lo --dport service -j ACCEPT
# iptables -A INPUT -p tcp --dport service -j REJECT

You can also single out your local IP address specifically:

# iptables -A INPUT -p tcp ! -s your_ip address --dport 

  service -j REJECT

2.11 Controlling access by MAC Address

Problem: You want only a particuler machine, identified by its MAC address, to access your system

Solution:

# iptables -F INPUT
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m mac --mac-source 12:34:56:89:90:ab 

  -j ACCCEPT
# iptables -A INPUT -j REJECT

This will work only within your local network. If you receive a packets from a machine outside your subnet, it will contain your gateway's MAC address, not that of the orginal source machine.

MAC address can be spoofed. Suppose you have a machine called MACHINE, whose MAC address is trusted by your firewall. If an intruder discovers this fact and MACHINE is down, the intruder could spoof MACHINE's MAC address and your firewall would be none the wiser. On the other hand if MACHINE is up during the spoofing
its kernel will start screaming(via syslog) about duplicate MAC address.


2.12 Permitting SSH Access only

Problem: you want to permit incoming SSH access but no other incoming access. Allow local connections to all services

Solutions:
# iptables -F INPUT
# iptables -A INPUT -p tcp --dport ssh -j ACCEPT
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -j REJECT

A common setup is to permit access to a remote machine only by ssh.If you want this access limited to certain hosts or networks, list them by IP address as follows,

# iptables -A INPUT -p tcp -s 128.220.13.4 --dport ssh -j ACCEPT
# iptables -A INPUT -p tcp -s 71.54.121.19 --dport ssh -j ACCEPT
# iptables -A INPUT -p tcp -s 152.16.91.0/24 --dport ssh -j

  ACCEPT
# iptables -A INPUT -j REJECT

The REJECT rule in the preceding prevents all other incoming connections. If you want to prevent only SSH connections use this REJECT rule instead

# iptables -A INPUT -p tcp --dport ssh -j REJECT

 
2.13 Prohibiting outgoing Telnet connections

Problem: You want to block all outgoing telnet connections,

Solution:
# iptables -A OUTPUT -p tcp --dport tenlet -j REJECT

To block all outgoing telnet connections except to yourself from yourself

# iptables -A OUTPUT -p tcp -o lo --dport telnet -j ACCEPT
# iptables -A OUTPUT -p tcp --dport tenet -j REJECT

2.14 Protecting Dedicated server

Problem: You want to run a specific set of services on your machine, accessible to the outside world. All other services should be rejected and logged. Internally, however, local users can access all services.

Solution: suppose your services are www,ssh,smtp

# iptables -F INPUT
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m multiport -p tcp --dport 

   www,ssh,smtp -j ACCEPT
# iptables -A INPUT -j LOG -m limit
# iptables -A INPUT -j REJECT

Local connections from your own host arrive via the loopback interface.


2.15 Preventing pings

Problem: You don't want remote sites to receive responses if they ping you,

Solution:
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Don't make the mistake of dropping all ICMP messages,

Wrong, Don't do this
# iptables -A INPUT -p icmp -j DROP

Because pings are only one type of ICMP message, and you might not want to block all types. List the available ICMP messages with
 

# iptables -p icmp -h

2.16 Listing your firewall rules

Problem: You want to see your firewall rules
 

Solution:
# iptables -L [chain]

For more detailed output, append the -v option

If iptable takes a long time to print the rule list, try appending thee -n option to disable reverse DNS lookups. Such lookups of local addresses, such as 192.168.0.2 may cause delays due to timeouts.

2.17 Deleting firewall rules

Problem: You want to delete firewall rules, individually or all at once.


Solution: To delete rules en masse, also called flushing a chain, do the following:

# iptables -F [chain]
To delete rules individually:-

# iptables -D chain rule_number
Rules are numbered beginning with 1. To list the rules,

# iptables -L

Select one to delete(say,rule 4 on the input chain), and type

# iptables -D INPUT 4

If you have previously saved your rules and want your deletions to remain in effect after the next reboot, re-save the new configuration.


2.18 Inserting firewall rule

Problem: Rather than appending a rule to a chain, you want to insert or replace one else where in the chain,


Solution: Instead of the -A option, use -I to insert or -R to replace. You'll need to know the numeric position, within the existing rules, of the new rule.
 

For instance, to insert a new rule in the fourth position in the chain:

# iptables -I chain 4 ......specification.........

To replace the second rule in a chain:

# iptables -R chain 2 ......specification......

When you insert a rule at position N in a chain, the old rule N becomes rule N+1, the rule N+1 becomes the rule N+2 and so on.

2.19 Saving a firewall configuration

Problem: you want to save your firewall configuration


Solution: Save your settings

# iptables-save > /etc/sysconfig/iptables

2.20 Loading a firewall configuration

Problem: you want to load your firewall rules, eg: at boot time


Solution: use iptables-restore. Assuming you've saved your firewall configuration in /etc/sysconfig

#!/bin/bash
echo 1 > /proc/sys/net/ipv4/ip_forward  (optional)
iptables-restore < /etc/sysconfig/iptables


to load firewall at boot time,
# chkconfig iptables on

2.21 Building complex rule trees

Problem: you want to construct complex firewall behaviors, but you are getting lost in the complexity.
 

Solution:
Be modular: isolate behaviors into their own chains. Then connect the chains in the desired manner

# iptables -N CHAIN1
# iptables -N CHAIN2
# iptables -N CHAIN3
# iptables -N CHAIN4
# iptables -N CHAIN5

Add your rules to each chain, Then connect the chains; for examp

# iptables -A INPUT ......specification...... -j CHAIN1
# iptables -A CHAIN1 ......specification...... -j CHAIN2
# iptables -A CHAIN2 ......specification...... -j CHAIN3
# iptables -A INPUT ......specification...... -j CHAIN4
# iptables -A INPUT ......specification...... -j CHAIN5

Connecting chains is like a modular programming with subroutines, the rule:

# iptables -A CHAIN1 ......specification...... -j CHAIN2

creates a jump point to CHAIN2 from this rule in CHAIN1, if the rule is satisfied. Once CHAIN2 has been traversed, control returns to the next rule in CHAIN1,similar to 

 returning from a subroutine.

2.22 Logging

Problem: You want firewall to log and drop certain packets


Solution: Create a new rule chain that logs and drops in sequence:

# iptables -N LOG_DROP
# iptables -A LOG_DROP -j LOG --log-level warning 

  --log-prefix "dropped" -m limit
# iptables -A LOG_DROP -j DROP

then use it as a target in any relevant rules:

# iptables ......specification...... -j LOG_DROP

iptables's LOG targeet causes the kernel to log packets that matches your given specification. 


The "--log-level" option sets the syslog level for these
log messages and "--log-prefix" adds an identifiable string to the log entries.

The further options "--log-prefix", "--log-tcp-sequence", "--log-tcp-options" and "--log-ip-options" affect the 
 information written to the log.

LOG is usually combined with the limit module (-m limit) to limit the number of redundant log entries made per time period, to flooding your logs.


2.23 Open port 80 and 110 in server machine

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 110 -j ACCEPT
  
Verify that port is open
 # netstat -tulpn | less

Make sute iptable is allowing port 80 / 110
 # iptables -L -n

Wednesday 19 June 2013

Iptables Help

Iptables used for packet filtering and as a firewall to some extent.

A rate limiting feature that helps iptables block some types of denial of service (DoS) attacks.

All packets inspected by iptables pass through a sequence of built-in tables (queues) for processing. Each of these queues is dedicated to a particular type of packet activity and is controlled by an associated packet


 transformation/filtering chain.

There are three tables in total:-
 

The first is the mangle table which is responsible for the alteration of quality of service bits in the TCP header. This is hardly used in a home 
 or SOHO  environment.

The second table is the filter queue which is responsible for packet filtering. It has three built-in chains in which you can place your firewall policy rules.
 

These are the:
 

Forward chain: Filters packets to servers protected by the firewall.
 

Input chain: Filters packets destined for the firewall ie, Packets coming
 towards Firewall
 

Output chain: Filters packets originating from the firewall ie, Packets 
going out from Firewall

The third table is the nat queue which is responsible for network address translation. It has two built-in chains; these are:

Pre-routing chain: NATs packets when the destination address of the packet needs to be changed.
 

Post-routing chain: NATs packets when the source address of the packet needs to be changed.

Queue-Type:       Filter
Queue-Function:  Packet filtering
Packet-Transformation-Chain-in-Queue: FORWARD
Chain-Function:  Filters packets to servers accessible by another NIC on the firewall.[if a machine has two interfaces its used FORWARD from 
 one to the other, from local machine to router to the internet.]


Queue-Type:       Filter
Queue-Function:  Packet filtering
Packet-Transformation-Chain-in-Queue: INPUT
Chain-Function: Filters packets destined to the firewall.

Queue-Type:       Filter
Queue-Function:  Packet filtering
Packet-Transformation-Chain-in-Queue: OUTPUT
Chain-Function: Filters packets originating from the firewall.

Queue-Type: Nat      
Queue-Function: Network Address Translation
Packet-Transformation-Chain-in-Queue: PREROUTING
Chain-Function: Address translation occurs before routing. Facilitates the transformation of the destination IP address to be compatible with the firewall's routing table. Used with NAT of the destination IP address,
 also known as destination NAT or DNAT.

Queue-Type: Nat      
Queue-Function: Network Address Translation
Packet-Transformation-Chain-in-Queue: POSTROUTING
Chain-Function: Address translation occurs after routing. This implies that there was no need to modify the destination IP address of the packet as in pre-routing. Used with NAT of the source IP address using either one-to-one or many-to-one NAT. This is known as source NAT, or SNAT.

Queue-Type: Nat      
Queue-Function: Network Address Translation
Packet-Transformation-Chain-in-Queue: OUTPUT
Chain-Function: Network address translation for packets generated by the firewall. (Rarely used in SOHO environments)

Queue-Type: Mangle
Queue-Function: TCP header modification
Packet-Transformation-Chain-in-Queue: PREROUTING
                                                                   POSTROUTING
                                                                   OUTPUT

                                                                   INPUT
                                                                   FORWARD

Chain-Function: Modification of the TCP packet quality of service bits before routing occurs. (Rarely used in SOHO environments) 

You need to specify the table and the chain for each firewall rule you create.
There is an exception: Most rules are related to filtering, so iptables assumes that any chain that's defined without an associated table will be a part of the filter table. The filter table is therefore the default.

EXMP:- a TCP packet from the Internet arrives at the firewall's interface on Network A to create a data connection. The packet is first examined by your rules in the mangle table's PREROUTING chain, if any. It is then inspected by the rules in the nat table's PREROUTING chain to see whether the packet requires DNAT. It is then routed.

If the packet is destined for a protected network, then it is filtered by the rules in the FORWARD chain of the filter table and, if necessary, the packet undergoes SNAT in the POSTROUTING chain before arriving at Network B.
When the destination server decides to reply, the packet undergoes the same sequence of steps.
Both the FORWARD and POSTROUTING chains may be configured to implement quality of service (QoS) features in their mangle tables.

If the packet is destined for the firewall itself, then it passes through the mangle table of the INPUT chain, if configured, before being filtered by
the rules in the INPUT chain of the filter table before. If it successfully passes these tests then it is processed by the intended application on the firewall.

At some point, the firewall needs to reply. This reply is routed and inspected by the rules in the OUTPUT chain of the mangle table, if any. Next, the rules in the OUTPUT chain of the nat table determine whether DNAT is required and the rules in the OUTPUT chain of the filter table are then inspected to help restrict unauthorized packets. Finally, before the packet is sent back to the Internet, SNAT and QoS mangling is done by the POSTROUTING chain.


   Targets And Jumps 

Each firewall rule inspects each IP packet and then tries to identify it as the target of some sort of operation. Once a target is identified, the packet needs to jump over to it for further processing.
check the built-in targets that iptables uses:-


Target : ACCEPT  
Description : * iptables stops further processing.
                 * The packet is handed over to the end application or the 

                    operating system for processing
Most-Common-Options : N/A 

Target : DROP
Description :  * iptables stops further processing.
                   * The packet is blocked. It won't return any 

                        error message to the host.
Most-Common-Options : N/A

Target : LOG
Description :  * The packet information is sent to the syslog daemon for
                      logging
                   * iptables continues processing with the next rule 
                        in the table
                   * As you can't log and drop at the same time, 
                      it is common to have two similar rules in sequence.
                    The first will log the packet, the second will drop it.

Most-Common-Options : --log-prefix "string"
              Tells iptables to prefix all log messages with 
               a user defined string. Frequently used to tell why the 
                  logged packet was dropped.

Target : REJECT
Description : * Works like the DROP target, but will also return an error 
                  message to the host sending the packet that 
                   the packet was blocked.
Most-Common-Options : --reject-with qualifier        
                      The qualifier tells what type of reject message is returned. Qualifiers include: icmp-port-unreachable (default)
                          icmp-net-unreachable
                          icmp-host-unreachable
                          icmp-proto-unreachable
                          icmp-net-prohibited
                          icmp-host-prohibited
                          tcp-reset
                          echo-reply


Target : DNAT
Description :  * Used to do destination network address translation.
                    ie. rewriting the destination IP address of the packet.
Most-Common-Options : --to-destination ipaddress
                       Tells iptables what the destination IP address should be.



Target : SNAT
Description : * Used to do source network address translation 
                 rewriting the source IP address of the packet, 
                 * The source IP address is user defined
Most-Common-Options :  
               --to-source <address>[-<address>][:<port>-<port>]
            Specifies the source IP address and ports to be used by SNAT.



Target : MASQUERADE
Description : * Used to do Source Network Address Translation.
           * By default the source IP address is the same as that used 
               by the firewall's interface

Most-Common-Options : [--to-ports <port>[-<port>]]
    Specifies the range of source ports to which the original source 

    port can be  mapped.

General Iptables Match Criteria

iptables command Switch           Desciption 

-t <-table->                 If you don't specify a table, then the filter
                                 table is assumed. As discussed before, 
                                   the possible built-in tables include: filter, nat,
                                  mangle.

-j <target>                  Jump to the specified target chain
                               when the packet matches the current rule.

-A                               Append rule to end of a chain

-F     Flush.                  Deletes all the rules in the selected table

-p <protocol-type>        Match protocol. Types include, 

                                    icmp, tcp, udp, and all

-s <ip-address>            Match source IP address

-d <ip-address>            Match destination IP address

-i <interface-name>      Match "input" interface on which 

                                    the packet enters.

-o <interface-name>     Match "output" interface on which 

                                    the packet exits
In this command switches example:-
 # iptables -A INPUT -s 0/0 -i eth0 -d 192.168.1.1  -p TCP -j ACCEPT
 
iptables is being configured to allow the firewall to accept TCP packets coming in on interface eth0 from any IP address destined for the firewall's IP address of 192.168.1.1. The 0/0 representation of an IP address means any.


Common TCP and UDP Match Criteria 

Switch                              Desciption

-p tcp --sport <port>       TCP source port. Can be a single value 
                                  or a range in the format: 
                                   start-port-number:end-port-number

-p tcp --dport <port>      TCP destination port. Can be a single 

                                value or a  range in the format: 
                                    starting-port:ending-port

-p tcp --syn                    Used to identify a new TCP connection 

                                  request. ! --syn means, not a new connection 
                                   request

-p udp --sport <port>      UDP source port. Can be a 

                                     single value or a range in  the format: 
                                    starting-port:ending-port

-p udp --dport <port>     UDP destination port. Can be a 

                                     single value or a  range in the format: 
                                   starting-port:ending-port


In this example:

# iptables -A FORWARD -s 0/0 -i eth0 -d 192.168.1.58 -o eth1 -p TCP --sport 1024:65535 --dport 80 -j ACCEPT


iptables is being configured to allow the firewall to accept TCP packets for routing when they enter on interface eth0 from any IP address and are destined for an IP address of 192.168.1.58 that is reachable via interface eth1. The source port is in the range 1024 to 65535 and the destination

port is port 80 (www/http).

Common ICMP (Ping) Match Criteria

Matches used with ---icmp-type               Desciption 

--icmp-type <type>                         The most commonly used 
                                                   types are  echo-reply and 
                                                     echo-request
In this example:

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

iptables is being configured to allow the firewall to send ICMP echo-requests (pings) and in turn, accept the expected ICMP echo-replies.

Consider another example:

# iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -i eth0 -j ACCEPT

The limit feature in iptables specifies the maximum average number of matches to allow per second. 


You can specify time intervals in the format /second, /minute, /hour, or /day, or you can use abbreviations so that 3/second is the same as 3/s.

In this example, ICMP echo requests are restricted to no more than one per second.


When tuned correctly, this feature allows you to filter unusually high volumes of traffic that characterize denial of service (DOS) attacks and Internet worms.

# iptables -A INPUT -p tcp --syn -m limit --limit 5/s -i eth0 -j ACCEPT

You can expand on the limit feature of iptables to reduce your vulnerability to certain types of denial of service attack.
 

Here a defense for SYN flood attacks was created by limiting the acceptance of TCP segments with the SYN bit set to no more than five per second.