Shashikant shah

Monday, 26 September 2016

NTP Server configure on Centos 6

NTP Server on Centos 6

1.       Host Details :-
NTP server :- ntp.momagic.com  192.168.1.10
NTP client :- client.example.com 192.168.1.11

Note :- Both machine add ip and hostname in  /etc/hosts file :-

# vim /etc/hosts
192.168.1.10  ntp.momagic.com  
192.168.1.11  client.example.com

Note :- both machine Iptable and Selinux service is disabled.

2.       Install NTP in both machine :-
# yum install ntp

3.       NTP Server side  :-
# cp –rf  /etc/ntp.conf   /etc/ntp.conf.bkp
# vim  /etc/ntp.conf
i)        The drift file is used to store the frequency offset between the system clock running at its nominal frequency.
driftfile /var/lib/ntp/drif
restrict  default  kod  nomodify  notrap  nopeer  noquery
restrict -6 default  kod  nomodify  notrap  nopeer  noquery

§  noquery :- prevents dumping status data from ntpd.
§  notrap  :- prevents control message trap service.
§  nomodify :- prevents all ntpq queries that attempts to modify the server.
§  nopeer :- prevents all packets that attempts to establish a peer association.
§  Kod :-  Kiss-o-death packet is to be sent to reduce unwanted queries
§  The value -6 in the second line allows forces the DNS resolution to the IPV6 address resolution.
ii)       If the localhost needs to have the full access to query or modify.
restrict 127.0.0.1
restrict -6 ::1
iii)     Only allow machines on your own network to synchronize with your NTP server.
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
iv)     NTP Server synchronize below server with internet.
server 0.asia.pool.ntp.org iburst
server 1.asia.pool.ntp.org iburst
server 2.asia.pool.ntp.org iburst
server 3.asia.pool.ntp.org iburst
v)      if the NTP server is disconnected from the internet, NTP server provides time from its local system clock.
server 127.127.1.0
fudge  127.127.1.0 stratum 10
server 192.168.1.10 iburst

includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
logfile /var/log/ntp.log

#  service ntpd start
# chkconfig ntpd on
# ntpq -p 
4.       Client side :-
# vim  /etc/ntp.conf
driftfile /var/lib/ntp/drift
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict -6 ::1
server 192.168.1.10 prefer
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
logfile /var/log/ntp.log 
# service ntpd  start
# chkconfig ntpd on
# ntpq –p
# ntpdate  –u  192.168.1.10
5.       Add Cron job :-
*/5 * * * * /usr/sbin/ntpdate -u 192.168.1.10


Thursday, 28 April 2016

nagios ssh Plugin

#!/bin/bash
#### NO SSH CONNECTION 1FUNCATION AND SSH HAI TO 2FUNCATION RUN.
# Check for missing parameters
if [[ -z "$1" ]] || [[ -z "$2" ]] || [[ -z "$3" ]] || [[ -z "$4" ]]; then
        echo "Missing parameters! Syntax: ./check_ssh.sh <HOSTNAME> <PORT_NO> <WARNING_THRESHOLD> <CRITICAL_THRESHOLD>"
        exit 2
fi

host=$1
port=$2
Warning=$3
Critical=$4

########### check Port ############################################
netstatus=$(netstat -nlp | grep :$port)

if [[ $? == 1 ]]; then
       echo "CRITICAL - PORT NOT ESTABLISHED"
        exit 2
fi
############ ESTABLISHED connection ###############################
command=$(netstat -alntp | grep :$port | grep ESTABLISHED | awk '{print $5}' | cut -d ":" -f1 | sort |uniq)
check_command=$(echo $command | wc -l)

if [[ $command = "" ]];then
 echo "OK - ESTABLISHED"
 exit 0
fi

if [ -f /tmp/.user_count ];then
$(rm -rf /tmp/.user_count)
fi
######### looping ############################
if [ $check_command -gt 0 ];then
loop_ip=$(for ip in $command;
do
command1=$(who | grep $ip | awk {'print $1'})
com=$(who | grep $ip | awk {'print $1'} >> /tmp/.user_count)
echo -e "$(echo $command1) $ip"
done)

fi
##############################################
if [ -f /tmp/.user_count ];then
count=$(wc -l < /tmp/.user_count)
fi
# Connection is Establish---OK;

if [[ "$count"<="$Warning" ]]; then
        echo "OK - ESTABLISHED/Total_user $count "
        echo "$loop_ip"
        exit 0
fi

# Connection is WARNING---WARNING;

if [[ "$count"=>"$Warning" ]] && [[ "$count"<="$Critical" ]]; then
        echo "WARNING - ESTABLISHED/Total_user $count"
        echo "$loop_ip "
        exit 1
fi

# Connection is CRITICAL---CRITICAL;

if [[ "$count"=>"$Critical" ]]; then
       echo "CRITICAL - ESTABLISHED/Total_user $count"      
        echo "$loop_ip "
        exit 2
fi
=====================================

./check_ssh.sh localhost 22 4 5

Wednesday, 20 April 2016

Protect Apache DDoS Attacks Using Mod_evasive Modules



Protect Apache  DDoS Attacks Using Mod_evasive Modules
Denial-of-Service (DoS) attack is an attempt to make a machine or network resource unavailable to its intended users, such as to temporarily or indefinitely interrupt or suspend services of a host connected to the Internet. A distributed denial-of-service (DDoS) is where the attack source is more than one–and often thousands of-unique IP addresses.
What is mod_evasive?
The mod_evasive Apache module, formerly known as mod_dosevasive, helps protect against DoS, DDoS (Distributed Denial of Service), and brute force attacks on the Apache web server. It can provide evasive action during attacks and report abuses via email and syslog facilities.
1.     Installing mod_evasive :-
Centos :- 6.1,  serverIP :- 192.168.1.184
# yum install mod_evasive
# ls -l /etc/httpd/conf.d/mod_evasive.conf
 
2.     Check module :- 
LoadModule evasive20_module modules/mod_evasive20.so
 
# cd /etc/httpd/modules
# ls -l | grep -Ei 'evasive'
# /etc/init.d/httpd start
# chkconfig httpd on
# /etc/init.d/httpd restart
# httpd -M | grep -Ei 'evasive'
 
# vim /etc/httpd/conf.d/mod_evasive.conf
 
LoadModule evasive20_module modules/mod_evasive20.so
 
<IfModule mod_evasive20.c>
               DOSHashTableSize    3097
               DOSPageCount        2
               DOSSiteCount        50
               DOSPageInterval     1
               DOSSiteInterval     1
               DOSBlockingPeriod   10
               DOSEmailNotify      shashi.brain11@gmail.com
               DOSSystemCommand    "sudo /etc/httpd/conf.d/ban_ip.sh %s"
               DOSLogDir           "/var/log/httpd/mod_evasive"
               DOSWhitelist   127.0.0.1
</IfModule>
  1. DOSHashTableSize: This directive specifies the size of the hash table that is used to keep track of activity on a per-IP address basis. Increasing this number will provide a faster look up of the sites that the client has visited in the past, but may impact overall performance if it is set too high.
  2. DOSPageCount: Legitimate number of identical requests to a specific URI (for example, any file that is being served by Apache) that can be made by a visitor over the DOSPageInterval interval.
  3. DOSSiteCount: Similar to DOSPageCount, but refers to how many overall requests can be made to the entire site over the DOSSiteInterval interval.
  4. DOSPageInterval: The page count interval, accepts real number as seconds. Default value is 1 second.
  5. DOSSiteInterval: The site count interval, accepts real number as seconds. Default value is 1 second.
  6. DOSBlockingPeriod: If a visitor exceeds the limits set by DOSSPageCount or DOSSiteCount, his source IP address will be blacklisted during the DOSBlockingPeriod amount of time. During DOSBlockingPeriod, any requests coming from that IP address will encounter a 403 Forbidden error.
  7.  DOSEmailNotify:
    This is an E-mail if provided will send notification once an IP is being blacklisted
  8. DOSSystemCommand:  This is a system command that can be executed once an IP is blacklist if enabled. Where %s is the blacklisted IP, this is designed for system call to IP filter or other tools
  9.  DOSLogDir: This is a directory where mod_evasive stores it’s log
 
# mkdir –p   /var/log/httpd/mod_evasive
# chmod  –R  777 /var/log/httpd/mod_evasive
 
3.     Write a shell script that handles IP blacklisting at the firewall level
 
#vim /etc/httpd/conf.d/ban_ip.sh
 
#!/bin/sh
# IP that will be blocked, as detected by mod_evasive
IP=$1
# Full path to iptables
IPTABLES="/sbin/iptables"
# mod_evasive lock directory
MOD_EVASIVE_LOGDIR=/var/log/httpd/mod_evasive
# Add the following firewall rule (block all traffic coming from $IP)
$IPTABLES -I INPUT -s $IP -j DROP
# Remove lock file for future checks
rm -f "$MOD_EVASIVE_LOGDIR"/dos-"$IP"
 
#chmod  777 /etc/httpd/conf.d/ban_ip.sh
 
 
4.     Enable to Iptable:-
# service iptables start
#iptable –L
#iptable –F
#iptable –t nat –L
#service  iptables save
#chkconfig iptables on 
 
5.     Add the apache user to the sudoers file
 
# vim /etc/sudoers
 
# User_Alias ADMINS = jsmith, mikem
apache ALL=NOPASSWD: /etc/httpd/conf.d/ban_ip.sh
Defaults:apache !requiretty
 
IMPORTANT: As a default security policy, you can only run sudo in a terminal. Since in this case we need to use sudo without a tty, we have to comment out the line that is highlighted in the following image:

# Disable "ssh hostname sudo <cmd>", because it will show the password in clear.
#Defaults    requiretty
# service httpd restart
Testing mod_evasive Setup
Another machine :-
# ab -n 100 -c 10 http://192.168.1.184/
# tail –f /var/log/httpd/evasive/
# iptables –L
Showing :-
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
DROP       all  --  192.168.1.117        anywhere

Wednesday, 13 April 2016

SSH Service Hardening :-



PAM offers very powerful authentication control. You need to use the pam_access PAM module, which is mainly for access management. It provides login access control based on
§  Login names
§  Host or domain names
§  Internet addresses or network IP numbers
§  Terminal line names etc
2. Why pam_access matters?
On a production server, authorized login can come from any networked computer. Therefore, it is important to have tight control over users who are allowed to connect server via OpenSSH server.

3. How do I configure pam_access?
You need to edit following files:
1.    /etc/pam.d/sshd – Linux PAM configuration file.
2.    /etc/security/access.conf – By default rules for access management are taken from configuration this file. When someone logs in, the entry in this scanned and matched against rule. You can specify whether the login will be accepted or refused to user. General syntax is as follows:
permission : username: origins
Where,
§  permission : Permission field should be a “+” (access granted) or “-” (access denied) character.
§  username : Linux system username/login name such as root, shashi etc. You can also specify group names. You can also use special keywod ALL (to match all username).
§  origins : It is a list of one ore more tty names, host name, IP address, domain names that begin with . or special key words ALL or LOCAL

Open /etc/pam.d/sshd file :-
# vim /etc/pam.d/sshd
account    required     pam_access.so
auth       required     pam_sepermit.so


root and shashi user only login in ssh and only one IP allow 192.168.1.150

4.Open file /etc/security/access.conf

# vi /etc/security/access.conf

Append following line:

+: ALL EXCEPT root shashi:192.168.1.150

5. Restart SSH Services.
#/etc/init.d/sshd restart

Check ssh services.
Other IP not able to login ssh server.

Some RULE PAM :-

1.      Block All network with user :-
-:ALL  :  ALL

2.      Only user allow on network :-
+:shashi:192.168.1.0/24
            OR
+:shashi:192.168.1.150

3.      Normal user not able to access root su – command.

/etc/pam.d/su
# Uncomment the following line to require a user to be in the "wheel" group.
auth       required    pam_wheel.so use_uid

Some Normal user use su root access :-
               # usermod -G wheel user1
               
               # cat /etc/group | grep user1
               Wheel:x:10:user1
               User1:x:501:
               # tail  –f   /var/log/secure
 
 
2. Use of X11Forwarding
The display server on the client might have a higher exposure to be attacked, when enabling this option. If forwarding of X11 traffic is not needed, disable it by setting this value to “no”.
 
X11Forwarding no
 
3. Disable rhosts
While not common anymore, rhosts were a weak way to authenticate systems. By default the use of rhosts is already disabled. Make sure to check if it really is.
 
IgnoreRhosts yes
 
4. DNS hostname checking
By default the SSH server can check if the client connecting maps back to the same combination of hostname and IP address. Use this option to perform this basic check.
 
UseDNS yes
 
5. Disable Empty Passwords
You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:
 
PermitEmptyPasswords no
 
6. Disable root Login via SSH
Uncomment it and change the value to “no”:
PermitRootLogin no
 
7. Change Port no 22 in file /etc/ssh/sshd_config
 #Port 22
Port 8022
netstat -anp |grep 8022
 
8.Configure Idle user Log Out Timeout Interval
ClientAliveInterval 300
ClientAliveCountMax 0
You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out).
 
9.Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:
AllowUsers root vivek jerry
DenyUsers saroj anjali foo
 
10. Only use SSH Protocol 2
Since SSH protocol 1 is insecure we need to force SSH server to always use protocol 2
i)                    Strong cryptographic integrity check
ii)                  Separate transport, authentication, and connection protocols
 
Protocol 2
 
11.Change SSH Server Listen Address
By default SSH Server listens on all available interfaces which is in some cases not OK. It is always best, to limit SSH server to listen only on interfaces we want and use for to connect to.
(we can access ssh this two ip)
 
ListenAddress 192.168.1.5 # System IP
ListenAddress 202.54.1.5  #VIP
 
         # netstat -anp |grep 22
 
12.Max Authentication Tries
MaxAuthTries 4
 
13. Log All Information
LogLevel INFO
 
14.Message Of The Day
Banner /etc/motd
 
How to block ssh users after 3 failed login attempts using pam_tally2.so

3.      Edit /etc/pam.d/sshd

auth required pam_tally2.so deny=3 onerr=fail unlock_time=300 

4.      pam_tally2.so uses the file /var/log/tallylog as a counter for the failed logis, if you wish to check the counter you can use the command pam_tally2

[root@nuke]# pam_tally2
5.      If you wish to reset the counter for a user, before the 5 minutes ban 
# pam_tally2 -r -u hacker1