How to password protect the single user mode in Linux

terminal-glossy.jpgOne of the very compromising situation arising with a Linux box with a slack physical security easy access to anyone to the linux box – is one were a malicious user boots into an un protected single user mode and changes your root password. This can be prevented by making your linux machine to ask for the root password even when the system is made to boot into single user mode. The below given tip lets you achieve this goal.
How to implement this Tip?

1. From your Linux machine access a terminal window and open /etc/inittab file for edit.

2. In this file add the below given line just before the id:X:initdefault: entry 
su:S:wait:/sbin/sulogin

3. Save the /etc/ininttab file.

4. Now from next time onwards you will be prompted to provide the root password before accessing the single user mode.

How to List perl modules installed on my system?

List installed perl module

To display the list enter the following command:
$ instmodsh
Output:
Available commands are:
l            - List all installed modules
m    - Select a module
q            - Quit the program
cmd?
At cmd? prompt type l to list all installed modules:
cmd? l

Net cat tricks

Few Useful Netcat Tricks

I always say that small, simple and self contained tools can often be more useful, and more feature rich than huge bloated frameworks. For example lets take legendary “Swiss Army Knife of Networking” - netcat. It is a single binary, which takes up about 60KB of space on your disk (give or take a few KB depending on where and how you compile it). What can it do?


Port Scanner
Netcat can be a port scanner. It does not have as many features as say nmap, but if you just want to see what ports are open on a given machine, you can simply do:

nc -v -w 1 localhost -z 1-3000

The command above will scan all the ports in the range 1-3000 on localhost.


Chat Server

Have you even needed an improvised one-on-one chat? Netcat can do that too. You simply start listening to connections on some port like this:

nc -lp 1337

Then on another machine simply connect to that port:

nc 10.48.2.40 1337

Now start typing on either machine. When you press enter, the line will immediately show up on the other machine.
Telnet Server

Nectat can also be used to set up a telnet server in a matter of seconds. You can specify the shell (or for that matter any executable) you want netcat to run at a successful connection with the -e parameter:
nc -lp 1337 -e /bin/bash
On windows you can use:
nc -lp 1337 -e cmd.exe
Then on a client machine simply connect to port 1337 and you will get full access to the shell, with the permissions of the user who ran nc on the server.
Spoofing HTTP Headers
You can use netcat to connect to a server using completely spoofed headers. You can actually type out your user agent, referrer and etc. It’s useful when you want to generate bunch of hits that can be easily found in the logs or something like that:
nc google.com 80
GET / HTTP/1.1
Host: google.com
User-Agent: NOT-YOUR-BUSINESS
Referrer: YOUR-MOM.COM
Note that your request won’t be sent until you generate a blank line. So hit return twice when your are done typing. You will get a response of headers and HTML streaming down your screen:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=79f8f28c854d90ec:TM=1186369443:LM=1186369443:S=UIiTvi68MtmbcmGl; expires=Sun, 1
-Jan-2038 19:14:07 GMT; path=/; domain=.google.com
Server: GWS/2.1
Transfer-Encoding: chunked
Date: Mon, 06 Aug 2007 03:04:03 GMT
738
I deleted the HTML that followed the response - but you get the idea. It is also a good way of looking at headers. Some sites have nice surprises there (like slashdot’s X-Bender and X-Fry headers). Seriously, check them out!

Web Server

I think this is my favorite trick. Did you ever need to set up simple makeshift webserver that would serve a single page? I know I did. In the past when my web server at work melted down, I set up laptop with this simple script:
while true; do nc -l -p 80 -q 1 < error.html; done
The error.html page was just a very simple error message notifying our users about the outage, and giving them an estimate of when it would be fixed. It took me 3 minutes to set up, and probably saved us many angry support calls.

Cloning Hard Drive Partitions Over the Network
This trick was submitted by Craig in the comments. On a system you want to clone do:
dd if=/dev/sda | nc 192.168.0.1 9000
Where 9000 is some random port. On the receiving side di:
nc -l -p 9000 | dd of=/dev/sda
Of course you need to have the cloned partitions unmounted on both systems. So if you are cloning / you will have to boot from a live distro like Knoppix. Note that you can use this technique to clone NTFS partitions as well - just need to use a live Linux distro on both sides.

Snort Install Guide for Red Hat Enterprise Linux 5

Snort Install Guide for Red Hat Enterprise Linux 5 to log to MySQL Database

Written by kammo on August 3rd, 2008 This guide is intended for users who are using Red Hat Enterprise Linux 5, but this should work fine, or be rather easy to follow and manipulate for users using earlier versions of RHEL, or other Red Hat based Distorbutions such as CentOS and Fedora.
Pre-requisites: You need to have a MySQL database setup for Snort to log to. See my guide, Create MySQL Database for Snort, on how to setup the MySQL Database.

First Login to the server and su to root:
sudo su –
Then create a source directory for Snort and switch to it:
mkdir /root/snort
cd /root/snort


Download Snort:

Be sure to check the latest version. As of this writing we will be using snort 2.8.2 which is the current.  You can get the latest version by going to http://www.snort.org/dl/ and checking there.

wget http://www.snort.org/dl/old/snort-2.8.2.tar.gz

Uncompress the file:
tar –zxvf snort-2.8.2.tar.gz
Install Dependencies:
yum install libpcap-devel libtool pcre-devel mysql mysql-devel gcc
Install snort:
cd /root/snort/snort-2.8.2
./configure --with-mysql --prefix=/usr

If you get any errors, you probably need to install other dependencies. Google them and try again.
After the ./configure completes successfully, do:
make all
make install

Create Snort user and group:
groupadd snort
useradd –g snort snort


Create Snort Directories:

mkdir –p /etc/snort/rules
mkdir /var/log/snort

Change ownership of log directory:
chown snort.snort /var/log/snort
Copy your rules to /etc/snort/rules. These rules can be downloaded from http://www.snort.org.
Copy the snort.conf file from here and paste it to /etc/snort/snort.conf
Configure MySql information in snort.conf:
vi /etc/snort/snort.conf

Search for log, mysql by typing this exactly:

?alert, mysql
Then press Enter.
This will take you to the line that you will configure MySql logging on.
Set the variables it asks for on that line.  If you don’t know what they are, you probably shouldn’t be doing this install to begin with…
At this point you should go in and setup your rules that you have at the bottom of the file. Just follow the format from the already configured rules.
Add script to /etc/init.d/ to start snort service:
vi /etc/int.d/snortd
press i to enable inserting text.
Copy the following text in gray:
#!/bin/sh
# Description: start up script for snort
# chkconfig: 2345 40 60
#
# Source function library.
. /etc/rc.d/init.d/functions
#
case "$1" in
#
'start')
echo "Starting up Snort..."
/usr/bin/snort -c /etc/snort/snort.conf -D -g snort -u snort -i eth0 -l /var/log/snort
echo "Done."
;;
#
'stop')
echo "Stopping Snort..."
killproc snort
echo "Done."
;;
#
'restart')
$0 stop
$0 start
;;
#
status)
status snort
;;
#
*)
echo "Usage: $0 {start|stop}"
exit 1
#
esac
exit 0

Go back to the ssh client and hold the shift key and press the Insert key (This will paste the script into the file. )
Press the Esc Key to leave insert mode.
Hold the Shift key and press z twice to save and exit the file.
Make the service script executable:
chmod +x /etc/rc.d/init.d/snortd
Start Snort Service at boot:
chkconfig snortd on
Start Snort:
service snortd start
Check that it’s runnig:
ps –ef | grep snort
or
service snortd status
If the only thing you see contains grep then snort is not running.
If this is the case, look at the messages log to see what held it up. Generally it’s a bad rule, which it will tell you what is bad about it.
tail –n100 /var/log/messages

snort.conf

You can use this config as a starting point for your Snort configuration. Note that you will need to change the MySql variable… You should see it if you scroll down some. Also comment out or add any rules that you may or may not have. A good source for rules would be http://www.snort.org, or google for bleeding-edge rules. I personally use a combination of the two rulesets.

#--------------------------------------------------
# http://www.snort.org Snort 2.8.2 Ruleset
# Contact: snort-sigs@lists.sourceforge.net
#--------------------------------------------------
# $Id$
#
# Step #1: Set the network variables:
#
# You must change the following variables
# to reflect your local network. The variable
# is currently setup for an RFC 1918 address space.
#
# You can specify it explicitly as:
#
# var HOME_NET 10.1.1.0/24
#
#
# var HOME_NET $eth0_ADDRESS
#
# You can specify lists of IP addresses for HOME_NET
# by separating the IPs with commas like this:
#
# var HOME_NET [10.1.1.0/24,192.168.1.0/24]
#
# MAKE SURE YOU DON’T PLACE ANY SPACES IN YOUR LIST!
#
# or you can specify the variable to be any IP address
# like this:

var HOME_NET any

# Set up the external network addresses as well.
var EXTERNAL_NET any

# List of DNS servers on your network
var DNS_SERVERS $HOME_NET

# List of SMTP servers on your network
var SMTP_SERVERS $HOME_NET

# List of web servers on your network
var HTTP_SERVERS $HOME_NET

# List of sql servers on your network
var SQL_SERVERS $HOME_NET

# List of telnet servers on your network
var TELNET_SERVERS $HOME_NET

# List of snmp servers on your network
var SNMP_SERVERS $HOME_NET

# Ports you run web servers on
portvar HTTP_PORTS 80

# Ports you want to look for SHELLCODE on.
portvar SHELLCODE_PORTS !80

# Ports you might see oracle attacks on
portvar ORACLE_PORTS 1521

# Path to your rules files (this can be a relative path)
var RULE_PATH /etc/snort/rules

# frag3: Target-based IP defragmentation
preprocessor frag3_global: max_frags 65536
preprocessor frag3_engine: policy first detect_anomalies

# Target Based stateful inspection/stream reassembly for Snort
preprocessor stream5_global: max_tcp 8192, track_tcp yes, \
track_udp no
preprocessor stream5_tcp: policy first, use_static_footprint_sizes

# http_inspect
preprocessor http_inspect: global \
iis_unicode_map unicode.map 1252

preprocessor http_inspect_server: server default \
profile all ports { 80 8080 8180 } oversize_dir_length 500

# rpc_decode: normalize RPC traffic
preprocessor rpc_decode: 111 32771

# bo: Back Orifice detector
preprocessor bo

# sfPortScan
preprocessor sfportscan: proto { all } \
memcap { 10000000 } \
sense_level { low }
# database: log to a variety of databases

#######################################
#CHANGE THESE VALUES TO MATCH YOUR SETUP!!!! #
#######################################

output database: alert, mysql, user=snort password=snort dbname=snort host=snort

# Include classification & priority settings
include classification.config

# Include reference systems
include reference.config

# Customize your rule set
include $RULE_PATH/local.rules
include $RULE_PATH/bad-traffic.rules
include $RULE_PATH/exploit.rules
include $RULE_PATH/scan.rules
include $RULE_PATH/finger.rules
include $RULE_PATH/ftp.rules
include $RULE_PATH/telnet.rules
include $RULE_PATH/rpc.rules
include $RULE_PATH/rservices.rules
include $RULE_PATH/dos.rules
include $RULE_PATH/ddos.rules
include $RULE_PATH/dns.rules
include $RULE_PATH/tftp.rules
include $RULE_PATH/web-cgi.rules
include $RULE_PATH/web-coldfusion.rules
include $RULE_PATH/web-iis.rules
include $RULE_PATH/web-frontpage.rules
include $RULE_PATH/web-misc.rules
include $RULE_PATH/web-client.rules
include $RULE_PATH/web-php.rules
include $RULE_PATH/sql.rules
include $RULE_PATH/x11.rules
include $RULE_PATH/icmp.rules
include $RULE_PATH/netbios.rules
include $RULE_PATH/misc.rules
include $RULE_PATH/attack-responses.rules
include $RULE_PATH/oracle.rules
include $RULE_PATH/mysql.rules
include $RULE_PATH/snmp.rules
include $RULE_PATH/smtp.rules
include $RULE_PATH/imap.rules
include $RULE_PATH/pop2.rules
include $RULE_PATH/pop3.rules
include $RULE_PATH/nntp.rules
include $RULE_PATH/other-ids.rules
include $RULE_PATH/web-attacks.rules
include $RULE_PATH/backdoor.rules
include $RULE_PATH/shellcode.rules
include $RULE_PATH/policy.rules
include $RULE_PATH/porn.rules
include $RULE_PATH/info.rules
include $RULE_PATH/icmp-info.rules
include $RULE_PATH/virus.rules
include $RULE_PATH/chat.rules
include $RULE_PATH/multimedia.rules
include $RULE_PATH/p2p.rules

MySQL Change/Update root Password


Setting up mysql password is one of the essential tasks. By default root user is MySQL admin account. Please note that the Linux / UNIX login root account for your operating system and MySQL root are different. They are separate and nothing to do with each other (indeed some admin removes root account and setup admin as mysql super user).

mysqladmin command to change root password

If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. To setup root password for first time, use mysqladmin command at shell prompt as follows:
$ mysqladmin -u root password NEWPASSWORD
However, if you want to change (or update) a root password, then you need to use following command
$ mysqladmin -u root -p'oldpassword' password newpass
For example, If old password is abc, and set new password to 123456, enter:
$ mysqladmin -u root -p'abc' password '123456'

Change MySQL password for other user

To change a normal user password you need to type (let us assume you would like to change password for vivek):
$ mysqladmin -u vivek -p oldpassword password newpass

Changing MySQL root user password using MySQL sql command

This is another method. MySQL stores username and passwords in user table inside MySQL database. You can directly update password using the following method to update or change password for user vivek:
1) Login to mysql server, type following command at shell prompt:
$ mysql -u root -p
2) Use mysql database (type command at mysql> prompt):
mysql> use mysql;
3) Change password for user vivek:
mysql> update user set password=PASSWORD("NEWPASSWORD") where User='vivek';
4) Reload privileges:
mysql> flush privileges;
mysql> quit

Detect and Configure / Install Modem on UBUNTU

     

To find out what kind of software modem you are using, go to linmodems.org, read the page, and download the scanModem tool (which will only recognize PCI and USB modems, not ISA modems). Copy it to your desktop in your Ubuntu machine, then open a command line and enter:


  • $ cd ~/Desktop
     $ gunzip scanModem.gz
     $ chmod +x scanModem
     $ ./scanModem
     $ gedit Modem/ModemData.txt


The program gunzip will decompress the file, chmod will mark it as executable, and ./scanModem will run it. If it tells you to do something as root by issuing su - root, instead just enter the commands it wants following a "sudo", e.g. $ sudo modprobe snd-intel8x0m. scanModem will scan your modem and tell you what it is and how to configure it. It will not configure it for you. But after running, you will see a number of new folders, including a Modem folder. Read 1stRead.txt and ModemData.txt in there, and see if you modem was recognized. This is admittedly not a straight-forward read and might need some more reading around on above mentioned page to find out which drivers your modem needs. Then scan through the following sections to find out about the easiest way to install that driver under Ubuntu.
Note: For many of the following drivers, you will need to enable the universe and or the multiverse repositories. See AddingRepositoriesHowto. This requires you to have working network connection. You can also search for packages to download in another system and transfer to your Ubuntu installation at http://packages.ubuntu.com/ . Be careful with the dependencies... Check out this forum post for another way to get packages using the LiveCD on another system with network connection and a CD burner: http://www.ubuntuforums.org/showpost.php?p=893732&postcount=6
Now that you know what modem you have, please return to DialupModemHowto to continue.

Yum Repositories

yum install yum-priorities 
Repositories listed in order of reliability:

epel

Install Repository: Install Key:
rpm --import http://download.fedora.redhat.com/pub/epel/RPM-GPG-KEY-EPEL
Verify repository package: you should get "(sha1) dsa sha1 md5 gpg OK"
rpm -K http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-3.noarch.rpm
Install Repository:
rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-3.noarch.rpm

rpmfusion

Install epel and enable epel-testing at this time. Most packages are still in rpmfusion testing repository
rpm --import 
rpm -ivh http://download1.rpmfusion.org/free/el/updates/testing/5/i386/rpmfusion-free-release-5-0.1.noarch.rpm
rpm -ivh http://download1.rpmfusion.org/nonfree/el/updates/testing/5/i386/rpmfusion-nonfree-release-5-0.1.noarch.rpm

rpmforge

Installing repository:
rpm --import http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt
rpm -K http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm
rpm -Uvh http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm

adobe

rpm -Uvh adobe-release-i386-1.0-1.noarch.rpm

atrpms

/etc/yum.repos.d/atrpms.repo
[atrpms-stable]
name=RedHat Enterprise $releasever - $basearch - ATrpms
baseurl=http://dl.atrpms.net/el$releasever-$basearch/atrpms/stable
       http://www.mirrorservice.org/sites/download.atrpms.net/el$releasever-$basearch/atrpms/stable/
       http://mirrors.ircam.fr/pub/atrpms/el$releasever-$basearch/atrpms/stable/
       http://ftp-stud.fht-esslingen.de/atrpms/dl.atrpms.net/el$releasever-$basearch/atrpms/stable/
       http://fedora.univ-nantes.fr/dl.atrpms.net/el$releasever-$basearch/atrpms/stable/
       http://wftp.tu-chemnitz.de/pub/linux/ATrpms/el$releasever-$basearch/atrpms/stable/
failovermethod=priority
enabled=1
gpgkey=http://ATrpms.net/RPM-GPG-KEY.atrpms
gpgcheck=1
protect=0

El Repo


karan

appears to have no major packages for rhel5 at this time
cd /etc/yum.repos.d/
wget http://centos.karan.org/kbsingh-CentOS-Extras.repo
wget http://centos.karan.org/kbsingh-CentOS-Misc.repo
add "protect=0" to these repositories
rpm --import http://centos.karan.org/RPM-GPG-KEY-karan.org.txt
Also read: http://www.karan.org/blog/

jpackage

http://www.jpackage.org/

future

RPMrepo: http://rpmrepo.org/ - merger of rpmforge and atrpms
RPMfusion: http://rpmfusion.org/ - merger of livna, freshrpms, and dribble

other

Atomic Rocket Turtle
jason litka

install Ubuntu on a USB device

How to install Ubuntu Linux from USB Stick posted on this site a while ago, and found it to be quite some work to get Ubuntu working on a USB stick. Besides, having to prepare your USB device, creating a separate partition on it which will be more or less “useless” after the installation, giving up 750MB of space?

There had to be a better way.
Together with a colleague of mine, I decided to figure out whether there could be an easier way to install Ubuntu on a USB device.
I found a way of doing it in a much simpler way… without creating the separate partition to store the LiveCD:

  1. Insert the LiveCD into your computer;
  2. Connect your USB device;
  3. Boot your computer from the liveCD;
  4. Once Ubuntu is started, go to System - Administration - Partition Manager
    This will open the Partion Editor. Select your USB device and delete all partitions on it. Click Apply and exit Partition Editor;
  5. Double Click the Install Icon. This will start the Installer;
  6. The Welcome Screen is shown. Choose your language and click Forward;
  7. Select your Time Zone and click Forward;
  8. Choose your Keyboard Layout and click Forward;
  9. The partitioner will be started, and you will be given the choice where to install Ubuntu. Choose Guided - Use entire disk, selecting your USB device (this will most likely be /dev/sdb, don’t choose /dev/sdb1!);
  10. The next sceen you will give your username/password information. Provide the required info and hit Forward;
  11. If there is anything to migrate from other installations on your computer (most likely not), do whatever you want, and click Forward;
  12. The next screen is important - It is titled: “Ready to Install”. Be careful here: before clicking on Forward, make sure you click on the “Advanced” Button!
    This will open a new screen, giving you the option whether and where to install the bootloader. Select your USB device (in my case it was /dev/sdb) to install the bootloader to;
    Exit this screen and click on Forward in the “Ready to Install” screen, which will be shown;
  13. The installation will be started now. Just be patient, grab a cup of coffee and come back 15 minutes later, your installation will be more or less finished by then.
So you have finished the installation. However, when you will be restarting your system from USB, you will find out that the partition you just installed Ubuntu to cannot be mounted.
Here comes the trick:
  1. Once the installation is finished, reboot your PC (this is the safest) from your LiveCD, with your USB device connected;
  2. Once started, open up a terminal (Applications - Accessories - Terminal);
  3. In the Terminal, type: sudo -i (which will give you root privileges, so be careful from now on!);
  4. Change directories to /media/disk/boot/grub - This will take you to the “/boot/grub” directory on the USB device;
  5. open menu.lst with vi (make a backup first!)
  6. Go to line 130 (or somewhere in that area).
    You will find a line looking like:
    ## ## End Default options ##
    And underneath it you will find three entries pointing to your Ubuntu you just installed:
    title         Ubuntu 8.04, kernel 2.6.24-16-generic
    root        (hd1,0)
    kernel     /boot/vmlinuz………
    initrd       /boot/initrd…….
    quiet
    (the above 5 lines repeat 3 times with slight differences)
  7. The magic trick is to change (hd1,0) into (hd0,0) for all these three entries.
    Why? Booting from USB device makes your USB device hd0, in stead of hd1 at time of installation.
  8. Search for the line starting with “# groot=(hd1,0)” and change (hd1,0) to (hd0,0) - Don’t delete the # at te beginning of this line!
  9. Once you did this, you can optionally remove the remaining of the file
    (everything underneath ### END DEBIAN AUTOMATIC KERNELS LIST);
  10. Save the file, make sure it is owned by root:ubuntu (chgrp ubuntu menu.* will do)
  11. Edit device.map (in the same directory) and change the mapping of hd0 to /dev/sdb.
  12. Reboot your machine, from USB, choose the Ubuntu installation from the Boot Loader and you are one happy person.
I guess that is it. If I missed something, please comment.

Few Securing a LInux server tips

#Reference:http://www.cisecurity.org/bench_linux.html

#Note:This tutorial is based on Fedora Core 4.Should be valid for a newer version of Fedora too.The reader is advised to read the CIS Benchmark pdf after completing all activities mentioned in this document.

# Setup an informative command prompt
export PS1="-\$?-(\u@\h) \w > "


# Hostname Setup
Reference:http://www.cpqlinux.com/hostname.html

# Please ensure that the correct hostname is setup in the following files.The hostname should ideally match the PTR record of the system IP
/etc/hosts
/etc/sysconfig/network
# Use echo to set the hostname in the file below eg.
echo yourhostname > /proc/sys/kernel/hostname
/proc/sys/kernel/hostname
# Virtual IP Setup
cd /etc/sysconfig/network-scripts

#Check for existing network adapters with the command:

ls ifcfg-*

#In most instances, you will see the files ifcfg-eth0 and ifcfg-lo. If you see other files with any other names and are unfamiliar with configuring TCP/IP, you may want to consult with your system administrator before proceeding.

cp -a ifcfg-eth0 ifcfg-eth0:0
cp -a ifcfg-eth0 ifcfg-eth0:1
# Ensure the following lines are configured as

vi icfg-eth0:0
DEVICE=eth0:0
IPADDR=
VLAN=yes

vi icfg-eth0:1
DEVICE=eth0:1
IPADDR=
VLAN=yes

#Disable IPV6

cp -a /etc/modprobe.conf /etc/modprobe_backup.conf
echo "alias net-pf-10 off" >> /etc/modprobe.conf
echo "alias ipv6 off" >> /etc/modprobe.conf

/etc/init.d/ip6tables stop
/sbin/chkconfig --level 35 ip6tables off

# Restart the network to effect changes

/sbin/service network restart

# Edit /etc/hosts and add a line for your new addresses and name such as:
127.0.0.1 localhost.localdomain localhost
x.x.x.x newhost1.yourdomain.com
x.x.x.x newhost2.yourdomain.com


# Disabling selinux

vi /etc/sysconfig/selinux
#check for the line SELINUX
SELINUX=disabled

# Date and Time Configuration

Ref:http://www.linuxsa.org.au/tips/time.html

ln -sf /usr/share/zoneinfo/Asia/Calcutta /etc/localtime

date monthdayhourminyear

yum install ntp

#Configure a cron job to update time every night at 12 AM
00 00 * * * /usr/sbin/ntpdate 0.pool.ntp.org 1.pool.ntp.org

# Configure Automatic Updates using yum.Fedora Core 6 or above will have yum-updatesd instead of yum

/sbin/chkconfig yum on
/sbin/service yum start

# If you wish to disable autoupdation of some package, eg.firefox and cacti ,do the following
cp -a /etc/yum.conf /etc/yum.conf.orig
vi /etc/yum.conf
# Add the following line
exclude=firefox cacti

# For Fedora Core 6 or above do this
# Reference: http://www.die.net/doc/linux/man/man5/yum-updatesd.conf.5.html
cp -a /etc/updatedb.conf /etc/updatedb.conf.orig
vi /etc/yum/yum-updatesd.conf

#########
# Configure the entries as shown below
# automatically install updates
do_update = yes
# automatically download updates
do_download = yes
# automatically download deps of updates
do_download_deps = yes
#########

/sbin/chkconfig yum-updatesd on
/sbin/service yum-updatesd start

crontab -e

00 0 * * * yum -y update

# Configuring updatedb
cp -a /etc/updatedb.conf /etc/updatedb.conf.orig

vi /etc/updatedb.conf
#Configure the following values to yes
#DAILY_UPDATE=no
DAILY_UPDATE=yes

# Configuring Log Compression
cp -a /etc/logrotate.conf /etc/logrotate.conf.orig
vi /etc/logrotate.conf

# uncomment this if you want your log files compressed
compress

# Unalias cp and mv

unalias mv cp

# Firewall ,Reactive IDS and SSH bruteforce prevention setup

Please install and configure shorewall ,psad and fail2ban by referring their separate howtos

# Apache Installation

# Check if Apache is already installed

rpm -qa httpd
service httpd status

# If httpd is not installed proceed with the apache installation as follows

yum install httpd
yum install httpd-devel


# Apache Hardening

Edit httpd.conf file as follows.

cd /etc/httpd/conf/

cp -a httpd.conf httpd.conf.orig

vi /etc/httpd/conf/httpd.conf

# Edit the following entry as follows

#ServerTokens OS
ServerTokens Prod

#ServerSignature On
ServerSignature Off


#Ref:http://www.slac.stanford.edu/comp/unix/apache-security.html
#http://publib.boulder.ibm.com/httpserv/ihsdiag/http_trace.html

# Disabling Indexing
# Ref: http://www.ducea.com/2006/06/26/apache-tips-tricks-disable-directory-indexes/
# In Main Server Configurations

Options -Indexes

# To disable Trace and Track Methods:

For apache version 1.3.34 (or later 1.3.x versions), or apache 2.0.55 (or later), in section 1, add the line
TraceEnable off

For older versions of apache, see below.

#Add Before Secton 3 and in each virtual host configuration section/file
# Block access: SLAC addition
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
# End block access rule

# Disabling welcome page
cp -a /etc/httpd/conf.d/welcome.conf /etc/httpd/conf.d/welcome.conf.orig
vi /etc/httpd/conf.d/welcome.conf
# Comment all the lines in the file

# Disabling configuration by .htaccess

AllowOverride None

# Restart Apache
/etc/rc.d/init.d/httpd start

# MySQL Installation
# Check if MySQL is already installed

rpm -qa mysql
service mysqld status

# If Mysqld Daemon is not installed proceed with the MySQL installation as follows

yum install mysql-server
yum install mysql
yum install mysql-devel

#Start MySQL for the first time

mysql_install_db
/etc/rc.d/init.d/mysqld start
#Note:In case you have issues starting Mysql server for the first time and you see error messggaes saying that tmp files could not be created,please run bastille configuration again and answer N to "Q: Would you like to install TMPDIR/TMP scripts?" question reboot the system.Post reboot you can start Mysqld

/sbin/chkconfig mysqld on

#Mysql Hardening:

mysql
# Removing anonymous login:

DELETE FROM mysql.user WHERE User = '';
FLUSH PRIVILEGES;
quit
#Setting Mysql Root password:

/usr/bin/mysqladmin -u root password 'yourpassword'
/usr/bin/mysqladmin -u root -h password 'yourpassword'

# Delete test database

mysql
drop database test;

# Configure Mysql to not listen for external connections

cp -a /etc/my.cnf /etc/my.cnf.orig

vi /etc/my.cnf

[mysqld]
skip-networking

#Perl Installation

#check if perl is installed or not

rpm -qa perl

# If Perl is not installed proceed with the Perl installation as follows

yum install perl

# Cpan configuration

# Before running cpan ensure that gcc is installed else some modules will throw errors during compilation

rpm -qa gcc

# Install gcc if not found

yum install gcc

# Run and configure cpan

cpan

# A first time set of configuration questions will be asked

# Update cpan by running

cpan
install Bundle::CPAN
reload cpan

# Bastille Hardening


#Bastille Installation

cd /tmp

wget http://nchc.dl.sourceforge.net/sourceforge/bastille-linux/Bastille-3.2.1-0.1.noarch.rpm


# Ref: http://www.bastille-linux.org/running_bastille_on.htm#top

rpm -ivh Bastille-3.2.1-0.1.noarch.rpm

# Install Curses from cpan
# Please check wheather ncurses-devel is installed

rpm -qa ncurses-devel

# If ncurses is not installed install it as follows

yum install ncurses-devel

# Install Curses module as follows

cpan

install Curses

# Run bastille text mode hardening as follows

/usr/sbin/bastille -c

# Respond to all questions

# Check your score

/usr/sbin/bastille --report


# ICMP Hardening


# Check and Download sysctl RPM
yum install sysctl

# Enter the following in /etc/sysctl.conf file
net.ipv4.icmp_echo_ignore_all = 1

net.ipv4.icmp_echo_ignore_broadcasts = 1

net.ipv4.icmp_ignore_bogus_error_responses = 1

net.ipv4.conf.all.accept_source_route = 0

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.tcp_max_syn_backlog = 4096

net.ipv4.tcp_syncookies=1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.tcp_max_orphans = 256
net.ipv4.conf.all.log_martians = 1

# Diable Forwarding and Gateway functionality
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0


#Check for the syntax in the file /etc/sysctl.conf
/sbin/sysctl -p

OR
/sbin/iptables -A INPUT -j REJECT -p icmp --icmp-type 13
/sbin/iptables -A OUTPUT -j REJECT -p icmp --icmp-type 14

# Detailed audit trail setup

Ref: http://www.cyberciti.biz/tips/howto-log-user-activity-using-process-accounting.html

yum install psacct
chkconfig psacct on
/etc/init.d/psacct start

# Rootkit Hunter

Reference:http://www.rootkit.nl/

Installation:

# Download rkhunter from http://www.rootkit.nl/projects/rootkit_hunter.html
cd /tmp
wget http://nchc.dl.sourceforge.net/sourceforge/rkhunter/rkhunter-1.3.2.tar.gz
tar zxvf rkhunter-1.3.2.tar.gz
cd rkhunter-1.3.2
sh installer.sh --layout default --install

# Running Rkhunter
/usr/local/bin/rkhunter --update
/usr/local/bin/rkhunter -c --createlogfile --quiet
The report will be generated at /var/log/rkhunter.log

#Configure rkhunter for automatic update
crontab -e
00 0 * * * /usr/local/bin/rkhunter --update -q

# SSHD Hardening
cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.orig

vi /etc/ssh/sshd_config

#change port no from 22 to 222
Port 222

PermitRootLogin no

Banner /etc/issue

#This banner is generated when you ran Bastille previously.

#Prevent X11 forwarding
X11Forwarding no

#Don't read the user's ~/.rhosts and ~/.shosts files uncomment IgnoreRhosts yes
IgnoreRhosts yes

# The following switch is not found in Fedora 4.Please check the switch to ensure that it exists #before making this entry

RhostsAuthentication no

RhostsRSAAuthentication no

HostbasedAuthentication no

PermitEmptyPasswords no

#Note:Before restarting ssh please create a non-root account.

Restart sshd
/etc/rc.d/init.d/sshd restart
# Nessus Setup

# Read the Nessus How to file for installing and running Nessus

# CIS benchmark security exercise

# Download the CIS benchmark locally from http://www.cisecurity.org/bench_linux.html and copy the do-backup.sh file in /root and run the same to backup all important directories and files

cd /root
chmod 755 do-backup.sh
./do-backup.sh

# Uninstalling xinetd
rpm -qa xinetd
rpm -e xinetd-versionnumber

# Incase you still want to use some services in xinetd ,please run the following comands to stop these unnnecessary services.

cd /etc/xinetd.d
for FILE in chargen chargen-udp cups-lpd cups daytime \ daytime-udp echo echo-udp eklogin ekrb5-telnet finger \ gssftp imap imaps ipop2 ipop3 krb5-telnet klogin kshell \ ktalk ntalk pop3s rexec rlogin rsh rsync servers services \ sgi_fam talk telnet tftp time time-udp vsftpd wu-ftpd do

chkconfig ${FILE} off done

# Disable GUI
sed -e 's/id:5:initdefault:/id:3:initdefault:/' \
< /etc/inittab-preCIS > /etc/inittab
chown root:root /etc/inittab
chmod 0600 /etc/inittab
diff /etc/inittab-preCIS /etc/inittab

# Disable Unneccessary services
# Please review all services listed in the following script before running.

vi disable_unwanted_services

########
for FILE in apmd avahi-daemon canna cups-config-daemon FreeWnn gpm hidd hpoj hplip innd irda isdn kdcrotate lvs mars-nwe messagebus oki4daemon privoxy rstatd rusersd rwalld rwhod wine; do
/sbin/service $FILE stop
/sbin/chkconfig $FILE off
done

for FILE in nfs nfslock autofs ypbind ypserv yppasswdd portmap smb netfs lpd tux snmpd named postgresql webmin kudzu squid cups ip6tables pcmcia bluetooth mDNSResponder; do
/sbin/service $FILE stop
/sbin/chkconfig $FILE off
done
########

chmod 755 disable_unwanted_services
./disable_unwanted_services

# Assign Proper permissions to log files

chmod o-rwx boot.log* cron* dmesg ksyms* httpd/* maillog* messages* news/* pgsql rpmpkgs* samba/* sa/* scrollkeeper.log secure* spooler* squid/* vbox/* wtmp

chmod o-rx boot.log* cron* maillog* messages* pgsql secure* spooler* squid/* sa/*

chmod g-w boot.log* cron* dmesg httpd/* ksyms* maillog* messages* pgsql rpmpkgs* samba/* sa/* scrollkeeper.log secure* spooler*

chmod g-rx boot.log* cron* maillog* messages* pgsql secure* spooler*

chmod o-w gdm/ httpd/ news/ samba/ squid/ sa/ vbox/

chmod o-rx httpd/ samba/ squid/ sa/

chmod g-w gdm/ httpd/ news/ samba/ squid/ sa/ vbox/

chmod g-rx httpd/ samba/ sa/

chmod u-x kernel syslog loginlog

# Verify passwd, shadow, and group File Permissions

cd /etc
chown root:root passwd shadow group
chmod 644 passwd group
chmod 400 shadow

# Allowing only root access to Cron and At

cd /etc/
rm -f cron.deny at.deny
echo root > cron.allow
echo root > at.allow
chown root:root cron.allow at.allow
chmod 400 cron.allow at.allow

# Restrict Permissions On crontab Files

chown root:root /etc/crontab
chmod 400 /etc/crontab
chown -R root:root /var/spool/cron
chmod -R go-rwx /var/spool/cron
cd /etc
ls | grep cron | grep -v preCIS | xargs chown -R root:root
ls | grep cron | grep -v preCIS | xargs chmod -R go-rwx

# Block all system accounts from loging on to the server

cd /root
vi lock_system_accounts

####
cd /etc
for NAME in `cut -d: -f1 /etc/passwd`; do
MyUID=`id -u $NAME`
if [ $MyUID -lt 500 -a $NAME != 'root' ]; then
/usr/sbin/usermod -L -s /dev/null $NAME
fi
done
###

chmod 755 lock_system_accounts

./lock_system_accounts

rm -rf lock_system_accounts

# Check for empty password accounts
awk -F: '($2 == "") { print $1 }' /etc/shadow

# Set Account Expiration Parameters On Active Accounts

cd /etc
awk '($1 ~ /^PASS_MAX_DAYS/) { $2="90" }
($1 ~ /^PASS_MIN_DAYS/) { $2="7" }
($1 ~ /^PASS_WARN_AGE/) { $2="28" }
($1 ~ /^PASS_MIN_LEN/) { $2="6" }
{ print } ' login.defs-preCIS > login.defs
diff login.defs-preCIS login.defs
chown root:root login.defs
chmod 640 login.defs
diff login.defs-preCIS login.defs

useradd -D -f 7
diff /etc/default/useradd-preCIS /etc/default/useradd
for NAME in `cut -d: -f1 /etc/passwd`; do
uid=`id -u $NAME`
if [ $uid -ge 500 -a $uid != 65534 ]; then
chage -m 7 -M 90 -W 28 -I 7 $NAME
fi
done
diff shadow-preCIS shadow

# Verify No Legacy '+' Entries Exist In passwd, shadow, And group Files

grep ^+: /etc/passwd /etc/shadow /etc/group

# No '.' or Group/World-Writable Directory In Root's $PATH

#To find ‘.’ in $PATH:
echo $PATH | egrep '(^|:)(\.|:|$)'
#To find group- or world-writable directories in $PATH:
find `echo $PATH | tr ':' ' '` -type d \( -perm -002 -o -perm -020 \) -ls

#These commands should produce no output.

#User Home Directories Should Be Mode 750 or More Restrictive

vi user_directories_permission

###############
for DIR in `awk -F: '($3 >= 500) { print $6 }' /etc/passwd`; do
chmod g-w $DIR
chmod o-rwx $DIR
done
##############

chmod 755 user_directories_permission
./user_directories_permission

#No User Dot-Files Should Be World-Writable

vi user_dot_files_non_worldwritable

#############

for DIR in `awk -F: '($3 >= 500) { print $6 }' /etc/passwd`; do
for FILE in $DIR/.[A-Za-z0-9]*; do
if [ ! -h "$FILE" -a -f "$FILE" ]; then
chmod go-w "$FILE"
fi
done
done
#########

chmod 755 user_dot_files_non_worldwritable
./user_dot_files_non_worlwritable

#Remove User .netrc Files

find / -name .netrc

# If any .netrc file is found then run the following script to remove

vi remove_netrc

###############
for DIR in `cut -f6 -d: /etc/passwd`; do
if [ -e $DIR/.netrc ]; then
echo "Removing $DIR/.netrc"
rm -f $DIR/.netrc fi
done
###############

chmod 755 remove_netrc
./remove_netrc

#Set Default umask For Users

vi set_default_umask

#########
cd /etc
for FILE in profile csh.login csh.cshrc bashrc; do
if ! egrep -q 'umask.*77' $FILE ; then
echo "umask 077" >> $FILE
fi
chown root:root $FILE
chmod 444 $FILE
diff ${FILE}-preCIS $FILE
done

cd /root
for FILE in .bash_profile .bashrc .cshrc .tcshrc; do
if ! egrep -q 'umask.*77' $FILE ; then
echo "umask 077" >> $FILE # See description
fi
chown root:root $FILE
diff ${FILE}-preCIS $FILE
done
###########

chmod 755 set_default_umask
./set_default_umask


# Disable Core Dumps

cp -a /etc/security/limits.conf /etc/security/limits.conf.orig

vi /etc/security/limits.conf

#Add the following two lines.In future you can enable core dumps for invidual users if required.

* soft core 0
* hard core 0

####

# Limit Access To The Root Account From su
# Warning:Please add your account to the wheel group before proceeding with this activity else you # will not be able to su.
# eg. /usr/sbin/usermod -G wheel

# In case you want to create a new account and add it to the wheel group, then run this command
/usr/sbin/useradd -G wheel

# Limit Access To The Root Account From su

cd /etc/pam.d/
cp -a su su_backup_18_dec_2006

vi su

##Uncommenting this line allows only the users in the wheel group to become root by using the su command and entering the root password.All other users get the message Incorrect Password

auth required /lib/security/$ISA/pam_wheel.so use_uid

# Banners

# Note:/etc/issue banner should have already been created by BastilleIf you havent run Bastille please create an appropriate banner file /etc/issue as follows



***************************************************************************
NOTICE TO USERS


This computer system is the private property of , whether
individual, corporate or government. It is for authorized use only.
Users (authorized or unauthorized) have no explicit or implicit
expectation of privacy.

Any or all uses of this system and all files on this system may be
intercepted, monitored, recorded, copied, audited, inspected, and
disclosed to your employer, to authorized site, government, and law
enforcement personnel, as well as authorized officials of government
agencies, both domestic and foreign.

By using this system, the user consents to such interception, monitoring,
recording, copying, auditing, inspection, and disclosure at the
discretion of such personnel or officials. Unauthorized or improper use
of this system may result in civil and criminal penalties and
administrative or disciplinary action, as appropriate. By continuing to use
this system you indicate your awareness of and consent to these terms
and conditions of use. LOG OFF IMMEDIATELY if you do not agree to the
conditions stated in this warning.

****************************************************************************
cp -a issue.net issue_backup_todays_date.net

cp -a issue issue.net

# Contents of /etc/motd are displayed after a user logins in so its not neccessary to create a #banner in that file

chown root:root /etc/motd /etc/issue /etc/issue.net
chmod 644 /etc/motd /etc/issue /etc/issue.net

# Removing unnecessary applications
# Please refer http://www.mjmwired.net/resources/mjm-services-fc6.html for the list of services and their uses and recommendations on which to disable
cd /etc/init.d
ls

# Verify the softwares that are listed here.Remove all unnecesaasy packages as show below.

# For eg. if you see bluetooth and you want to identify what package it represnts, do the following
rpm -qf bluetooth
bluez-utils-2.15-7
yum remove bluez-utils-2.15-7

# Do this for all other softwares like portmap,apmd,cups,isdn,irda,etc.

# RHEL comes with virtualisation enabled.Due to this you may see an additional network adapter ( virbr0 ) when you run /sbin/ifconfig -a
# This can be removed by following these steps
#Source :http://www.cyberciti.biz/faq/rhel-fedora-centos-linux-remove-network-interface-virbr0/
yum groupremove "Virtualization"

# Type y when it lists the following pakcages to be removed
libvirt
libvirt-python
rhn-virtualization-host

This will also remove the virbr0 network adapter

#Firewall Configuration

/bin/netstat -ltunp

# The above command will show you list of processes running on specific ports.Please ensure that unnecassary services are disabled and uninstalled as shown in the above point.
# Open required ports in iptables using Shorewall (Please refer the separate Howto)
/usr/sbin/lokkit

# Remove All Compilers and Assemblers

#The following command will help you identify the packages installed on your system
rpm -qa | egrep "^gcc|java|bin86|dev86|nasm"

#Identify the package and remove the ones you dont need

#Verify That No Unauthorized UID 0 Accounts Exists

getent passwd | awk -F: '$3 == "0" { print $1 }'

#should return only the word "root", unless additional uid 0 accounts have been specifically authorized. Having #multiple uid 0 accounts are acceptable if the accounts are authorized, but not recommended for

Shorewall setup to ease your Iptables setup

Reference:
http://www.shorewall.net/shorewall_setup_guide.htm


# Backup your existing Iptables configuration so that you can revert back in case something goes wrong

cp -a /etc/sysconfig/iptables /etc/sysconfig/iptables_backup_

# Deploying a safety net to ensure that you dont get locked out
Reference : http://www.iptablesrocks.org/guide/safetynet.php
vi /root/firewall_reset

############
# Iptables firewall reset script
*filter
:INPUT ACCEPT [164:15203]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [147:63028]
COMMIT

*mangle
:PREROUTING ACCEPT [164:15203]
:INPUT ACCEPT [164:15203]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [147:63028]
:POSTROUTING ACCEPT [147:63028]
COMMIT

*nat
:PREROUTING ACCEPT [14:672]
:POSTROUTING ACCEPT [9:684]
:OUTPUT ACCEPT [9:684]
COMMIT

###########

# Test if the above script works and throws no error

/sbin/iptables-restore < /root/firewall_reset

/sbin/iptables -L

# The output should be similar to the following
###
Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
###

# restore your orginal firewall configuration and proceed

/sbin/iptables-restore < /etc/sysconfig/iptables_backup_

# Confirm that your original rules have been restored by running the following command

/sbin/iptables -L

# Create a crontab entry that resets the firewall every 15 minutes

crontab -e

0,15,30,45 * * * * /sbin/iptables-restore < /root/firewall_reset

# Please ensure that you comment out this line after you have succesfully tested you shorewall working.


# Reference:http://www.shorewall.net/shorewall_quickstart_guide.htm

# Before installing ,check if iproute and shorewall already exist

rpm -qa | grep -i "iproute"
rpm -qa | grep -i "shorewall"

# If iproute doesn't exist then proceed as follows

yum install iproute

# Shorewall Installation

# Using Yum
yum install shorewall

# Using RPM
# In most cases shorewall would not exist in yum repositories so proceed as follows for the rpm installation

References :
http://www.shorewall.net/Install.htm
http://www.shorewall.net/download.htm

Download the shorewall and shorewall-perl rpm package

cd /tmp

wget http://www.invoca.ch/pub/packages/shorewall/4.2/shorewall-4.2.5/shorewall-4.2.5-3.noarch.rpm

wget http://www.invoca.ch/pub/packages/shorewall/4.2/shorewall-4.2.5/shorewall-perl-4.2.5-3.noarch.rpm

rpm -ivh shorewall-perl-4.2.5-3.noarch.rpm shorewall-4.2.5-3.noarch.rpm

#Setting up Shorewall on a standalone Linux system with a single static IP address
Reference :http://www.shorewall.net/standalone.htm

# Add your IP address (IP address of the system/gateway you are connecting from and not the server IP address where you are installing shorewall) to the /etc/shorewall/routestopped file to ensure that you stay connected when the firewall restarts.You can find your IP address by visiting http://whatismyip.com
cp -a /etc/shorewall/routestopped /etc/shorewall/routestopped.orig

vi /etc/shorewall/routestopped
# eg. if your IP address ( the system/gateway you are connecting from) is 59.144.118.69
#INTERFACE HOST(S)
eth0 59.144.0.0/24

# You can also add a CIDR number to indicate a range of IPs from which connection will not break
# For eg. if you want to keep alive connections from 192.168.0.1 to 192.168.0.254 during the firewall restart add the following line

#INTERFACE HOST(S)
eth0 192.168.0.0/24

# Find the sample configuration files by running

rpm -ql shorewall | fgrep one-interface

cp -a /usr/share/doc/shorewall-4.2.5/Samples/one-interface /tmp/


cd /tmp/one-interface
# Confirm your ethernet interface ( to check if you have a single lan card)

/sbin/ifconfig -a

vi interfaces

########
#ZONE INTERFACE BROADCAST OPTIONS
net eth0 210.210.18.90 norfc1918,routefilter,tcpflags,logmartians,nosmurfs
########

# The BROADCAST address can be ignored above and instead you can put a -

#RFC-1918 reserves several Private IP address ranges for use in private networks:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

#If your IP address falls in any of the above range, then please remove "norfc1918" in the options section of the interfaces file
# If you have a non-static DHCP IP address,add "detect" in the "broadcast" section and add “dhcp” to the option list.

# Configuration of rules

# You can find custom rules files by running

ls /usr/share/shorewall/macro.*

# You can then use these macros in your shorewall rules file

# For eg. if you want to allow access to your web server running TCP Port 80 and SSHD running on TCP port 22 do the following

# Tip: You can identify the network services running on your server bu issuing the following command.

/bin/netstat -luntp

# Based on the output you get , you can decide which services to allow remote access or not

cd /tmp/one-interface

vi rules

#######
#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
Web/ACCEPT net $FW
SSH/ACCEPT net $FW
######


# You can also add the above rules in this way.

vi rules

#########
#ACTION SOURCE DESTINATION PROTO DEST PORT(S)
ACCEPT net $FW tcp 80
ACCEPT net $FW tcp 22
#########
# You can also add the following rule if you see port TCP 113 as closed in your nmap scan.
DROP net $FW tcp 113

If you want to allow conections to let's say the ssh port only from specific IP Addresses on the internet add the following

ACCEPT net:192.0.2.16/28,192.0.2.44 fw tcp 22

# Please ensure that you check the individual macros you applies from /usr/share/shorewall/macro.* to ensure that they work as desired


# You must enable startup by editing /etc/shorewall/shorewall.conf and setting STARTUP_ENABLED=Yes

cp -a /tmp/one-interface/shorewall.conf /tmp/one-interface/shorewall.conf.orig
vi /tmp/one-interface/shorewall.conf
# Modify the lines as shown

#STARTUP_ENABLED=No
STARTUP_ENABLED=Yes
#IPTABLES=
IPTABLES=/sbin/iptables
#IP_FORWARDING=On
IP_FORWARDING=Off
#DISABLE_IPV6=Yes

# Copy your configuration files to appropriate locations

cd /etc/shorewall/
cp -a policy policy.orig
cp -a rules rules.orig
cp -a interfaces interfaces.orig
cp -a zones zones.orig

cp -a /tmp/one-interface/* /etc/shorewall/

rm -rf /tmp/one-interface/

/etc/rc.d/init.d/shorewall restart

# You can use the following command to clear all shorewall rules
/sbin/shorewall clear

# Configure shorewall to auto start at boot time

/sbin/chkconfig shorewall on

# Use nmap from a different system to ensure that your firewall rules are in place

# Multiple IP address to single interface

# Reference:http://www.shorewall.net/Shorewall_and_Aliased_Interfaces.html#id2491727

# Ensure that all IP addresses ( non virtual ie. additional IP addresses on separate lan cards ) are configured in the /etc/shorewall/interfaces
# eg.

vi /etc/shorewall/interfaces

#ZONE INTERFACE BROADCAST OPTIONS
net eth1 210.210.23.26 norfc1918,routefilter,tcpflags,logmartians,nosmurfs

# The BROADCAST address can be ignored above and instead you can put a -

#RFC-1918 reserves several Private IP address ranges for use in private networks:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

#If your IP address falls in any of the above range, then please remove "norfc1918" in the options section of the interfaces file
# If you have a non-static DHCP IP address,add "detect" in the "broadcast" section and add “dhcp” to the option list.

# If you are using virtual IP addresses (eg. eth0:0,eth0:1 etc,) configured for a single ethernet card, then you can ignore the above setting in /etc/shorewall/interfaces

# If you have muliple IP addresses and want a sshd to be available on a single IP address (eg. 210.210.23.26 )instead of all IP adresses on the server ,then do this

vi /etc/shorewall/rules

#ACCEPT net $FW tcp 22
ACCEPT net $FW:210.210.23.26 tcp 22

/sbin/shorewall clear
/etc/rc.d/init.d/shorewall restart

# Remove the firewall_reset cron job and the entries in /etc/shorewall/routestopped after shorewall is run and firewall behaves as expected.

Fail2ban Installation guide :Prevent automated SSH attacks

##Manual Installation

# Download Fail2ban from http://www.fail2ban.org/wiki/index.php/Downloads

cd /tmp
wget http://nchc.dl.sourceforge.net/sourceforge/fail2ban/fail2ban-0.8.3.tar.bz2

tar jxvf fail2ban-0.8.3.tar.bz2
rm -rf /tmp/fail2ban-0.8.3.tar.bz2
cd fail2ban-0.8.3

./setup.py install

cd /tmp/fail2ban-0.8.3/files

cp -a redhat-initd /etc/init.d/fail2ban

cd /etc/init.d/

chown root.root fail2ban

chmod 755 fail2ban

/sbin/chkconfig --add fail2ban

/sbin/chkconfig fail2ban on

cd /etc/fail2ban

cp -a jail.conf jail.conf.orig

vi /etc/fail2ban/jail.conf

Edit values as follows
##########
# Put space separated list of IPs you want to ignore
ignoreip = x.x.x.x



[[ssh-iptables]

#enabled = false
enabled = true
filter = sshd
#action = iptables[name=SSH, port=ssh, protocol=tcp]
# sendmail-whois[name=SSH, dest=you@mail.com, sender=fail2ban@mail.com]
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, dest=admin@yourdomain.com, sender=fail2ban@mail.com]
#logpath = /var/log/sshd.log
logpath = /var/log/secure
#maxretry = 5
maxretry = 3

############

Edit Shorewall configuration (if you are using one as follow)

vi /etc/shorewall/shorewall.conf
#########
#BLACKLISTNEWONLY=Yes
BLACKLISTNEWONLY=No
##########

cd /etc/fail2ban

chown root.root fail2ban.conf
chmod 644 fail2ban.conf

# Log rotation of Fail2ban Logs

cd /etc/logrotate.d

vi fail2ban

###
/var/log/fail2ban.log {
missingok
notifempty
copytruncate
}
###

chown root.root fail2ban
chmod 644 fail2ban

/etc/rc.d/init.d/fail2ban start

# Check fail2ban.log for any errors

tail -f /var/log/fail2ban.log

rm -rf /tmp/fail2ban-0.8.3

 Reference: http://www.fail2ban.org/wiki/index.php/MANUAL_0_8

psad: Linux Detect And Block Port Scan Attacks In Real Time



detect port scan attacks by analyzing Debian Linux firewall log files and block port scans in real time? How do I detect suspicious network traffic under Linux?

  A port scanner (such as nmap) is a piece of software designed to search a network host for open ports. Cracker can use nmap to scan your network before starting attack. You can always see scan patterns by visiting /var/log/messages. But, I recommend the automated tool called psad - the port scan attack detector under Linux which is a collection of lightweight system daemons that run on Linux machines and analyze iptables log messages to detect port scans and other suspicious traffic.
psad makes use of Netfilter log messages to detect, alert, and (optionally) block port scans and other suspect traffic. For tcp scans psad analyzes tcp flags to determine the scan type (syn, fin, xmas, etc.) and corresponding command line options that could be supplied to nmap to generate such a scan. In addition, psad makes use of many tcp, udp, and icmp signatures contained within the Snort intrusion detection system.

Install psad under Debian / Ubuntu Linux

Type the following command to install psad, enter:
$ sudo apt-get update
$ sudo apt-get install psad


Or You can Download it from :- http://www.cipherdyne.org/psad/download/

Configure psad

Open /etc/syslog.conf file, enter:
# vi /etc/syslog.conf
Append following code
kern.info       |/var/lib/psad/psadfifo
Alternatively, you can type the following command to update syslog.conf:
echo -e ’kern.info\t|/var/lib/psad/psadfifo’ >> /etc/syslog.conf
psad Syslog needs to be configured to write all kern.info messages to a named pipe /var/lib/psad/psadfifo. Close and save the file. Restart syslog:
# /etc/init.d/sysklogd restart
# /etc/init.d/klogd

The default psad file is located at /etc/psad/psad.conf:
# vi /etc/psad/psad.conf
You need to setup correct email ID to get port scan detections messages and other settings as follows:
EMAIL_ADDRESSES             vivek@nixcraft.in;
Set machine hostname (FQDN):
HOSTNAME                    server.nixcraft.in;
If you have only one interface on box (such as colo web server or mail server), sent HOME_NET to none:
HOME_NET                NOT_USED;  ### only one interface on box
You may also need to adjust danger levels as per your setup. You can also define a set of ports to ignore, for example to have psad ignore udp ports 53 and 5000, use:
IGNORE_PORTS                udp/53, udp/5000;
You can also enable real time iptables blocking, by setting following two variables:
ENABLE_AUTO_IDS             Y;
IPTABLES_BLOCK_METHOD       Y;
psad has many more options, please read man pages for further information. Save and close the file. Restart psad:
# /etc/init.d/psad restart

Update iptables rules

psad need following two rules with logging enabled:
iptables -A INPUT -j LOG
iptables -A FORWARD -j LOG 
Here is my sample Debian Linux desktop firewall script with logging enabled at the end:
#!/bin/bash
IPT="/sbin/iptables"
 
echo "Starting IPv4 Wall..."
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t mangle -F
$IPT -t mangle -X
modprobe ip_conntrack
 
BADIPS=$(egrep -v -E "^#|^$" /root/scripts/blocked.fw)
PUB_IF="eth0"
 
#unlimited
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT
 
# DROP all incomming traffic
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP
 
# block all bad ips
for ip in $BADIPS
do
    $IPT -A INPUT -s $ip -j DROP
    $IPT -A OUTPUT -d $ip -j DROP
done
 
# sync
$IPT -A INPUT -i ${PUB_IF} -p tcp ! --syn -m state --state NEW  -m limit --limit 5/m --limit-burst 7 -j LOG --log-level 4 --log-prefix "Drop Syn"
 
$IPT -A INPUT -i ${PUB_IF} -p tcp ! --syn -m state --state NEW -j DROP
 
# Fragments
$IPT -A INPUT -i ${PUB_IF} -f  -m limit --limit 5/m --limit-burst 7 -j LOG --log-level 4 --log-prefix "Fragments Packets"
$IPT -A INPUT -i ${PUB_IF} -f -j DROP
 
# block bad stuff
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL ALL -j DROP
 
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL NONE -m limit --limit 5/m --limit-burst 7 -j LOG --log-level 4 --log-prefix "NULL Packets"
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL NONE -j DROP # NULL packets
 
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
 
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,FIN SYN,FIN -m limit --limit 5/m --limit-burst 7 -j LOG --log-level 4 --log-prefix "XMAS Packets"
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP #XMAS
 
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags FIN,ACK FIN -m limit --limit 5/m --limit-burst 7 -j LOG --log-level 4 --log-prefix "Fin Packets Scan"
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags FIN,ACK FIN -j DROP # FIN packet scans
 
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
 
# Allow full outgoing connection but no incomming stuff
$IPT -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A OUTPUT -o eth0 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
 
# allow ssh only
$IPT -A INPUT -p tcp --destination-port 22 -j ACCEPT
$IPT -A OUTPUT -p tcp --sport 22 -j ACCEPT
 
# allow incoming ICMP ping pong stuff
$IPT -A INPUT -p icmp --icmp-type 8 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
$IPT -A OUTPUT -p icmp --icmp-type 0 -m state --state ESTABLISHED,RELATED -j ACCEPT
 
# No smb/windows sharing packets - too much logging
$IPT -A INPUT -p tcp -i eth0 --dport 137:139 -j REJECT
$IPT -A INPUT -p udp -i eth0 --dport 137:139 -j REJECT
 
# Log everything else
# *** Required for psad ****
$IPT -A INPUT -j LOG
$IPT -A FORWARD -j LOG
$IPT -A INPUT -j DROP
 
# Start ipv6 firewall
# echo "Starting IPv6 Wall..."
/root/scripts/start6.fw
 
exit 0

How do I view port scan report?

Simply type the following command:
# psad -S
Sample output (some of the sensitive / personally identified parts have been removed):
[+] psadwatchd (pid: 2540)  %CPU: 0.0  %MEM: 0.0
    Running since: Sun Jul 27 07:14:56 2008

[+] kmsgsd (pid: 2528)  %CPU: 0.0  %MEM: 0.0
    Running since: Sun Jul 27 07:14:55 2008

[+] psad (pid: 2524)  %CPU: 0.0  %MEM: 0.8
    Running since: Sun Jul 27 07:14:55 2008
    Command line arguments: -c /etc/psad/psad.conf
    Alert email address(es): radhika.xyz@xxxxxxxx.co.in

    src:            dst:            chain:  intf:  tcp:  udp:  icmp:  dl:  alerts:  os_guess:
    117.32.xxx.149  xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    118.167.xxx.219 xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    118.167.xxx.250 xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    118.167.xxx.5   xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    122.167.xx.11   xx.22.zz.121    INPUT   eth0   4642  0     0      4    50       -
    122.167.xx.80   xx.22.zz.121    INPUT   eth0   0     11    0      1    2        -
    123.134.xx.34   xx.22.zz.121    INPUT   eth0   20    0     0      2    9        -
    125.161.xx.3    xx.22.zz.121    INPUT   eth0   0     9     0      1    4        -
    125.67.xx.7     xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    190.159.xxx.220 xx.22.zz.121    INPUT   eth0   0     9     0      1    3        -
    193.140.xxx.210 xx.22.zz.121    INPUT   eth0   0     10    0      1    2        -
    202.xx.23x.196  xx.22.zz.121    INPUT   eth0   0     13    0      1    10       -
    202.xx.2x8.197  xx.22.zz.121    INPUT   eth0   0     20    0      2    17       -
    202.97.xxx.198  xx.22.zz.121    INPUT   eth0   0     17    0      2    12       -
    202.97.xxx.199  xx.22.zz.121    INPUT   eth0   0     18    0      2    15       -
    202.97.xxx.200  xx.22.zz.121    INPUT   eth0   0     17    0      2    14       -
    202.97.xxx.201  xx.22.zz.121    INPUT   eth0   0     15    0      2    12       -
    202.97.xxx.202  xx.22.zz.121    INPUT   eth0   0     21    0      2    16       -
    203.xxx.128.65  xx.22.zz.121    INPUT   eth0   12    0     0      2    6        Windows XP/2000
    211.90.xx.14    xx.22.zz.121    INPUT   eth0   1     0     0      2    2        -
    213.163.xxx.9   xx.22.zz.121    INPUT   eth0   0     0     1      2    2        -
    221.130.xxx.124 xx.22.zz.121    INPUT   eth0   0     35    0      2    31       -
    221.206.xxx.10  xx.22.zz.121    INPUT   eth0   0     33    0      2    21       -
    221.206.xxx.53  xx.22.zz.121    INPUT   eth0   0     33    0      2    27       -
    221.206.xxx.54  xx.22.zz.121    INPUT   eth0   0     39    0      2    26       -
    221.206.xxx.57  xx.22.zz.121    INPUT   eth0   0     33    0      2    19       -
    60.222.xxx.146  xx.22.zz.121    INPUT   eth0   0     40    0      2    33       -
    60.222.xxx.153  xx.22.zz.121    INPUT   eth0   0     14    0      1    11       -
    60.222.xxx.154  xx.22.zz.121    INPUT   eth0   0     18    0      2    15       -

    Netfilter prefix counters:
        "SPAM DROP Block": 161519
        "Drop Syn Attacks": 136

    Total scan sources: 95
    Total scan destinations: 1

    Total packet counters:
        tcp:  5868
        udp:  164012
        icmp: 2

How do I remove automatically blocked ips?

Simply type the following command to remove any auto-generated firewall block
# psad -F

How do I view detailed log for each IP address?

Go to /var/log/psad/ip.address/ directory. For example, view log for IP address 11.22.22.33, enter:
# cd /var/log/psad/11.22.22.33
# ls -l

Sample output:
-rw------- 1 root root 2623 2008-07-30 13:02 xx.22.zz.121_email_alert
-rw------- 1 root root   32 2008-07-30 13:02 xx.22.zz.121_packet_ctr
-rw------- 1 root root    0 2008-07-29 00:27 xx.22.zz.121_signatures
-rw------- 1 root root   11 2008-07-30 13:02 xx.22.zz.121_start_time
-rw------- 1 root root    2 2008-07-30 13:02 danger_level
-rw------- 1 root root    2 2008-07-30 13:02 email_count
-rw------- 1 root root 1798 2008-07-29 00:27 whois

yum command: Update / Install Packages Under Redhat Enterprise / CentOS Linux Version 5.x


up2date command was part of RHEL v4.x or older version. You need to use yum command to update and patch the system using RHN or Internet. Use yum command to install critical and non-critical security updates as well as binary packages. Login as the root user to install and update the system.

Task: Register my system with RHN

To register your system with RHN type the following command and just follow on screen instructions (CentOS user skip to next step):
# rhn_register
WARNING! These examples only works with RHEL / CentOS Linux version 5.x or above. For RHEL 4.x and older version use up2date command.

Task: Display list of updated software (security fix)

Type the following command at shell prompt:
# yum list updates

Task: Patch up system by applying all updates

To download and install all updates type the following command:
# yum update

Task: List all installed packages

List all installed packages, enter:
# rpm -qa
# yum list installed

Find out if httpd package installed or not, enter:
# rpm -qa | grep httpd*
# yum list installed httpd

Task: Check for and update specified packages

# yum update {package-name-1}
To check for and update httpd package, enter:
# yum update httpd

Task: Search for packages by name

Search httpd and all matching perl packages, enter:
# yum list {package-name}
# yum list {regex}
# yum list httpd
# yum list perl*

Sample output:
Loading "installonlyn" plugin
Loading "security" plugin
Setting up repositories
Reading repository metadata in from local files
Installed Packages
perl.i386                                4:5.8.8-10.el5_0.2     installed
perl-Archive-Tar.noarch                  1.30-1.fc6             installed
perl-BSD-Resource.i386                   1.28-1.fc6.1           installed
perl-Compress-Zlib.i386                  1.42-1.fc6             installed
perl-DBD-MySQL.i386                      3.0007-1.fc6           installed
perl-DBI.i386                            1.52-1.fc6             installed
perl-Digest-HMAC.noarch                  1.01-15                installed
perl-Digest-SHA1.i386                    2.11-1.2.1             installed
perl-HTML-Parser.i386                    3.55-1.fc6             installed
.....
.......
..
perl-libxml-perl.noarch                  0.08-1.2.1             base
perl-suidperl.i386                       4:5.8.8-10.el5_0.2     updates 

Task: Install the specified packages [ RPM(s) ]

Install package called httpd:
# yum install {package-name-1} {package-name-2}
# yum install httpd

Task: Remove / Uninstall the specified packages [ RPM(s) ]

Remove package called httpd, enter:
# yum remove {package-name-1} {package-name-2}
# yum remove httpd

Task: Display the list of available packages

# yum list all

Task: Display list of group software

Type the following command:
# yum grouplist
Output:
Installed Groups:
   Engineering and Scientific
   MySQL Database
   Editors
   System Tools
   Text-based Internet
   Legacy Network Server
   DNS Name Server
   Dialup Networking Support
   FTP Server
   Network Servers
   Legacy Software Development
   Legacy Software Support
   Development Libraries
   Graphics
   Web Server
   Ruby
   Printing Support
   Mail Server
   Server Configuration Tools
   PostgreSQL Database
Available Groups:
   Office/Productivity
   Administration Tools
   Beagle
   Development Tools
   GNOME Software Development
   X Software Development
   Virtualization
   GNOME Desktop Environment
   Authoring and Publishing
   Mono
   Games and Entertainment
   XFCE-4.4
   Tomboy
   Java
   Java Development
   Emacs
   X Window System
   Windows File Server
   KDE Software Development
   KDE (K Desktop Environment)
   Horde
   Sound and Video
   FreeNX and NX
   News Server
   Yum Utilities
   Graphical Internet
Done

Task: Install all the default packages by group

Install all 'Development Tools' group packages, enter:
# yum groupinstall "Development Tools"

Task: Update all the default packages by group

Update all 'Development Tools' group packages, enter:
# yum groupupdate "Development Tools"

Task: Remove all packages in a group

Remove all 'Development Tools' group packages, enter:
# yum groupremove "Development Tools"

Task: Install particular architecture package

If you are using 64 bit RHEL version it is possible to install 32 packages:
# yum install {package-name}.{architecture}
# yum install mysql.i386

Task: Display packages not installed via official RHN subscribed repos

Show all packages not available via subscribed channels or repositories i.e show packages installed via other repos:
# yum list extras
Sample output:
Loading "installonlyn" plugin
Loading "security" plugin
Setting up repositories
Reading repository metadata in from local files
Extra Packages
DenyHosts.noarch                         2.6-python2.4          installed
VMwareTools.i386                         6532-44356             installed
john.i386                                1.7.0.2-3.el5.rf       installed
kernel.i686                              2.6.18-8.1.15.el5      installed
kernel-devel.i686                        2.6.18-8.1.15.el5      installed
lighttpd.i386                            1.4.18-1.el5.rf        installed
lighttpd-fastcgi.i386                    1.4.18-1.el5.rf        installed
psad.i386                                2.1-1                  installed
rssh.i386                                2.3.2-1.2.el5.rf       installed

Task: Display what package provides the file

You can easily find out what RPM package provides the file. For example find out what provides the /etc/passwd file:
# yum whatprovides /etc/passwd
Sample output:
Loading "installonlyn" plugin
Loading "security" plugin
Setting up repositories
Reading repository metadata in from local files

setup.noarch                             2.5.58-1.el5           base
Matched from:
/etc/passwd

setup.noarch                             2.5.58-1.el5           installed
Matched from:
/etc/passwd
You can use same command to list packages that satisfy dependencies:
# yum whatprovides {dependency-1} {dependency-2}
Refer yum command man page for more information:
# man yum