Saturday, July 30, 2016

Turning off or disabling SELinux

Turning off or disabling SELinux

SELinux is a set of extra security restrictions on top of the normal Linux security tools. It gives the systems administrator a finer grain of control than what the kernel typically provides.

But SELINUX can sometimes get in your way. For example, I have had typical services, such as Apache, appear to start up correctly, but remain inaccessible from the outside world because I forgot to allow the apache user rights to open that port or maybe my distro forgot about it. Before you turn off SELinux make sure you know why you are turning it off and the security concerns you might be opening yourself up to.

Test if SELinux is running
You can test to see if SELinux is currently enabled with the following command:

selinuxenabled && echo enabled || echo disabled

Turning off SELinux temporarily
Disabling SELinux temporarily is the easiest way to determine if the problem you are experiencing is related to your SELinux settings. To turn it off, you will need to become the root users on your system and execute the following command:

echo 0 > /selinux/enforce
This temporarily turns off SELinux until it is either re-enabled or the system is rebooted. To turn it back on you simply execute this command:

echo 1 > /selinux/enforce
As you can see from these commands what you are doing is setting the file /selinux/enforce to either '1' or '0' to denote 'true' and 'false'.

Configuring SELinux to log warnings instead of block
You can also configure SELinux to give you a warning message instead of actually prohibiting the action. This known as permissive mode. To change SELinux's behavior to permissive mode you need to edit the configuration file. On Fedora and RHEL systems that file is located at /etc/selinux/config. You need to change the SELINUX option to permissive like so:

SELINUX=permissive
Note that these changes will not take effect until the system is rebooted, which is why the first section comes in handy on a system you either cannot or do not want to reboot right now.

Completely turning off SELinux
To completely disable SELinux instead of setting the configuration file to permissive mode you set it to disabled like:

SELINUX=disabled
You will need to reboot your system or temporarily set SELinux to non-enforcing mode to create the desired effect like the example above.

--------------------------------------------------------------------------------------------------------

Disabling SELinux

1) Configure SELINUX=disabled in the /etc/selinux/config file:
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

2)Reboot your system. After reboot, confirm that the getenforce command returns Disabled:
~]~ getenforce
Disabled

-------------------------------------------------------------------------------------------------------------
Viewing the Status of SELinux

The sestatus command provides a configurable view into the status of SELinux. The simplest form of this command shows the following information:

[root@localhost ~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 21
Policy from config file:        targeted


The -v option includes information about the security contexts of a series of files that are specified in /etc/sestatus.conf:

[root@localhost ~]# sestatus -v
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 21
Policy from config file:        targeted

Process contexts:
Current context:                user_u:system_r:unconfined_t
Init context:                   system_u:system_r:init_t
/sbin/mingetty                  system_u:system_r:getty_t
/usr/sbin/sshd                  system_u:system_r:unconfined_t:s0-s0:c0.c1023

The -b displays the current state of booleans. You can use this in combination with grep or other tools to determine the status of particular booleans:

[root@host2a ~]# sestatus -b | grep httpd | grep on$
httpd_builtin_scripting           on
httpd_disable_trans               on
httpd_enable_cgi                  on
httpd_enable_homedirs             on
httpd_unified                       on

--------------------------------------------------------------------------------------------------------------

Enable or Disable SELinux

From the command line, you can edit the /etc/sysconfig/selinux file. This file is a symlink to /etc/selinux/config. The configuration file is self-explanatory. Changing the value of SELINUX or SELINUXTYPE changes the state of SELinux and the name of the policy to be used the next time the system boots.

 [root@host2a ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0


Changing the Mode of SELinux Using the GUI

Use the following procedure to change the mode of SELinux using the GUI.

Note
You need administrator privileges to perform this procedure.


On the System menu, point to Administration and then click Security Level and Firewall to display the Security Level Configuration dialog box.
Click the SELinux tab.
In the SELinux Setting select either Disabled, Enforcing or Permissive, and then click OK.
If you changed from Enabled to Disabled or vice versa, you need to restart the machine for the change to take effect.
Changes made using this dialog box are immediately reflected in /etc/sysconfig/selinux.


Scripts

1) Create svnupload.sh  -------local svn script

vim /usr/local/subversion/harry/svnupload.sh

#/bin/sh!
home_dir=/usr/local/subversion/harry
#> /usr/local/subversion/harry/test.txt
svnlook changed /usr/local/subversion/harry >> /usr/local/subversion/harry/test.txt
cat  /usr/local/subversion/harry/test.txt| sed 's/^[A-Z]//g'| sed 's/^  //g' >> /usr/local/subversion/harry/upload.txt
for i in `cat /usr/local/subversion/harry/upload.txt`;do svn export --username 'harry' --password 'harry@123' --no-auth-cache  http://localhost:82/harry/$i /mnt/httpdocs/harry/$i --force;done
for i in `cat /usr/local/subversion/harry/upload.txt`;do chown -R apache:apache /mnt/httpdocs/harry/$i ;done
for i in `cat /usr/local/subversion/harry/upload.txt`;do chmod -R 775 /mnt/httpdocs/harry/$i ;done
> /usr/local/subversion/harry/test.txt
> /usr/local/subversion/harry/upload.txt

Chech localhost port
######################## THE END #####################

2) Jenkins Script

#!/bin/bash
################## setting function Document Root##########################

t1="project name"
url="http://mastersvn.hungamatech.com/svn/"$t1""
htdocs="/usr/local/apache/htdocs"

################ setting functions for backup Dir #################

DATE_TIME=`date +%Y_%m_%d_%H_%M_%S`
backdir=/tmp/"$t1"_$DATE_TIME
/bin/mkdir $backdir
cd $backdir

#################### setting authentication function for svn user #######################
uname=svn
passwd="svn123"

################## setting function for tmpfile ##########
tmpfile=/tmp/svnchanged_tmpfile.txt
tarfile=/tmp/tarfiles_"$t1".txt

###############  calling Head Revision from mastersvn URL #####################

[ -z $1 ] && Revision=HEAD || Revision=$1
svn log --non-interactive --username=$uname --password="$passwd" --verbose  -r $Revision $url |grep -E 'M /|A /|D /|R /'| awk {'print $2'}|sed -e 's/^\///' > $tmpfile

###################### taking backup of previous revision  ################

for i in `cat $tmpfile`;do /bin/cp $htdocs/$i $backdir/$i ;done
/bin/tar zcvf /tmp/$DATE_TIME.tar.gz .
/bin/rm -rf $backdir

######## exporting Head Revision from mastersvn URL  to document root ##############

for i in `cat $tmpfile`;do svn export --username=$uname --password="$passwd" --no-auth-cache $url/$i $htdocs/$i --force;done
for i in `cat $tmpfile`;do chown -R apache:apache $htdocs/$i ;done

####################### Exporting files to Remote servers (192.168.10.11) ########
scp $tmpfile root@192.168.10.XX:/tmp/temp_svncheck/
ssh root@192.168.10.XX /root/scripts/billing_svnexport.sh

##################### truncating tmpfile ######################
> $tmpfile

########################### THE END #######################################

2 ) for SVN

#/bin/sh!
home_dir=/tmp/temp_svncheck/
tmpfile=/tmp/temp_svncheck/svnchanged_tmpfile.txt

for i in `cat $tmpfile`;do svn export --username="svn" --password="svn123" --no-auth-cache http://mastersvn.hungamatech.com/svn/test/$i /usr/local/apache/htdocs/$i --force;done
for i in `cat $tmpfile`;do chown -R apache:apache /usr/local/apache/htdocs/$i ;done
for i in `cat $tmpfile`;do chmod -R 775 /usr/local/apache/htdocs/$i ;done
> $tmpfile

########################### THE END #######################################

!#/bin/sh
$1=access_log_4.txt
for i in {1..30}
do
   less access_log_4.txt | grep "04:$i" > accesslog_4_$i.txt
done
########################### THE END #######################################

#!bin/bash

curDay=`date +"%Y%m%d"`
#echo "$curDay"
find /opt/apache-tomcat-8.0.20/logs/ -mtime -7 -print | grep 'localhost_access_log' | sort | while read LINE; do echo "$LINE : "`bzgrep 'create' $LINE | wc -l`; done > /opt/apache-tomcat-8.0.20/logs/data/unique_user_count_"$curDay".log

########################### THE END #######################################

#!bin/bash

var=`ps aux|grep 'apache-tomcat-8.0.20'|wc -l`

current=`date +"%Y-%m-%d %T"`
if [ $var -lt 2 ]; then
        echo $current" --> tomcat is not runing."
        `sh /opt/apache-tomcat-8.0.20/bin/startup.sh`
        echo $current" --> tomcat was stop bcz of some reason, but now started."
else
        echo $current" --> tomcat is runing"
fi

########################### THE END #######################################

I have the following backup script that packs my current folders contents to an external hard disk (in my company we have enough hard disks so there is no really need to do incremental backups)
Code:
echo '----- Backup Started '`date` >>/root/backup/backuperrors.txt
tar -zcvf /media/a9f299d7-fcbc28b3f3c0/user-host`date '+%d-%B-%Y'`.tar.gz /etc /root /home 2>> /root/backup/backuperrors.txt

########################### THE END #######################################

Script for RDS (More 10m runing QUERY KILL)

[root@localhost_scripts]# cat newRDS_BSC.sh
HOST='mtp2newreadreplicanewttp.cgckm3nudvpd.us-east-1.rds.amazonaws.com'
USER='user1'
PASS='password123'
TIME='600'

for i in `mysql -h $HOST  -u $USER -p$PASS -A --skip-column-names -e "SELECT ID, USER, TIME FROM information_schema.PROCESSLIST WHERE USER='$USER' AND TIME > $TIME;" | grep "$USER" | awk '{print $1}'` ;
        do
        mysql -h $HOST -u $USER -p$PASS -A --skip-column-names -e "KILL QUERY $i;" ;
        echo "KILL QUERY $i;"
done

########################### THE END #######################################

Script for RDS (Kill all ruing Query of user1 user)

[root@localhost_scripts]# cat newRDS_BSC1.sh
for i in `mysql -h mtp2newreadreplicanewttp.cgckm3nudvpd.us-east-1.rds.amazonaws.com  -u'user1' -p'password123' -A --skip-column-names -e"SHOW PROCESSLIST" | grep "user1" | awk '{print $1}'` ; do mysql -h mtp2newreadreplicanewttp.cgckm3nudvpd.us-east-1.rds.amazonaws.com -u 'user1' -p'password123' -A --skip-column-names -e"KILL QUERY $i" ; done

########################### THE END #######################################

Kill test user query RDS

[root@RDS ~]# for i in `mysql -uroot -padmin123 -A --skip-column-names -e"SHOW PROCESSLIST" | grep "test" | awk '{print $1}'` ; do mysql -uroot -padmin123 -A --skip-column-names -e"kill $i;" ; done

########################### THE END #######################################
Delete   30 days old logs

#!/bin/bas
#take output in a file
find  /solrd/apache-tomcat-7.0.64/logs/ -type f -mtime +30 > /tmp/solrd_apache-7.064

#delete 30 days old files
find  /solrd/apache-tomcat-7.0.64/logs/ -type f -mtime +30 -exec rm -f {} +

#take output in a file

find /tomcat2001/apache-tomcat-7.0.64/logs/ -type f -mtime +30 > /tmp/tomcat2001_tomcat-7.064
#delete 30 days old files

find /tomcat2001/apache-tomcat-7.0.64/logs/ -type f -mtime +30 -exec rm -f {} +

########################### THE END #######################################
Zip log before 2day
#!/bin/sh
find /mnt/logs/apilogs -type f -name "*.txt" -mtime +2 > /tmp/apilogs.txt
for i in `cat /tmp/apilogs.txt`;
do bzip2 $i;
done########################### THE END #######################################

#!/bin/sh

find /mnt/logs/httplogs -type f -name "*.log" -mtime +2 > /tmp/httplogs.txt

for i in `cat /tmp/httplogs.txt`;

do bzip2 $i;

done

########################### THE END #######################################
[root@intl-live htdocs]# cat svnupload.sh
#/bin/sh!
home_dir=/usr/local/subversion/htdocs147/
svnlook changed /usr/local/subversion/htdocs >> /usr/local/subversion/htdocs/test.txt
cat /usr/local/subversion/htdocs147/test.txt| sed 's/^[A-Z]//g'| sed 's/^ //g' >> /usr/local/subversion/htdocs147/upload.txt
sshpass -p 'br!$b@nexxx' scp /usr/local/subversion/htdocs/upload.txt root@192.168.10.x:/usr/local/subversion/svnscript/upload.txt
> /usr/local/subversion/htdocs147/test.txt
> /usr/local/subversion/htdocs147/upload.txt
sshpass -p 'br!$b@ne134' ssh root@192.168.10.x 'sh -x /usr/local/subversion/svnscript/svnupload.sh'
########################### THE END #######################################
#!/bin/bash
SSH='ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
$SSH svn@10.171.x.x "sudo /bin/chown -R svn:svn /mnt/httpdocs/project_name"
rsync -avzOp /var/lib/jenkins/jobs/hisense/workspace/ -e "$SSH" svn@10.171.x.x:/mnt/httpdocs/project_name  --exclude '.svn'
$SSH svn@10.171.x.x "sudo /bin/chown -R apache:apache /mnt/httpdocs/project_name"

$SSH svn@10.237.x.x "sudo /bin/chown -R svn:svn /mnt/httpdocs/project_name"
rsync -avzOp /var/lib/jenkins/jobs/project_name/workspace/ -e "$SSH" svn@10.237.x.x:/mnt/httpdocs/project_name --exclude '.svn'
$SSH svn@10.237.x.x "sudo /bin/chown -R apache:apache /mnt/httpdocs/project_name"

Local SVN


Step 1: Setup Yum Repository

Firstly we need to configure yum repository in our system.
Create a new repo file /etc/yum.repos.d/wandisco-svn.repo and add following
content as per your operating system version.

[WandiscoSVN]
name=Wandisco SVN Repo
baseurl=http://opensource.wandisco.com/centos/$releasever/svn-1.8/RPMS/$basearch/
enabled=1

gpgcheck=0

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

Step 2: Install Subversion Package

Before installing latest package remove existing subversion packages from system to remove conflict.

# yum remove subversion*
Now install latest available Subversion package using yum command line package manager utility.

# yum clean all

yum install mod_dav_svn subversion

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

Step 3: Verify Subversion Version

At this stage you have successfully install Subversion client on your system. Lets use following command to verify version of svn client.

[root@localhost /]#  svn --version
svn, version 1.8.16 (r1740329)
   compiled Jul  6 2016, 11:38:59 on x86_64-redhat-linux-gnu

Copyright (C) 2016 The Apache Software Foundation.
This software consists of contributions made by many people;
see the NOTICE file for more information.
Subversion is open source software, see http://subversion.apache.org/

The following repository access (RA) modules are available:

* ra_svn : Module for accessing a repository using the svn network protocol.
  - with Cyrus SASL authentication
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme
* ra_serf : Module for accessing a repository via WebDAV protocol using serf.
  - using serf 1.3.7
  - handles 'http' scheme
  - handles 'https' scheme

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

Step 4 : Local SVN Configuration step by step

1) Login to the server on which we need to create the svn.

2) Go to svn directory:
create mkdir -p /usr/local/subversion direcoty
cd /usr/local/subversion
a. Create the folder for which we need to create svn (eg: harry).
To create a svn folder the command is as below.
svnadmin create /usr/local/subversion/harry
chown apache.apache -R harry     -----------------chnage owner permission
chmod 775 -R harry     --------------------------------change folder permission

3)Create svnupload.sh
vim /usr/local/subversion/harry/svnupload.sh


script 1   

#/bin/sh!
home_dir=/usr/local/subversion/harry
svnlook changed /usr/local/subversion/harry >> /usr/local/subversion/harry/test.txt
cat  /usr/local/subversion/harry/test.txt| sed 's/^[A-Z]//g'| sed 's/^  //g' >> /usr/local/subversion/harry/upload.txt
for i in `cat /usr/local/subversion/harry/upload.txt`;do svn export --username 'harry' --password 'harry@123' --no-auth-cache  http://localhost:82/harry/$i /mnt/httpdocs/harry/$i --force;done
for i in `cat /usr/local/subversion/harry/upload.txt`;do chown -R apache:apache /mnt/httpdocs/harry/$i ;done
for i in `cat /usr/local/subversion/harry/upload.txt`;do chmod -R 775 /mnt/httpdocs/harry/$i ;done
> /usr/local/subversion/harry/test.txt
> /usr/local/subversion/harry/upload.txt


script 2

#!/bin/sh
home_dir=/usr/local/subversion/myproject1/
svnlook changed /usr/local/subversion/myproject1 >> /usr/local/subversion/myproject1/test.txt
cat /usr/local/subversion/myproject1/test.txt| sed 's/^[A-Z]//g'| sed 's/^  //g' >> /usr/local/subversion/myproject1/upload.txt
for i in `cat /usr/local/subversion/myproject1/upload.txt`;do svn export --username "svn" --password "Nvs12#4" --no-auth-cache http://localhost/myproject1/$i /var/www/html/$i --force;done
for i in `cat /usr/local/subversion/myproject1/upload.txt`;do chown -R apache:apache /var/www/html/$i ;done
for i in `cat /usr/local/subversion/myproject1/upload.txt`;do chmod -R 775 /var/www/html/$i ;done
cat /usr/local/subversion/myproject1/test.txt |grep D | sed 's/^[A-Z]//g'| sed 's/^  //g' >> /usr/local/subversion/myproject1/delete.txt
for i in `cat /usr/local/subversion/myproject1/delete.txt`;do /bin/rm –rf /var/www/html/$i ;done
> /usr/local/subversion/myproject1/test.txt
> /usr/local/subversion/myproject1/upload.txt
> /usr/local/subversion/myproject1/delete.txt


chown apache.apache /usr/local/subversion/harry/svnupload.sh


4) Create post-commit file
Path : /usr/local/subversion/harry/hooks/
rename post-commit.tmpl to post-commit
chmod +x post-commit

edit post-commit and disable 
vim /usr/local/subversion/harry/hooks/post-commit
#REPOS="$1"
#REV="$2"

#mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf

/bin/sh -x /usr/local/subversion/harry/svnupload.sh ----------------------add this entry

5)Add user in svn

htpasswd -c /var/.htpasswd harry ------------- to create svn user

htpasswd -m /var/.htpasswd john (user name)  -------------------to add user under svn

6) Go to the configuration file of apache. The configuration file may be httpd.conf or it may be
in conf.d/filename.conf.(In this the configuration file is in conf.d directory.)

cd /etc/httpd/conf.d/  -----------------add project name 

vim harry.conf

<VirtualHost *:81>

        ServerName harry.example.com
        DocumentRoot /var/www/html/harry
        <Directory /usr/local/subversion/harry>
          AuthType Basic
          AuthName "Authentication Required"
          AuthUserFile /var/.htpasswd
          Require valid-user
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
#        ErrorLog "|rotatelogs /mnt/log/bhsvn/errorsvn-%Y-%m-%d.log 86400"
#        CustomLog "|rotatelogs /mnt/log/bhsvn/accesssvn-%Y-%m-%d.log 86400" combined

<Location /harry>
       DAV svn
       SVNPath /usr/local/subversion/harry
</Location>

</VirtualHost>

-----------------------------------------------------------------------------------------------------
7)  chmod 775 svnupload.sh    ---change script permission
     chmod +x svnupload.sh    -----prove executive permission

8) cd /var/www/html/ -------------------document root path
mkdir harry
chmod 775 harry
chown apache. harry

 /etc/init.d/httpd reload   ----- reload httpd service

take checkout and try to upload code through local svn

http://localhost:81/harry

Add repository in AMI server (AWS Image) 2016.3 version

 Add repository in AMI server (AWS Image) 2016.3 version

Go to the repository location and create repo.

 cd /etc/yum.repos.d/

 1) amzn-main.repo

[root@ip-10-15-1-239 yum.repos.d]# cat amzn-main.repo
[amzn-main]
name=amzn-main-Base
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/main/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=1
retries=5
timeout=10
report_instanceid=yes

[amzn-main-debuginfo]
name=amzn-main-debuginfo
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/main/debuginfo/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=0
retries=5
timeout=10
report_instanceid=yes


2) amzn-nosrc.repo

[root@ip-10-15-1-239 yum.repos.d]# cat amzn-nosrc.repo
[amzn-nosrc]
name=amzn-nosrc-Base
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/nosrc/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=0
retries=5
timeout=10
report_instanceid=yes


3) amzn-preview.repo

[root@ip-10-15-1-239 yum.repos.d]# cat amzn-preview.repo
[amzn-preview]
name=amzn-preview-Base
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/preview/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=0
retries=5
timeout=10
report_instanceid=yes

[amzn-preview-debuginfo]
name=amzn-preview-debuginfo
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/preview/debuginfo/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=0
retries=5
timeout=10
report_instanceid=yes


4) amzn-updates.repo

[root@ip-10-15-1-239 yum.repos.d]# cat amzn-updates.repo
[amzn-updates]
name=amzn-updates-Base
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/updates/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=1
retries=5
timeout=10
report_instanceid=yes

[amzn-updates-debuginfo]
name=amzn-updates-debuginfo
mirrorlist=http://repo.$awsregion.$awsdomain/$releasever/updates/debuginfo/mirror.list
mirrorlist_expire=300
metadata_expire=300
priority=10
failovermethod=priority
fastestmirror_enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga
enabled=0
retries=5
timeout=10
report_instanceid=yes


5) epel.repo

[root@ip-10-15-1-239 yum.repos.d]# cat epel.repo
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 6 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch/debug
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-6&arch=$basearch
failovermethod=priority
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 6 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/6/SRPMS
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-6&arch=$basearch
failovermethod=priority
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=1



Netstat (Network Statistics)

Netstat

In computing, netstat (network statistics) is a command-line tool that displaysnetwork connections (both incoming and outgoing), routing tables, and a number of network interface (network interface controller or software-defined network interface) and network protocol statistics. It is available on Unix, Unix-like, and Windows NT-based operating systems.
It is used for finding problems in the network and to determine the amount of traffic on the network as a performance measurement.

Check all the recently logged user:-
[root@localhost ~]# last
This will show you the all current logged in users.

check loged in user and the user never logged in:-
[root@localhost ~]# lastlog
This will show you all the logged in user and the user never logged in.

To check listening and connected socket:-
 [root@localhost ~]# netstat

To check all the open TCP connected socket:-
[root@localhost ~]# netstat -tnlp

To check all the open UDP connected socket:-
 [root@localhost ~]# netstat -unlp

To check both tcp/UDP socket:
 [root@localhost ~]# netstat -tunlp

Check all the tcp based current connection:-
 [root@localhost ~]# netstat -ant

Nmap(Network map)

Nmap(Network map)

Mmap:- is a powerfull scanner available in Linux system using nmap you can scan the remote server open socket as well you can check the ping status and and latency comming for any ip address.
You can also check which socket is using which application and the version of the applications.

Note read man page for more information:-

Some nmap switch:-
-sP:- this show only the ping status( like it will display host is up and latency for the IP)

-PR:- ARP (Address Resolution Protocol) ping scan.

-p21:- This swithc will scan the perticular port

-A :- Enables OS detection and application Version detection with application port
Installing nmap:-
[tushar@localhost ~]$ yum install nmap

1.IP Scanning with range:-
[tushar@localhost ~]$ nmap -sP 192.168.8.0/24
[tushar@localhost ~]$ nmap -sP 192.168.8.9-50

2.Port Scanning with range port 20 – port 500
[tushar@localhost ~]$ nmap 192.168.8.9 -p20-500
[tushar@localhost ~]$ nmap -p21,22,80 192.168.8.9

3.Scanning Operating system on target IP:-
[tushar@localhost ~]$ nmap -O 192.168.8.10

4.nmap Faster Execution faster scan, use -T4
[tushar@localhost ~]$ nmap -A -T4 192.168.8.9

5.Version detection:-
[tushar@localhost ~]$ nmap -A -T4 -F 192.168.8.9
[tushar@localhost ~]$ nmap -A -T4 192.168.8.9

6.Choose between TCP and UDP protocol
[tushar@localhost ~]$ nmap -p T:3000-4000 192.168.8.9

7. Chek Only UDP:-
[tushar@localhost ~]$ nmap -sU 192.168.8.9

8.check Only TCP:-
[tushar@localhost ~]$ nmap -sS 192.168.8.9

IP TABLES ( FIREWALL ) - 2

IPtables

What is IP tables:- Originally, the most popular firewall/NAT package running on Linux was ipchains, but it had a number of shortcomings. To rectify this, the Netfilter organization decided to create a new product called iptables, giving it such improvements as:
Better integration with the Linux kernel with the capability of loading iptables-specific kernel modules designed for improved speed and reliability.
Stateful packet inspection. This means that the firewall keeps track of each connection passing through it and in certain cases will view the contents of data flows in an attempt to anticipate the next action of certain protocols. This is an important feature in the support of active FTP and DNS, as well as many other network services.
Filtering packets based on a MAC address and the values of the flags in the TCP header. This is helpful in preventing attacks using malformed packets and in restricting access from locally attached servers to other networks in spite of their IP addresses.
System logging that provides the option of adjusting the level of detail of the reporting.
Better network address translation.
Support for transparent integration with such Web proxy programs as Squid.
A rate limiting feature that helps iptables block some types of denial of service (DoS) attacks.
Considered a faster and more secure alternative to ipchains, iptables has become the default firewall package installed under RedHat and Fedora Linux.

Notes:- Iptables work on the network layer and transport layer of OSI model.
1. check where ip table resides:-
[root@noc boot]# which iptables

2. check ipables rpm:-
[root@noc boot]# rpm -qa |grep iptables
iptables-ipv6-1.4.7-4.el6.x86_64
iptables-1.4.7-4.el6.x86_64

3. check the installed file of iptables:-
[root@noc ~]# rpm -ql iptables-1.4.7-4.el6.x86_64

4. As we know it is default compiled with the kernal to check its module check the kernal:- change you directory to boot
[root@noc ~]#cd /boot
[root@noc ~]# ls -ltr
config-2.6.32-220.el6.x86_64( this is the kernal open using vim command and check the iptable is complied or not)

5. Lets talk about target:-A firewall rule specifies criteria for a packet, and a target. If the packet does not match, the next rule in the chain is the examined; if it does match, then the next rule is specified by the value of the target, which can be the name of a user-defined chain or one of the special values ACCEPT, DROP, QUEUE, or RETURN. ACCEPT means to let the packet through. DROP means to drop the packet on the floor. QUEUE means to pass the packet to userspace. (How the packet can be received by a userspace process differs by the particu- lar queue handler. 2.4.x and 2.6.x kernels up to 2.6.13 include the ip_queue queue handler. Kernels 2.6.14 and later additionally include the nfnetlink_queue queue handler. Packets with a target of QUEUE will be sent to queue number ’0’ in this case. Please also see the NFQUEUE target. RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet.

6.Targets And Jumps:- Each firewall rule inspects each IP packet and then tries to identify it as the target of some sort of operation. Once a target is identified, the packet needs to jump over to it forfurther processing. Below are the lists of built-in targets that iptables uses.
1. filter:-This is the default table (if no -t option is passed). It contains the built-in chains INPUT (for packets destined to local sockets), FORWARD(for packets being routed through the box), and OUTPUT (for locally-generated packets).
2. nat:-This table is consulted when a packet that creates a new connection is encountered. It con-
sists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out).

3. mangle:-This table is used for specialized packet alteration. Until kernel 2.4.17 it had two built-in
chains: PREROUTING (for altering incoming packets before routing) and OUTPUT (for altering
locally-generated packets before routing). Since kernel 2.4.18, three other built-in chains are also supported: INPUT (for packets coming into the box itself), FORWARD (for altering packets being routed through the box), and POSTROUTING (for altering packets as they are about to go out).

4. raw:- This table is used mainly for configuring exemptions from connection tracking in combination with the NOTRACK target. It registers at the netfilter hooks with higher priority and is thus called before ip_conntrack, or any other IP tables. It provides the following built-in chains: PREROUTING (for packets arriving via any network interface) OUTPUT (for packets generated by local processes) .

7. JUMPS:- Once a target is identified, the packet needs to jump over to it forfurther processing. Below are the lists of built-in targets that iptables uses.
1. ACCEPT
2.DROP
3.LOG
4.REJECT
5.DNAT
6.SNAT
7.MASQUERADE

 8. General Iptables Match Criteria:-
-t(table):-If you don't specify a table, then the filter table is assumed. As discussed before, the possible built-in tables include: filter,nat, mangle
-j(target):-Jump to the specified target chain when the packet matches the current rule.
-A:- Append rule to end of a chain
-F:- (Flush) Deletes all the rules in the selected table
-p (protocol-type):-Match protocol. Types include, icmp, tcp, udp, and all
-s (ip-address):-Match source IP address
-d (ip-address):-Match destination IP address
-i (interface-name):-Match "input" interface on which the packet enters.
-o (interface-name):-Match "output" interface on which the packet exits.

9.Common TCP and UDP Match Criteria:-
-p tcp --sport <port>:- TCP source port. Can be a single value or a range in the format: start-port-number:end-port-number
-p tcp --dport <port>:- TCP destination port. Can be a single value or a range in the format: starting-port:ending-port
-p tcp –syn:- Used to identify a new TCP connection request. ! --syn means, not a new connection request
-p udp --sport <port>:- UDP source port. Can be a single value or a range in the format: starting-port:ending-port
-p udp --dport <port>:- UDP destination port. Can be a single value or a range in the format: starting-port:ending-port

10. Displaying the Status of Your Firewall:-
[root@noc ~]# iptables -L
or
[root@noc ~]# iptables -L -n -v
Where:-
-L : List rules.
-v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively.
-n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing.
11. To inspect firewall with line numbers, enter:-
[root@noc ~]# iptables -n -L -v –line-numbers
12. To display INPUT or OUTPUT chain rules, enter:-
[root@noc ~]# iptables -L INPUT -n -v
[root@noc ~]# iptables -L INPUT -n -v
13. Stop / Start / Restart the Firewall:-
14. Stop and flush the firewall:-
[root@noc ~]# iptables -F (Deleting (flushing) all the rules)
[root@noc ~]# iptables -X (Delete chain).
[root@noc ~]# iptables -t nat -F (Select table (called nat or mangle) and delete/flush rules.)
[root@noc ~]# iptables -t nat -X[root@noc ~]# iptables -t mangle -F[root@noc ~]# iptables -t mangle -X
[root@noc ~]# iptables -P INPUT ACCEPT (Set the default policy (such as DROP, REJECT, or ACCEPT)
[root@noc ~]# iptables -P OUTPUT ACCEPT[root@noc ~]# iptables -P FORWARD ACCEPT
15. Delete Firewall Rules:-
1. To display line number along with other information for existing rules, enter:-
[root@noc ~]# iptables -L INPUT -n –line-numbers
[root@noc ~]# iptables -L OUTPUT -n –line-numbers
[root@noc ~]# iptables -L OUTPUT -n --line-numbers | less
[root@noc ~]# iptables -L OUTPUT -n --line-numbers | grep 192.168.8.9
2. You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter:-
[root@noc ~]# iptables -D INPUT 4
1. OR find source 192.168.8.9 and delete from rule:
[root@noc ~]# iptables -D INPUT -s 192.168.8.9 -j DROP

16. Inserting Firewall rules:-
Bllock all the port for perticular host and subent:- this will close all the port for this host
[root@noc ~]#iptables -A INPUT -s 192.168.122.111 -j DROP
[root@noc ~]#service iptables save
Now go to the server and tray to access

17 .Set the Default Firewall Policies:
1. To drop all traffic:-
[root@noc ~]# iptables -P INPUT DRO
[root@noc ~]# iptables -P OUTPUT DROP
[root@noc ~]# iptables -P FORWARD DROP
[root@noc ~]# iptables -L -v -n
Note:- #### you will not able to connect anywhere as all traffic is dropped ###

18. Only Block Incoming Traffic:-
1. drop all incoming / forwarded packets, but allow outgoing traffic, enter:
[root@noc ~]# iptables -P INPUT DROP
[root@noc ~]# iptables -P FORWARD DROP
[root@noc ~]# iptables -P OUTPUT ACCEPT
[root@noc ~]# iptables -A INPUT -m state --state NEW,ESTABLISHED -jACCEPT

Note: now you will be able to send the traffice to outside but the incomming traffic will be blocked.

19. Drop Private Network Address On Public Interface:-
IP spoofing is nothing but to stop the following IPv4 address ranges for private networks on your public interfaces. Packets with non-routable source addresses should be rejected using the following syntax:
[root@noc ~]# iptables -A INPUT -i eth1 -s 192.168.8.0/24 -j DROP
[root@noc ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

20. Blocking an IP Address or sybnet (BLOCK IP):- to block any perticular IP address.
[root@noc ~]# iptables -A INPUT -s 192.168.8.9 -j DROP
[root@noc ~]# iptables -A INPUT -s 192.168.8.0/24 -j DROP

21.Block Incoming Port Requests (BLOCK PORT):-
[root@noc ~]# iptables -A INPUT -p tcp --dport 80 -j DROP
[root@noc ~]# iptables -A INPUT -i eth1 -p tcp --dport 80 -j DROP

22. To block port 80 only for an ip address:-
[root@noc ~]# iptables -A INPUT -p tcp -s 1.2.3.4 --dport 80 -j DROP
[root@noc ~]# iptables -A INPUT -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j DROP

23. Block Outgoing IP Address:-
[root@noc ~]# iptables -A OUTPUT -d 192.168.8.9 -j DROP

24.You can use a subnet as follows:-
[root@noc ~]# iptables -A OUTPUT -d 192.168.8.0/24 -j DROP
[root@noc ~]# iptables -A OUTPUT -o eth1 -d 192.168.8.0/24 -j DROP

25. Log and Drop Packets:-Type the following to log and block IP spoofing on public interface called eth1.
[root@noc ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: "
[root@noc ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

By default everything is logged to /var/log/messages file.
[root@noc ~]# tail -f /var/log/messages[root@noc ~]# grep --color 'IP SPOOF' /var/log/messages

26.Log and Drop Packets with Limited Number of Log Entries:-
[root@noc ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
[root@noc ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

27.Block or Allow ICMP Ping Request
[root@noc ~]# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP[root@noc ~]# iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP

Ping responses can also be limited to certain networks or hosts:-

[root@noc ~]#iptables -A INPUT -s 192.168.1.0/24 -p icmp --icmp-type echo-request -j ACCEPT

28.The following only accepts limited type of ICMP requests:
### ** assumed that default INPUT policy set to DROP ** ##########
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
## ** all our server to respond to pings ** ##
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

29.Open Range of Ports:-
[root@noc ~]# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7010 -j ACCEPT

30.Open Range of IP Addresses
## only accept connection to tcp port 80 (Apache) if ip is between 192.168.1.100 and 192.168.1.200 ##
[root@noc ~]# iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT


#############################   END  ###############################

25 Most Frequently Used Linux IPTables Rules


# 1. Delete all existing rules
iptables -F

# 2. Set default chain policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# 3. Block a specific ip-address
#BLOCK_THIS_IP="x.x.x.x"
#iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP

# 4. Allow ALL incoming SSH
#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

# 5. Allow incoming SSH only from a sepcific network
#iptables -A INPUT -i eth0 -p tcp -s 
192.168.200.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

# 6. Allow incoming HTTP
#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

# Allow incoming HTTPS
#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. MultiPorts (Allow incoming SSH, HTTP, and HTTPS)
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
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

# 9. Allow outgoing SSH only to a specific network
#iptables -A OUTPUT -o eth0 -p tcp -d 
192.168.101.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
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

# 11. Load balance incoming HTTPS traffic
#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. Ping from inside to outside
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

# 13. Ping from outside to inside
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

# 14. Allow loopback access
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# 15. Allow packets from internal network to reach external network.
# if eth1 is connected to external network (internet)
# if eth0 is connected to internal network (192.168.1.x)
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

# 16. Allow outbound DNS
#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
# rpcinfo -p | grep ypbind ; This port is 853 and 850
#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

# 18. Allow rsync 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
iptables -A INPUT -i eth0 -p tcp -s 
192.168.200.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
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
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

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

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
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

# 24. Port forwarding 422 to 22
iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 
192.168.102.37:22
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
iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7
iptables -A LOGGING -j DROP

Wednesday, July 27, 2016

Auto logs zip script for Linux

Auto logs zip script for Linux 


vim  /root/scripts/zip_alllogs.sh

#!/bin/sh

find /mnt/logs/apilogs -type f -name "*.txt" -mtime +2 > /tmp/apilogs.txt

for i in `cat /tmp/apilogs.txt`;

do bzip2 $i;

done

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

#!/bin/sh

find /mnt/logs/httplogs -type f -name "*.txt" -mtime +2 > /tmp/httplogs.txt

for i in `cat /tmp/httplogs.txt`;

do bzip2 $i;


done

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

add to cron job

00 01 * * * /bin/bash /root/scripts/zip_alllogs.sh

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




Delete multiple files through awk command in linux

Delete multiple files through awk command in linux

ls -lrth|egrep -v "Jul 27"|awk {'print $9'}|xargs rm -rfv

ls -lrth -----list file

egrep ---for exclude 

awk {'print $9'} ---print value

xargs rm -rfv --- remove file 

Monday, July 25, 2016

Virtual hosting - Web server Apache

Virtual hosting

1. make directory /home/site1/www
[root@base ~]# mkdir -p /home/site1/www

2. create the web page:-
[root@base ~]# cd /home/site1/www/
[root@base www]# vim index.html
this is site1
wq! Save and exit

3. Navigate to conf.d or httpd.conf file
[root@base ~]# cd /etc/httpd/conf.d/
[root@base ~]# vim site1.conf
<VirtualHost 192.168.4.106:80>
ServerAdmin root@site1.example.com
DocumentRoot /home/site1/www
DirectoryIndex index.html
Options Indexes FollowSymLinks
ServerName site1.example.com
ErrorLog logs/site1.example.com-error_log
CustomLog logs/site1.example.com-access_log common
</VirtualHost>

4. check /etc/hosts
[root@base ~]# vim /etc/hosts
192.168.4.106 base
192.168.4.106 site1.example.com

5. Restart the apache server
[root@base ~]# /etc/init.d/httpd restart;chkconfig httpd on

6. Now test your site by hitting
http://site1.example.com




Apache content filtring

Apache content filtring


Apache content filtering


Content Restrictions

Features: -

1. Restricts access to content based on:

1. <Directory>

2. <Location> - URL - Web Space

3. <Files>

4. <Auth> - Authentication - related directives

2. Default Config Restricts access to: '.htaccess', '.ht*' - 'httpd.conf'

3. These are largely IP-based blocks of access to content


4. By Default, Apache restricts, by honouring File System semantics, access to hidden files


5. Facilitates the ability to publish some content externally and others internally


1. directory baised access(content filtering)

1. <Directory> # IP-based restriction

<Directory /var/www/html/pub1>

Order allow,deny

Allow from 127.0.0.1 192.168.4.106

</Directory>

2. Effectively take content offline from web space to facilitate File-System based updates

<Directory /var/www/html/pub1>

Order deny,allow

Deny from all

</Directory>



3. Use '<Location>' to restrict access to content :-


'<LocationMatch ^/priv>' - traps variants including, but not limited to: '/priv', '/private', '/privacy', 'privelege'


<LocationMatch ^/priv>

Order deny,allow

Deny from all

</LocationMatch>


change to


<Location ~ ^/priv>

Order deny,allow

Deny from all

</Location>


4. Use '<Files>' to restrict access to content(access to directory but restricting some file)

note put it into the Directive in which you want to apply this otherwise this will block all the directives file cause it has recursive nature.


'<Files ~ "\.(xls|doc|pdf|mdb)">

Order deny,allow

deny from all

</Files>


5. Block access to hidden files

<FilesMatch "\.">

Order deny,allow

deny from all

</FilesMatch>

Securing Apache with SSL certificate

Securing Apache with SSL certificate



1. install mod_ssl or openssl
[root@tct ~]# yum install mod_ssl openssl

 2. Generate a self-signed certificate
Using OpenSSL we will generate a self-signed certificate. If you are using this on a production server you are probably likely to want a key from Trusted Certificate Authority, but if you are just using this on a personal site or for testing purposes a self-signed certificate is fine. To create the key you will need to be root so you can either su to root or use sudo in front of the commands

1. Generate private key
[root@tct ~]#  openssl genrsa -out cert.key 1024 
2. Generate CSR(certificate request)
[root@tct ~]# openssl req -new -key cert.key -out ca.csr

3.  Generate Self Signed Key
[root@tct ~]# openssl x509 -req -days 365 -in cert.csr -signkey cert.key -out cert.crt

3. Copy the files to the correct locations
[root@tct ~]# cp cert.crt /etc/pki/tls/certs[root@tct ~]# cp cert.key /etc/pki/tls/private[root@tct ~]# cp cert.csr /etc/pki/tls/private 
4. Import key to apache
[root@tct ~]# vim /etc/httpd/conf.d/ssl.conf
   SSLCertificateFile /etc/pki/tls/certs/cert.crt
  SSLCertificateKeyFile /etc/pki/tls/private/cert.key
wq: save n exit
 
5. Now restart apache
[root@tct ~]# /etc/init.d/httpd restart;chkconfig httpd on
6. now open url to check if ssl is working using  https://url 

 

Setting up ssl for the virtual hosts

 NameVirtualHost *:443
 
<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/cert.crt
    SSLCertificateKeyFile /etc/pki/tls/private/cert.key
    ServerAdmin root@.example.com
    DocumentRoot /var/www/html
    ServerName root.example.com
    DirectoryIndex test.html
    ErrorLog logs/test/error_log
    CustomLog logs/test/access_log common