How to install ftp server?



FTP is used to transfer the file from the source machine to any machine on any location, this is one of the original software or a protocol of TCP/IP protocol suit. It works on server client mode, it was developed for centralizing the data so that client can download their required things wherever whenever they want.
Port number of FTP is 20,21. It listens the request on port 20 and makes the connection on port 21.

Here we are using VSFTPD(Very secure FTP Demon): It is one of the original software included with red hat provides the more security then other protocol.

How to install ftp server?
#yum insall vsftpd
You can use rpm or yum to install vsftpd.

Now your server is installed, make the changes according to your need in the configuration file /etc/vsftpd/vsftpd.conf

Some Important tips for FTP Server

anonymous_enable=yes: It is a global user, through which anybody can access it. Change it to NO to disable anonymous access.
local_enable=yes: It allows the system users to access the FTP.
local_root=/var/ftp: Add this to assign home directory to all ftp users, by default this line is not in the configuration file and the ftp's home directory is the home directory of the user itself.
chroot_local_user=yes: Add this line to enable the chroot in FTP. Using this, user can not change their home directory. TO make your FTP server secure enable this feature with anonymous_enable=no.
/etc/vsftpd/userlist: It allows the user to connecct with ftp server.
/etc/vsftpd/ftpusers: It denies the suers to access ftp.
/var/log/xferlog: This file contain the logs of ftp server.

Restart the service now:
#service vsftpd restart
#chkconfig vsftpd on

If SELinux is enabled on the server, then it may create problem in making connection from the client side. Use this to allow ftp connection.
#setsebool -P ftpd_disable_trans=1

On Client's side:

GUI: Open the browser and open the URL ftp://serverIP

CLI: #ftp serverIP

Useful commands:
ls: To list the file and folders.
get filename: To download the file.
mget filename*: To download the multiple files.
put filename: To upload the file.
mput filename: To upload multiple files.

How to install MySQL


How to install MySQL

Install MySQL

#yum install mysql-server mysql php-mysql

How to configure MySQL

Set the MySQL service to start on boot

#chkconfig --levels 235 mysqld on

Start the MySQL service

#service mysqld start

Log into MySQL

#mysql -u root

Set the root user password for all local domains
#SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new-password');
#SET PASSWORD FOR 'root'@'localhost.localdomain' = PASSWORD('new-password');
#SET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('new-password');


Drop the Any user
#DROP USER ''@'localhost';
#DROP USER ''@'localhost.localdomain';

Exit MySQL
exit


Forgotten MySQL Root Password

Stop the mysql daemon
#mysqld_safe --skip-grant-tables
#mysql --user=root mysql
>update user set Password=PASSWORD('new-password') where user='root';
>flush privileges;
>exit;

Sending SMS Notifications From Nagios


Sending SMS Notifications From Nagios
In my last article I have discuses how to install Gnokii for sending/receiving SMS from your computer. Today I'll explain how we are using Gnokii + Nagios for sending SMS notifications to our cell phones. Its a great way to get notify of the problems while on road.

I assume that you have working Nagios and its monitoring the devices in your infrastructure and sending notifications via Email and you are looking how to get these problem notifications on your phones.

Gnokii is also working and you can send SMS from CLI.

Lets cut it short and back to actual business.

In my setup we have Nagios and Gnokii install on same host running Centos 5.4, but it can easily be followed for any other Linux distro or even with setup where Gnokii is install on separate host.

1. Make sure you can send SMS from CLI with "gnokii --sendsms +92xxxxx" using root or the user under which Nagios process is running normally its 'nagios' user, sending under nagios user requires to add nagios to groups which have permission to access the device files.

a) So add nagios to 'uucp' group (you can do this with usermod command)

Gnokii also acquire a lock under /var/lock

b) So add nagios user to 'lock' group also.

su to nagios user and send sms from CLI using gnokii --sendsms, when it works move forward for defining commands.

2. Define command for send notification via SMS in commands.cfg

# 'notify-service-by-sms' command definition
define command{
command_name notify-service-by-sms
command_line /usr/bin/printf "%.120s" "*** Nagios Alert*** $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$" | /usr/local/bin/gnokii --sendsms $CONTACTPAGER$
}

# 'notify-host-by-sms' command definition
define command{
command_name notify-host-by-sms
command_line /usr/bin/printf "%.120s" "*** Nagios Alert*** $NOTIFICATIONTYPE$ : Host $HOSTALIAS$ is $HOSTSTATE$" | /usr/local/bin/gnokii --sendsms $CONTACTPAGER$
}

3. Modify contacts.cfg and add or modify a contact by calling new commands

define contact{
contact_name askarali
use generic-contact
alias Askar Ali Khan
email emailaddress
pager +92xxxxxx
service_notification_commands notify-service-by-email,notify-service-by-sms
host_notification_commands notify-host-by-email,notify-host-by-sms
}

The key in the contact detail is the service/host notifications commands

service_notification_commands notify-service-by-email,notify-service-by-sms
host_notification_commands notify-host-by-email,notify-host-by-sms

I have configured a contact so that he can receive notifications via Email 'notify-service-by-email' as well as via SMS 'notify-service-by-sms'


That's all, finally reload nagios, before reload better to run syntax check

'nagios -v PathTo nagios.cfg'

and then reload

/etc/init.d/nagios reload

Now Nagios will send SMS notifications on your phone whenever there is problem with any host/service which being monitor with Nagios.

I hope this could help.

Webmin in Details


To install webmin, follow the following steps.
1. Download the tarball, webmin.x.x.x.tar.gz
2. unzip it, tar -zxvf webmin.x.x.x.tar.gz
3. cd webmin.x.x.x
4. Run the following command and provide necessary informations

./setup.sh /usr/local/webmin

If you want to uninstall, then...

/etc/webmin/uninstall.sh

Thats all. Enjoy

Installing webmin in freeBSD
To install webmin, update your ports, enter:
# portsnap fetch update

Install webmin from /usr/ports/sysutils/webmin, enter:
# cd /usr/ports/sysutils/webmin
# make install clean

Configure webmin
Now, webmin is installed. Start webmin on startup, enter:
# vi /etc/rc.conf
Append following line:
webmin_enable="YES"

You need to run /usr/local/lib/webmin/setup.sh script in order to setup the various config
files, enter:
# /usr/local/lib/webmin/setup.sh

https://your-domain.com:10000/

Changing your webmin passwords

It’s not unusual that, as your FreeBSD server is so stable, you end not knowing what your password was.
Under other systems the location of webmin is clear and most of the documentation will point you to /usr/libexec/webmin or something like that, in FreeBSD, by default (and after some updates) webmin is installed under
/usr/local/lib/webmin-1.300
Where 1.300 is the running version
And it’s configuration file is located at:
/usr/local/etc/webmin
So, to change the password of let’s say user foo to bar you’ll have to type:
/usr/local/lib/webmin-1.300/changepass.pl /usr/local/etc/webmin foo bar

Script for daily SARG reports


SARG is Squid Analysis Report Generator is a tool that allow you to view "where" your users are going to on the Internet. http://sarg.sourceforge.net/

If you want to generate daily reports from Squid proxy server logs, create script:

#!/bin/bash

#Get current date
TODAY=$(date +%d/%m/%Y)

#Get yesterday's date
YESTERDAY=$(date --date yesterday +%d/%m/%Y)

/usr/bin/sarg -z -d $YESTERDAY-$TODAY > /dev/null 2>&1

exit 0

And add it to cron jobs:

55 23 * * * /scripts/sarg_daily_report

And restart cron

Postfix - Blocking spam before it enters the server


Postfix - blocking spam before it enters the server

Posted in DNSBL E-mail E-mail spam Extended SMTP Mail transfer agents Postfix Spam filtering
When i first setup the server part 1 and part 2 i used the basic setting for postfix but soon found that i could reduce the amount of spam and load on the server by rejecting it before accepting it, i will do this by forcing mail servers that wanna deliver mail to me to be configured correctly and by using a few RBL (Real-time Blacklists).

Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" or manually edit "/etc/postfix/main.cf"

Below is my new config file - obviously change the IP's to your IP's and the domains to yours.

########################################################
inet_protocols = all
inet_interfaces = 127.0.0.1, 192.168.0.200, [2001:470:1f09:d2b::220], [::1]
smtp_bind_address = 192.168.0.200
smtp_bind_address6 = [2001:470:1f09:d2b::220]
myorigin = $mydomain
mynetworks = 127.0.0.0/8, 192.168.0.200, [2001:470:1f09:d2b::/64], [::1/128]
myhostname = mail.example.com
mydomain = example.com
mydestination = $myhostname, $mydomain, localhost.$mydomain, localhost

virtual_alias_domains = example.co.uk, example2.com, example3.com, example2.co.uk
virtual_alias_maps = hash:/etc/postfix/virtual

smtpd_delay_reject = yes
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_hostname, reject_invalid_hostname, permit

smtpd_sender_restrictions =permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain, permit

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_invalid_hostname, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit

policyd-spf_time_limit = 3600
smtpd_client_restrictions = permit_tls_all_clientcerts, reject_unauth_pipelining

2bounce_notice_recipient = webmaster@example.com
error_notice_recipient = webmaster@example.com
bounce_notice_recipient = webmaster@example.com

smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_tls_key_file = /etc/postfix/ssl/key.pem
smtpd_tls_cert_file = /etc/postfix/ssl/mail.example.com.pem
smtpd_tls_CAfile = /etc/postfix/ssl/sub.class1.server.ca.pem
smtpd_error_sleep_time = 5s

smtp_use_tls = yes
smtpd_tls_auth_only = no
smtp_tls_note_starttls_offer = yes
smtpd_use_tls = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s

tls_random_source = dev:/dev/urandom
disable_vrfy_command = yes
unknown_client_reject_code = 550
unknown_hostname_reject_code = 550
unknown_address_reject_code = 550

some people might say this is quite restrictive as it will block any mail server that is mis-configured or using a dynamic ip, or been blocked for sending spam but i have found it blocks 95% of the spam i was receiving beforehand without using a spam filter (thus reducing the load on the server) and i haven't seen any downsides as all legit mail is getting through fine.

I'll try and explain what the main changes are. There are 3 main sections I changed "smtpd_helo_restrictions", "smtpd_sender_restrictions" and "smtpd_recipient_restrictions"

smtpd_sender_restrictions =permit_sasl_authenticated, permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain, permit
This allows my networks and users that have authenticated themselves to connect but blocks any servers that haven't configured a valid hostname for there mail server (should always use a proper domain name i.e. myhostname = mail.example.com) and also stops people trying to relay mail through my server.

smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_hostname, reject_invalid_hostname, permit
When mail servers communicate with each other they say hello and identify themselves, this setting allows my networks to connect but blocks any servers that haven't configured a valid hostname for there mail server (should always use a proper domain name i.e. myhostname = mail.example.com)

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, reject_invalid_hostname, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit
This setting does the same as the above commands except it rejects mail servers that have been listed on RBL (Real-time Blacklists) you can google for more RBL lists but these do just fine for me.
I use dnsbl.sorbs.net, zen.spamhaus.org and bl.spamcop.net

If you want a more detailed explanation of what each option does have a read of Postfix Configuration Parameters it lists every option going.

I have also setup SPF checking and a white-list just in-case a valid email server gets on the RBL list. SPF can be studied in previous article.

Postfix - whitelisting and spf filtering



Postfix - whitelisting and spf filtering

The whitelist will allow me to manually allow any mail servers to bypass the spf filtering and RBL(Real-time Blacklists) lists.

What does SPF filtering do? Suppose a spammer forges a Hotmail.com address and tries to spam you. They connect from somewhere other than Hotmail. When his message is sent, you see MAIL FROM: , but you don't have to take his word for it. You can ask Hotmail if the IP address comes from their network.
(In this example) Hotmail publishes an SPF record. That record tells you how to find out if the sending machine is allowed to send mail from Hotmail. If Hotmail says they recognize the sending machine, it passes, and you can assume the sender is who they say they are. If the message fails SPF tests, it's a forgery. That's how you can tell it's probably a spammer.

Now time to start setting everything, for the spf filtering we need to install a few packages so start with

yum --enable epel install python-dns python-pydns

we also need "pyspf". check for any updates from here
Then install it, you need to be the root user (change the version numbers if theirs an update)

#wget http://sourceforge.net/projects/pymilter/files/pyspf/pyspf-2.0.5/pyspf-2.0.5.tar.gz/download
#tar xvfz pyspf-2.0.5.tar.gz
#cd pyspf-2.0.5/
#python setup.py build
#python setup.py install

Finally we need "pypolicyd-spf". check for any updates from here
Then install it, you need to be the root user (change the version numbers if theirs an update)

#wget http://launchpad.net/pypolicyd-spf/0.8/0.8.0/+download/pypolicyd-spf-0.8.0.tar.gz
#tar xvfz pypolicyd-spf-0.8.0.tar.gz
#cd pypolicyd-spf-0.8.0/
#python setup.py build
#python setup.py install

Now everything is install I need to tell postfix to use it. Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" or manually edit "/etc/postfix/main.cf"

Now find "smtpd_recipient_restrictions = ", and add "check_client_access hash:/etc/postfix/rbl_override_whitelist, check_policy_service unix:private/policyd-spf," after "reject_unauth_destination,"
It is important that you add it AFTER reject_unauth_destination or else your system can become an open relay!
It should look like this.

smtpd_recipient_restrictions = permit_mynetworks, permit_inet_interfaces, permit_sasl_authenticated, reject_unauth_pipelining, reject_invalid_hostname, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_client_access hash:/etc/postfix/rbl_override_whitelist, check_policy_service unix:private/policyd-spf, reject_rbl_client dnsbl.sorbs.net, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, permit

Now I need to edit "/etc/postfix/master.cf". Since i use Webmin i just navigate to "servers", "Posfix Mail server" then click "Edit Config Files" and select "master.cf" from the drop box at the top.

Now i add at the end

policyd-spf  unix  -       n       n       -       0       spawn
                   user=nobody argv=/usr/bin/policyd-spf

The leading spaces before user=nobody are important so Postfix knows this line belongs to the previous one.

The last thing i need to do is create the whitelist file, so login as root

#cd /etc/postfix
#vi /etc/postfix/rbl_override_whitelist

Then add all ip addresses or hostname that you want whitelisted (one per line only)
here what it should look like

1.2.3.4 OK
mail.example.net OK

After you create/modify the file you need to run

#postmap /etc/postfix/rbl_override_whitelist

Finally restart postfix

#/etc/init.d/postfix restart

Now send a test message from an external email account to test, if the email doesn't arrive check the logs for any errors (something you should do regularly anyway).

Hopefully everything is working fine and you should start seeing a drop in forged emails, don't forget to create a spf record for your domain so other servers can check your emails. There is a easy to use wizard to help create the record for you.
This is what my record looks like

v=spf1 a ip4:195.242.236.240 ip4:85.234.148.232/30 ip4:85.234.148.236 ip6:2001:470:1f09:d2b::/64 ip6:2001:470:1f09:81e::/64 -all

It basically lists all the ip address that are allowed to send email for my domain and says reject everything else.
If you wanna check if a particulate site has an spf record or you want to check if its working correctly, you can check from http://www.kitterman.com/spf/validate.html

Sendmail and Dovecot Configurations


Install Sendmail and Dovecot

Code:
[root@sendmail ~]# yum install sendmail*
[root@sendmail mail]# yum install dovecot


Verify the installation and compilation options

Code:
[root@sendmail ~]# rpm -qa|grep sendmail
sendmail-8.13.8-2.el5
sendmail-cf-8.13.8-2.el5
sendmail-doc-8.13.8-2.el5
sendmail-devel-8.13.8-2.el5


Code:
[root@sendmail ~]# sendmail -d0.1 -bv
Version 8.13.8
 Compiled with: DNSMAP HESIOD HES_GETMAILHOST LDAPMAP LOG MAP_REGEX
                MATCHGECOS MILTER MIME7TO8 MIME8TO7 NAMED_BIND NETINET NETINET6
                NETUNIX NEWDB NIS PIPELINING SASLv2 SCANF SOCKETMAP STARTTLS
                TCPWRAPPERS USERDB USE_LDAP_INIT

============ SYSTEM IDENTITY (after readcf) ============
      (short domain name) $w = sendmail
  (canonical domain name) $j = sendmail.example.com
         (subdomain name) $m = example.com
              (node name) $k = sendmail.example.com
========================================================

This command will show the compiled options of sendmail.


Configuration

Code:
[root@sendmail mail]# cd /etc/mail/

[root@sendmail mail]# vi local-host-names


this file will contain the domain names for which the send mail server is going to serve

Code:
# local-host-names - include all aliases for your machine here.
example.com

Edit the mc file

Code:
[root@sendmail mail]# vi sendmail.mc

Code:
dnl # Following line is optional. If you want ot relay the mails through another server, use the next line

define(`SMART_HOST', `relayserver.example.com')dnl

dnl #
dnl # The following allows relaying if the user authenticates, and disallows
dnl # plaintext authentication (PLAIN/LOGIN) on non-TLS links
dnl #
dnl define(`confAUTH_OPTIONS', `A p')dnl
dnl #
dnl # PLAIN is the preferred plaintext authentication method and used by
dnl # Mozilla Mail and Evolution, though Outlook Express and other MUAs do
dnl # use LOGIN. Other mechanisms should be used if the connection is not
dnl # guaranteed secure.
dnl # Please remember that saslauthd needs to be running for AUTH.
dnl #
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl

dnl # The following causes sendmail to only listen on the IPv4 loopback address
dnl # 127.0.0.1 and not on any other network devices. Remove the loopback
dnl # address restriction to accept email from the internet or intranet.
dnl #
dnl # DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl

This step is also optional. If relay server need an authentication provide the credantials here

Code:
[root@sendmail mail]# vi access


Code:
AuthInfo:relay.dnsexit.com "U:USERNAME" "P:PASSWORD" "M:PLAIN"

Add a user and set password

Code:
[root@sendmail mail]# useradd -s /sbin/nologin senthil
[root@sendmail mail]# passwd senthil
Changing password for user senthil.
New UNIX password:
BAD PASSWORD: it is too short
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

Map the mails for users. This will be required when more number of users and more domains are hosted in the same server

[CODE]
Code:
[root@sendmail mail]# vi virtusertable
Code:
senthil@example.com     senthil

Configure Dovecot

Code:
[root@sendmail mail]# vi /etc/dovecot.conf

Code:
protocols = imap pop3

create the sendmail cf file with mc file

Code:
[root@sendmail mail]# m4 sendmail.mc > sendmail.cf
[root@sendmail mail]# make

Start the services

Code:
[root@sendmail mail]# /etc/init.d/sendmail start
[root@sendmail mail]# /etc/init.d/saslauthd start
[root@sendmail mail]# /etc/init.d/dovecot start

Make required services permanent (after a reboot they start automatically)

Code:
[root@sendmail mail]# chkconfig sendmail on
[root@sendmail mail]# chkconfig dovecot on
[root@sendmail mail]# chkconfig saslauthd on

As of now the sendmail server is ready. The server can be accessed by outlook or any mail client.

It will be very nice if are having a imap webmail client. I prefer Roundcube. The previous version of Roundcube was having some security holes(Before 2 years). But the current stable version seems to be secured.

Round cube requires mysql support and php greater than 5.2.0.

The current version of Php is 5.1.6 so have to update php version.

Updating PHP

Code:
[root@sendmail round]# php -v


Code:
PHP 5.1.6 (cli) (built: Mar 14 2007 18:56:07)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
Code:
[root@sendmail ~]# cd /etc/yum.repos.d

Code:
[root@sendmail ~]# wget dev.centos.org/centos/5/CentOS-Testing.repo

Code:

[root@sendmail ~]# yum --disablerepo=* --enablerepo=c5-testing update php  php-xml php-mysql

Code:
[root@sendmail round]# php -v

Code:
PHP 5.2.10 (cli) (built: Nov 13 2009 11:24:03)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
Install Mysql And set root password

Code:
yum install mysql mysql-server

/usr/bin/mysqladmin -u root password 'mysqlrootpassword'

Download Round cube Stable version and extract it

Code:
[root@sendmail ~]# cd /tmp/
[root@sendmail ~]# wget nchc.dl.sourceforge.net/project/roundcubemail/roundcubemail/0.3.1/roundcubemail-0.3.1.tar.gz
[root@sendmail ~]# tar -zxvf roundcubemail-0.3.1.tar.gz
[root@sendmail ~]# mv roundcube /usr/share/
[root@sendmail ~]# vi /etc/httpd/conf/roundcube.conf

Inside this file add as follows,

Code:
<IfModule mod_alias.c>
Alias /rcm /usr/share/roundcube
</IfModule>
<Directory /usr/share/roundcube>
   Options None
   Order allow,deny
   allow from all
</Directory>

Code:
[root@sendmail ~]# vi /etc/httpd/conf/httpd.conf

add the following line,

Code:
Include /etc/httpd/conf/roundcube.conf

Set Some permissions

Code:
[root@sendmail ~]# chown -R root:apache /usr/share/roundcube/
[root@sendmail ~]# cd /usr/share/roundcube/
[root@sendmail ~]# chmod g+w temp/
[root@sendmail ~]# chmod g+w logs/

Create Database for Round cube in Mysql

Code:
[root@sendmail ~]# mysql -u root -p

Code:
mysql> create database roundcube;
mysql> show databases;
mysql> create user roundcube;
mysql> GRANT ALL PRIVILEGES ON roundcube.* TO roundcube@localhost IDENTIFIED BY 'roundcube';
mysql> FLUSH PRIVILEGES;
mysql> quit;

restart http

Code:
[root@sendmail ~]# /etc/init.d/httpd restart

In the browser,

Code:
yourserverip/rcm/installer/

Click the "START INSTALLATION" button
These are all very simple forms in the browser. I cant enter all the options because the limited characters. Please contact me if there is any difficulties in filling those options.

General configuration, Database setup, IMAP Settings, SMTP Settings

Then click next

The installer will generate two configuration files for you,

Copy these contents (files) in side the /usr/share/roundcube/config

Code:
[root@sendmail ~]# vi main.inc.php
[root@sendmail ~]# vi db.inc.php

The installer directory should be moved to some other path.
Code:
[root@sendmail ~]# mv installer/ /tmp/

IPTABLES Examples


1. Delete Existing Rules

Before you start building new set of rules, you might want to clean-up all the default rules, and existing rules. Use the iptables flush command as shown below to do this.

iptables -F
(or)
iptables --flush

2. Set Default Chain Policies

The default chain policy is ACCEPT. Change this to DROP for all INPUT, FORWARD, and OUTPUT chains as shown below.

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
When you make both INPUT, and OUTPUT chain’s default policy as DROP, for every firewall rule requirement you have, you should define two rules. i.e one for incoming and one for outgoing.

In all our examples below, we have two rules for each scenario, as we’ve set DROP as default policy for both INPUT and OUTPUT chain.

If you trust your internal users, you can omit the last line above. i.e Do not DROP all outgoing packets by default. In that case, for every firewall rule requirement you have, you just have to define only one rule. i.e define rule only for incoming, as the outgoing is ACCEPT for all packets.

Note: If you don’t know what a chain means, you should first familiarize yourself with the IPTables fundamentals.

3. Block a Specific ip-address

Before we proceed further will other examples, if you want to block a specific ip-address, you should do that first as shown below. Change the “x.x.x.x” in the following example to the specific ip-address that you like to block.

BLOCK_THIS_IP="x.x.x.x"
iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP
This is helpful when you find some strange activities from a specific ip-address in your log files, and you want to temporarily block that ip-address while you do further research.

You can also use one of the following variations, which blocks only TCP traffic on eth0 connection for this ip-address.

iptables -A INPUT -i eth0 -s "$BLOCK_THIS_IP" -j DROP
iptables -A INPUT -i eth0 -p tcp -s "$BLOCK_THIS_IP" -j DROP

4. Allow ALL Incoming SSH

The following rules allow ALL incoming ssh connections on eth0 interface.

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
Note: If you like to understand exactly what each and every one of the arguments means, you should read How to Add IPTables Firewall Rules

5. Allow Incoming SSH only from a Sepcific Network

The following rules allow incoming ssh connections only from 192.168.100.X network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
In the above example, instead of /24, you can also use the full subnet mask. i.e “192.168.100.0/255.255.255.0″.

6. Allow Incoming HTTP and HTTPS

The following rules allow all incoming web traffic. i.e HTTP traffic to port 80.

iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
The following rules allow all incoming secure web traffic. i.e HTTPS traffic to port 443.

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

7. Combine Multiple Rules Together using MultiPorts

When you are allowing incoming connections from outside world to multiple ports, instead of writing individual rules for each and every port, you can combine them together using the multiport extension as shown below.

The following example allows all incoming SSH, HTTP and HTTPS traffic.

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

8. Allow Outgoing SSH

The following rules allow outgoing ssh connection. i.e When you ssh from inside to an outside server.

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

Please note that this is slightly different than the incoming rule. i.e We allow both the NEW and ESTABLISHED state on the OUTPUT chain, and only ESTABLISHED state on the INPUT chain. For the incoming rule, it is vice versa.

9. Allow Outgoing SSH only to a Specific Network

The following rules allow outgoing ssh connection only to a specific network. i.e You an ssh only to 192.168.100.0/24 network from the inside.

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

10. Allow Outgoing HTTPS

The following rules allow outgoing secure web traffic. This is helpful when you want to allow internet traffic for your users. On servers, these rules are also helpful when you want to use wget to download some files from outside.

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

Note: For outgoing HTTP web traffic, add two additional rules like the above, and change 443 to 80.

11. Load Balance Incoming Web Traffic

You can also load balance your incoming web traffic using iptables firewall rules.

This uses the iptables nth extension. The following example load balances the HTTPS traffic to three different ip-address. For every 3th packet, it is load balanced to the appropriate server (using the counter 0).

iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

12. Allow Ping from Outside to Inside

The following rules allow outside users to be able to ping your servers.

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

13. Allow Ping from Inside to Outside

The following rules allow you to ping from inside to any of the outside servers.

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

14. Allow Loopback Access

You should allow full loopback access on your servers. i.e access using 127.0.0.1

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

15. Allow Internal Network to External network.

On the firewall server where one ethernet card is connected to the external, and another ethernet card connected to the internal servers, use the following rules to allow internal network talk to external network.

In this example, eth1 is connected to external network (internet), and eth0 is connected to internal network (For example: 192.168.1.x).

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

16. Allow outbound DNS

The following rules allow outgoing DNS connections.

iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT
iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT

17. Allow NIS Connections

If you are running NIS to manage your user accounts, you should allow the NIS connections. Even when the SSH connection is allowed, if you don’t allow the NIS related ypbind connections, users will not be able to login.

The NIS ports are dynamic. i.e When the ypbind starts it allocates the ports.

First do a rpcinfo -p as shown below and get the port numbers. In this example, it was using port 853 and 850.

rpcinfo -p | grep ypbind
Now allow incoming connection to the port 111, and the ports that were used by ypbind.

iptables -A INPUT -p tcp --dport 111 -j ACCEPT
iptables -A INPUT -p udp --dport 111 -j ACCEPT
iptables -A INPUT -p tcp --dport 853 -j ACCEPT
iptables -A INPUT -p udp --dport 853 -j ACCEPT
iptables -A INPUT -p tcp --dport 850 -j ACCEPT
iptables -A INPUT -p udp --dport 850 -j ACCEPT
The above will not work when you restart the ypbind, as it will have different port numbers that time.

There are two solutions to this: 1) Use static ip-address for your NIS, or 2) Use some clever shell scripting techniques to automatically grab the dynamic port number from the “rpcinfo -p” command output, and use those in the above iptables rules.

18. Allow Rsync From a Specific Network

The following rules allows rsync only from a specific network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT

19. Allow MySQL connection only from a specific network

If you are running MySQL, typically you don’t want to allow direct connection from outside. In most cases, you might have web server running on the same server where the MySQL database runs.

However DBA and developers might need to login directly to the MySQL from their laptop and desktop using MySQL client. In those case, you might want to allow your internal network to talk to the MySQL directly as shown below.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT

20. Allow Sendmail or Postfix Traffic

The following rules allow mail traffic. It may be sendmail or postfix.

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

21. Allow IMAP and IMAPS

The following rules allow IMAP/IMAP2 traffic.

iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT
The following rules allow IMAPS traffic.

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

22. Allow POP3 and POP3S

The following rules allow POP3 access.

iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT
The following rules allow POP3S access.

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

23. Prevent DoS Attack

The following iptables rule will help you prevent the Denial of Service (DoS) attack on your webserver.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

In the above example:

-m limit: This uses the limit iptables extension
–limit 25/minute: This limits only maximum of 25 connection per minute. Change this value based on your specific requirement
–limit-burst 100: This value indicates that the limit/minute will be enforced only after the total number of connection have reached the limit-burst level.

24. Port Forwarding

The following example routes all traffic that comes to the port 442 to 22. This means that the incoming ssh connection can come from both port 22 and 422.

iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22
If you do the above, you also need to explicitly allow incoming connection on the port 422.

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

25. Log Dropped Packets

You might also want to log all the dropped packets. These rules should be at the bottom.

First, create a new chain called LOGGING.

iptables -N LOGGING
Next, make sure all the remaining incoming connections jump to the LOGGING chain as shown below.

iptables -A INPUT -j LOGGING
Next, log these packets by specifying a custom “log-prefix”.

iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7

Finally, drop these packets.

iptables -A LOGGING -j DROP

Linux OID's for CPU,Memory and Disk Statistics


SNMP Basics

SNMP stands for Simple Network Management Protocol and consists of three key components: managed devices, agents, and network-management systems (NMSs). A managed device is a node that has an SNMP agent and resides on a managed network. These devices can be routers and access server, switches and bridges, hubs, computer hosts, or printers. An agent is a software module residing within a device. This agent translates information into a compatible format with SNMP. An NMS runs monitoring applications. They provide the bulk of processing and memory resources required for network management.

MIBs, OIDs Overview

MIB stands for Management Information Base and is a collection of information organized hierarchically. These are accessed using a protocol such as SNMP. There are two types of MIBs: scalar and tabular. Scalar objects define a single object instance whereas tabular objects define multiple related object instances grouped in MIB tables.

OIDs or Object Identifiers uniquely identify manged objects in a MIB hierarchy. This can be depicted as a tree, the levels of which are assigned by different organizations. Top level MIB object IDs (OIDs) belong to different standard organizations. Vendors define private branches including managed objects for their own products.

Here is a sample structure of an OID

Iso (1).org(3).dod(6).internet(1).private(4).transition(868).products(2).chassis(4).card(1).slotCps(2)­
.­cpsSlotSummary(1).cpsModuleTable(1).cpsModuleEntry(1).cpsModuleModel(3).3562.3

Most of the people may be looking for OID's for Linux OID's for CPU,Memory and Disk Statistics for this first you need to install SNMP server and clients. If you want to install SNMP server and client installation in linux check here

 CPU  Statistics

        Load
               1 minute Load: .1.3.6.1.4.1.2021.10.1.3.1
               5 minute Load: .1.3.6.1.4.1.2021.10.1.3.2
               15 minute Load: .1.3.6.1.4.1.2021.10.1.3.3

       CPU
               percentage of user CPU time:    .1.3.6.1.4.1.2021.11.9.0
               raw user cpu time:                  .1.3.6.1.4.1.2021.11.50.0
               percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
               raw system cpu time:              .1.3.6.1.4.1.2021.11.52.0
               percentages of idle CPU time:   .1.3.6.1.4.1.2021.11.11.0
               raw idle cpu time:                   .1.3.6.1.4.1.2021.11.53.0
               raw nice cpu time:                  .1.3.6.1.4.1.2021.11.51.0

Memory Statistics

               Total Swap Size:                .1.3.6.1.4.1.2021.4.3.0
               Available Swap Space:         .1.3.6.1.4.1.2021.4.4.0
               Total RAM in machine:          .1.3.6.1.4.1.2021.4.5.0
               Total RAM used:                  .1.3.6.1.4.1.2021.4.6.0
               Total RAM Free:                   .1.3.6.1.4.1.2021.4.11.0
               Total RAM Shared:                .1.3.6.1.4.1.2021.4.13.0
               Total RAM Buffered:              .1.3.6.1.4.1.2021.4.14.0
               Total Cached Memory:           .1.3.6.1.4.1.2021.4.15.0

Disk Statistics

       The snmpd.conf needs to be edited. Add the following (assuming a machine with a single '/' partition):

                               disk    /       100000  (or)

                               includeAllDisks 10% for all partitions and disks

       The OIDs are as follows

               Path where the disk is mounted:                 .1.3.6.1.4.1.2021.9.1.2.1
               Path of the device for the partition:            .1.3.6.1.4.1.2021.9.1.3.1
               Total size of the disk/partion (kBytes):        .1.3.6.1.4.1.2021.9.1.6.1
               Available space on the disk:                      .1.3.6.1.4.1.2021.9.1.7.1
               Used space on the disk:                           .1.3.6.1.4.1.2021.9.1.8.1
               Percentage of space used on disk:             .1.3.6.1.4.1.2021.9.1.9.1
               Percentage of inodes used on disk:            .1.3.6.1.4.1.2021.9.1.10.1

Examples

These Commands you need to run on the SNMP server

Get available disk space for / on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.9.1.7.1

this will return available disk space for the first entry in the 'disk' section of snmpd.conf; replace 1 with n for the nth entry

Get the 1-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.1

Get the 5-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.2

Get the 15-minute system load on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.10.1.3.3

Get amount of available swap space on the target host

#snmpget -v 1 -c "community" target_name_or_ip .1.3.6.1.4.1.2021.4.4.0


Linux OID's for CPU,Memory and Disk Statistics