IBM شرکت RedHat را خرید!

 

 IBM شرکت RedHat را خرید!
احتمالا هنوز هم بسیاری از ما از شنیدن آن در شوک هستیم، چند روز پیش اعلام شد که IBM شرکت RedHat را به مبلغ ۳۴ بیلیون دلار خریده است .

توزیع های لينوکس چيست؟ Distribution چیست؟

 

مهمترین برتری گنو/لینوکس، نسبت به سیستم‌عامل‌های انحصاری آن است که این سیستم نرم‌افزار آزاد است. هیچ شرکت، دولت یا گروهی صاحب گنو/لینوکس نیست. شرکت‌ها و گروه‌های بسیاری اقدام به تولید مجموعه نرم‌افزارهای خود، که "پخش" یا "توزیع" نام دارد کرده‌اند. تعداد دقیق پخش‌های گنو/لینوکس مشخص نیست، اما آنچه که مسلم است آن است که بیش از ۲۰۰ پخش ثبت شده‌ی گنو/لینوکس وجود دارد. هر شخصی، با کمی دانش فنی و کمی وقت می‌تواند سیستم عامل گنو/لینوکس خودش را درست کند.

سهمیه بندی دیسک در لینوکس-Linux Journaled quota

 
 
                                
 

 سهمیه بندی دیسک سخت در لینوکس-Linux Journaled quota

هنگامی که  با سرویس دهنده ftp, fileserver و یا موارد دیگری که کاربران زیادی بر روی لینوکس شما کار می کنند. همواره نگرانی از پر شدن دیسک سخت و از کار افتادن لینوکس وجود دارد یکی از راههای کنترل میزان فضای مصرف دیسک کاربران استفاده از سرویس Quotas می باشد.همچنین به هر دلیلی یک برنامه می تواند از کنترل خارج شود و شروع به اشغال بیهوده فضای ذخیره سازی نماید بنابراین به کمک سرویس سهمیه بندی دیسک سخت در لینوکس می توانید از اتمام فضای دیسک جلوگیری نمایید و آن برنامه مخرب را متوقف نمایید. به وسیله این سرویس شما می توانید:

۱- محدودیت میزان فضای مصرفی برای کابران لینوکس ایجاد نمایید.
۲- محدودیت میزان فضای مصرفی برای گروه های لینوکس ایجاد نمایید.
۳- محدودیت  بر روی تعداد فایل های  یک کاربر لینوکس  ایجاد نمایید.
۴- محدودیت  بر روی تعداد فایل های  یک گروه لینوکس  ایجاد نمایید.
 
 در این آموزش تصویری کاربرد  سهمیه بندی دیسک سخت در لینوکس-Journaled quota در وب هاستینگ را ارایه می دهیم.
 #Enabling journaling for disk quota change fstab in this example /home
/dev/sda1 /home ext4 defaults,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv1 1 1
 ##Tips:
###vfsv1 Supporting quotas more than 4TB.You need at least kernel 2.6.33
###vfsv0 If your kernel is older.
 
Check Partitions and Disable quota
mount |grep -E 'home|Backup' |awk '{print $3,$6}' "
quotaoff -guvp -a
quotaoff -a

Create aquota.user, aquota.group on each partitions
 for i in `mount |grep -E 'home|Backup' |awk '{print $3}'`;
 do
    touch $i/{aquota.user,aquota.group};  
 done

Remount Partitions with quota options

for i in `mount |grep -E 'home|Backup' |awk '{print $3}'`;
 do
    mount -o remount,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv1  $i;
 done

Create the quota index
quotacheck -cguvamf -F vfsv1
 
Enable quotas
quotaon -a

Use this command to check for quotas
repquota -a

104.4 Manage disk quotas

Weight: 1

Description: Candidates should be able to manage disk quotas for users.

Key Knowledge Areas:

  • Set up a disk quota for a filesystem
  • Edit, check and generate user quota reports

Terms and Utilities:

  • quota
  • edquota
  • repquota
  • quotaon
 هرگونه نشر و کپی برداری بدون ذکر منبع و نام نویسنده دارای اشکال اخلاقی می باشد.
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

01-Linux Hardening - اقدامات اولیه در سخت سازی لینوکس

 

1.1 Linux Recommended Partitioning Scheme and Security

1.1.1 Partitioning Scheme

دلایل زیادی برای پارتیشن بندی وجود دارد در لینوکس برای دستیابی به دو قابلیت امنیت و کارایی از پارتیشن های متعدد با فایل سیستم های مناسب و سطوح دسترسی مورد نیاز استفاده میکنیم. تمامی موارد به صورت پیشنهاد می باشد.

ابتدا دیسک خود را به چهار قسمت تقسیم می کنیم و از استاندارد پارتیشن بندی MSDOS استفاده میکنیم. کل این مبحث به صورت کامل در دوره آموزش تصویری مدیریت لینوکس LPIC1 آموزش داده شده است.

Number  Start   End     Size    Type     File system        Used for
 1      1049kB  400MB   398MB   primary  ext4 boot
 2      400MB   10.0GB  9601MB  primary  linux-swap(v1) swap
 3      10.0GB  40.0GB  30.0GB  primary LVM (vgos)
 4      40.0GB  215GB   175GB   primary LVM (vgdata)

 پارتیشن اول برای بوت

پارتیشن دوم برای swap

پارتیشن سوم برای سیستم عامل که در قالب LVM استفاده می شود و خودش به بخش های زیر تقسیم می شود.

/, /var, /tmp, /var/tmp

پارتیشن چهارم که برای نگهداری دیتا می باشد و کل آن به صورت رمزنگاری و روی آن از قالب LVM استفاده می شود.

/home

ساختار درختی آن به صورت زیر می باشد.

NAME                   MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda                      8:0    0   200G  0 disk  
├─sda1                   8:1    0   380M  0 part  /boot
├─sda2                   8:2    0     9G  0 part  [SWAP]
├─sda3                   8:3    0    28G  0 part  
│ ├─mysrvvgos-root      254:0    0    10G  0 lvm   /
│ ├─mysrvvgos-var       254:1    0   5.1G  0 lvm   /var
│ ├─mysrvvgos-tmp       254:2    0     3G  0 lvm   /tmp
│ └─mysrvvgos-vartmp    254:3    0     2G  0 lvm   /var/tmp
└─sda4                   8:4    0 162.8G  0 part  
  └─mydata             254:4    0 162.8G  0 crypt
    ├─mydata-home      254:5    0    50G  0 lvm   /home

 بر روی سیستم عامل لینوکس شما می توانید انواع مختلفی از فایل سیستم ها را استفاده نمایید با توجه به نیاز خود بررسی و فایل سیستم مناسب را انتخاب نمایید فایل سیستم ext4 یکی از پایدارترین فایل سیستم های لینوکس می باشد که به خاطر این ويژگی استفاده از آن را به شما توصیه میکنم.

1.1.2 Linux FileSystem Scheme
Filesystem                  Type      Size  Used Avail Use% Mounted on
/dev/mapper/mysrvvgos-root   ext4       11G  3.0G  7.0G  30% /
/dev/mapper/mysrvvgos-var    ext4      5.4G  2.6G  2.6G  50% /var
/dev/mapper/mysrvvgos-tmp    ext4      3.2G  4.9M  3.0G   1% /tmp
/dev/mapper/mysrvvgos-vartmp ext4      2.1G  3.3M  2.0G   1% /var/tmp
/dev/sda1                   ext4      378M   83M  271M  24% /boot
/dev/mapper/mydata-home   ext4       53G   24G   27G  47% /home
1.1.3 Edit /etc/fstab
root@deb:~# cat /etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/mysrvvgos-root /  ext4    errors=remount-ro 0       1
/dev/sda1 /boot         ext4    defaults        0       2
/dev/mapper/mysrvvgos-tmp /tmp          ext4    defaults,nodev,nosuid,noexec        0       2
/dev/mapper/mysrvvgos-var /var          ext4    defaults         0       2
/dev/mapper/mysrvvgos-vartmp /var/tmp     ext4    defaults,nodev,nosuid,noexec        0       2
/dev/sda2 none          swap    sw              0       0
tmpfs                   /dev/shm      tmpfs   defaults,nodev,nosuid,noexec 0 0
/dev/sr0        /media/cdrom0 udf,iso9660 user,noauto      0       0
/dev/mydata/home /home/     ext4    data=ordered,relatime,rw,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv1  0    2

1.2 Minimal Installation and Document the host information

توصیه های دیگر قبل از نصب سیستم عامل به شرح زیر می باشد. نصب سیستم عامل به صورت minimal و مستند سازی های مورد نیاز:

Install Minimal OS
Machine name
IP address
Mac address
Name of the person who is doing the hardening (most likely you)
Date
Asset Number

1.3 Linux Disable Unneeded Modules

root@deb:~# cat << EOF >/etc/modprobe.d/itstorage.conf
#Disable Mounting of cramfs Filesystems
install cramfs /bin/true
#Disable Mounting of freevxfs Filesystems
install freevxfs /bin/true
#Disable Mounting of jffs2 Filesystems
install jffs2 /bin/true
#Disable Mounting of hfs Filesystems
install hfs /bin/true
#Disable Mounting of hfsplus Filesystems
install hfsplus /bin/true
#Disable Mounting of squashfs Filesystems
install squashfs /bin/true
#Disable Mounting of udf Filesystems
install udf /bin/true
install dccp /bin/true
install sctp /bin/true
install rds /bin/true
install tipc /bin/true
EOF

1.4 Linux Check cron and at

1.4.1 Set User/Group Owner and Permission on /etc/crontab
root@deb:~#chown root:root /etc/crontab
root@deb:~#chmod og-rwx /etc/crontab
1.4.2 Set User/Group Owner and Permission on /etc/cron.hourly
root@deb:~#chown root:root /etc/cron.hourly
root@deb:~#chmod og-rwx /etc/cron.hourly
1.4.3 Set User/Group Owner and Permission on /etc/cron.daily
root@deb:~#chown root:root /etc/cron.daily
root@deb:~# chmod og-rwx /etc/cron.daily
1.4.4 Set User/Group Owner and Permission on /etc/cron.weekly
root@deb:~#chown root:root /etc/cron.weekly
root@deb:~#chmod og-rwx /etc/cron.weekly
1.4.5 Set User/Group Owner and Permission on /etc/cron.monthly
root@deb:~#chown root:root /etc/cron.monthly
root@deb:~#chmod og-rwx /etc/cron.monthly
1.4.6 Set User/Group Owner and Permission on /etc/cron.d
root@deb:~#chown root:root /etc/cron.d
root@deb:~#chmod og-rwx /etc/cron.d
1.4.7 Restrict at Daemon
root@deb:~#rm /etc/at.deny
root@deb:~#touch /etc/at.allow
root@deb:~#
chown root:root /etc/at.allow
root@deb:~#chmod og-rwx /etc/at.allow
1.4.8 Restrict at/cron to Authorized Users
root@deb:~#/bin/rm /etc/cron.deny
root@deb:~#/bin/rm /etc/at.deny
root@deb:~#touch /etc/cron.allow
root@deb:~#chmod og-rwx /etc/cron.allow
root@deb:~#chmod og-rwx /etc/at.allow
root@deb:~#chown root:root /etc/cron.allow
root@deb:~#chown root:root /etc/at.allow

1.5 Linux Permissions and verifications

1.5.1 Verify Permissions on /etc/passwd && /etc/shadow && /etc/gshadow
root@deb:~#/bin/chmod 644 /etc/passwd
root@deb:~#/bin/chmod 000 /etc/shadow
root@deb:~#/bin/chmod 000 /etc/gshadow
1.5.2 Verify Permissions on /etc/group
root@deb:~#/bin/chmod 644 /etc/group
1.5.3 Verify User/Group Ownership on /etc/passwd && /etc/shadow && /etc/gshadow
root@deb:~#/bin/chown root:root /etc/passwd
root@deb:~#/bin/chown root:root /etc/shadow
root@deb:~#/bin/chown root:root /etc/gshadow

1.6 Display Date And Time For Each Command

برای خوانا تر شدن لاگ های history تاریخ و زمان اجرا را به آنها اضافه میکنیم. طبق روال زیر عمل نمایید.

root@deb:~#echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc
root@deb:~#echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile

 که در آن

%d - Day
%m - Month
%y - Year
%T - Time

1.7 How do I log all input and output in a terminal session?

root@deb:~#sudo cat <<EOF>bash.conf
local6.*    /var/log/commands.log
EOF
root@deb:~#sudo mv bash.conf /etc/rsyslog.d/
root@deb:~#grep who /etc/bash.bashrc
#Insert this at the end of /etc/bash.bashrc
whoami="$(whoami)@$(echo $SSH_CONNECTION | awk '{print $1}')"export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$whoami [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'
RHEL
root@deb:~#source /etc/bashrc
Debian
root@deb:~#source /etc/bash.bashrc
Here is a log sample:
root@deb:~#sudo tailf /var/log/commands.log
May  9 10:48:12 mbctux bahmani: bahmani@export [27210]: sudo /etc/init.d/rsyslog restart [0]
May  9 10:49:11 mbctux bahmani: bahmani@export [27210]: tailf /var/log/commands.log [130]
May  9 10:50:41 mbctux bahmani: bahmani@export [27210]: vi .bashrc  [0]
May  9 10:50:49 mbctux bahmani: bahmani@export [30083]: screen -x [0]
May  9 10:50:49 mbctux bahmani: bahmani@export [30083]: cd /home/bahmani [0]
May  9 10:50:57 mbctux bahmani: bahmani@export [27210]: vi .bashrc  [130]

May  9 10:51:43 mbctux bahmani: root@export [30123]: ls [0]
May  9 10:52:16 mbctux bahmani: root@export [30123]: vi .bashrc  [0]
May  9 10:52:18 mbctux bahmani: root@export [30123]: ls [0]

1.8 Change Home Permission

root@deb:~#chmod 700 /home/bahmani
root@deb:~#chmod 711 /home/mbctux

1.9 Set Sticky Bit on All World-Writable Directories

اگر روی سیستم شما دایرکتوری، باشد که همه به ان دسترسی دارند می بایست جهت جلوگیری از پاک شدن آن به غیر از مالک روی آن Sticky Bit را تنظیم نمایید. برای پیدا کردن و ست کردن Sticky Bit به روش زیر عمل نمایید.

root@deb:~#find / \( -fstype nfs -o -fstype cachefs -o -fstype autofs \
-o -fstype ctfs -o -fstype mntfs -o -fstype objfs \
-o -fstype proc \) -prune -o -type d \( -perm -0002 \
-a ! -perm -1000 \) -exec chmod +t {} \;

1.10 Find World Writable Files

فایلهایی که permission 777 را دارند شناسایی نمایید و در صورت نیاز دسترسی آنها را تغییر دهید.

root@deb:~#df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' |xargs -I '{}' find '{}' -xdev -type f -perm -0002

1.11 Find Un-owned Files and Directories

فایلهایی که مالکی ندارند را شناسایی نمایید و مالک آنها را مشخص نمایید.

root@deb:~#df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -nouser -ls

1.12 Find Un-grouped Files and Directories

فایلهایی که گروهی ندارند را شناسایی نمایید و گروه آنها را مشخص نمایید.

root@deb:~#df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -nogroup -ls

 

1.13 Find SUID System Executables

فایلهایی که permission SUID را دارند شناسایی نمایید بر روی یک سیستم نرمال فایلها به شرح زیر هستند اگر فایلی خارج از این لیست بود انرا بررسی نمایید.

root@deb:~#df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -type f -perm -4000 -print

/usr/bin/cryptmount
/usr/bin/pkexec
/usr/bin/Xvnc
/usr/bin/gpasswd
/usr/bin/vncserver-x11
/usr/bin/nvidia-modprobe
/usr/bin/sudo
/usr/bin/newgrp
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/chfn
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/openssh/ssh-keysign
/usr/lib/x86_64-linux-gnu/opera/opera_sandbox
/usr/lib/xorg/Xorg.wrap
/usr/lib/vmware/bin/vmware-vmx
/usr/lib/vmware/bin/vmware-vmx-debug
/usr/lib/vmware/bin/vmware-vmx-stats
/usr/lib/eject/dmcrypt-get-device
/usr/sbin/exim4
/usr/sbin/vmware-authd
/usr/sbin/pppd
/opt/google/chrome/chrome-sandbox
/bin/fusermount
/bin/ping
/bin/ntfs-3g
/bin/mount
/bin/ping6
/bin/umount
/bin/su
root@deb:~#for i in `df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -type f -perm -4000 -print`; do ls -la $i; done

-rwsr-xr-x 1 root root 94528 Oct  2  2016 /usr/bin/cryptmount
-rwsr-xr-x 1 root root 23352 May 24  2017 /usr/bin/pkexec
-rwsr-xr-x 1 root root 1450984 Oct 31  2016 /usr/bin/Xvnc
-rwsr-xr-x 1 root root 75792 May 17  2017 /usr/bin/gpasswd
-rwsr-xr-x 1 root root 1450984 Oct 31  2016 /usr/bin/vncserver-x11
-rwsr-xr-x 1 root root 34904 Feb 28 16:10 /usr/bin/nvidia-modprobe
-rwsr-xr-x 1 root root 140944 Jun  5  2017 /usr/bin/sudo
-rwsr-xr-x 1 root root 40312 May 17  2017 /usr/bin/newgrp
-rwsr-xr-x 1 root root 59680 May 17  2017 /usr/bin/passwd
-rwsr-xr-x 1 root root 40504 May 17  2017 /usr/bin/chsh
-rwsr-xr-x 1 root root 50040 May 17  2017 /usr/bin/chfn
-rwsr-xr-- 1 root messagebus 42992 Mar  2 12:29 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
-rwsr-xr-x 1 root root 14856 May 24  2017 /usr/lib/policykit-1/polkit-agent-helper-1
-rwsr-xr-x 1 root root 440728 Mar  1 18:47 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root root 14544 Aug 17  2015 /usr/lib/x86_64-linux-gnu/opera/opera_sandbox
-rwsr-sr-x 1 root root 10576 Oct 14 15:06 /usr/lib/xorg/Xorg.wrap
-rwsr-xr-x 1 root root 23140200 Apr  5 09:10 /usr/lib/vmware/bin/vmware-vmx
-rwsr-xr-x 1 root root 29047808 Apr  5 09:10 /usr/lib/vmware/bin/vmware-vmx-debug
-rwsr-xr-x 1 root root 26055528 Apr  5 09:10 /usr/lib/vmware/bin/vmware-vmx-stats
-rwsr-xr-x 1 root root 10232 Mar 28  2017 /usr/lib/eject/dmcrypt-get-device
-rwsr-xr-x 1 root root 1019656 Feb 10 11:56 /usr/sbin/exim4
-rwsr-xr-x 1 root root 1073896 Apr  5 09:10 /usr/sbin/vmware-authd
-rwsr-xr-- 1 root dip 365960 Nov 11  2016 /usr/sbin/pppd
-rwsr-xr-x 1 root root 19504 Mar 20 08:31 /opt/google/chrome/chrome-sandbox
-rwsr-xr-x 1 root root 30800 Jun 23  2016 /bin/fusermount
-rwsr-xr-x 1 root root 74072 Jun  5  2016 /bin/ping
-rwsr-xr-x 1 root root 146128 Feb 26  2017 /bin/ntfs-3g
-rwsr-xr-x 1 root root 44304 Mar  7 21:59 /bin/mount
-rwsr-xr-x 1 root root 64888 Jun  5  2016 /bin/ping6
-rwsr-xr-x 1 root root 31720 Mar  7 21:59 /bin/umount
-rwsr-xr-x 1 root root 40536 May 17  2017 /bin/su

1.14 Find SGID System Executables

فایلهایی که permission SGID را دارند شناسایی نمایید بر روی یک سیستم نرمال فایلها به شرح زیر هستند اگر فایلی خارج از این لیست بود انرا بررسی نمایید.

root@deb:~#df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -type f -perm -2000 -print 

/usr/bin/screen
/usr/bin/dotlock.mailutils
/usr/bin/dotlockfile
/usr/bin/crontab
/usr/bin/wall
/usr/bin/chage
/usr/bin/expiry
/usr/bin/ssh-agent
/usr/bin/xiterm+thai
/usr/bin/bsd-write
/usr/lib/libvte9/gnome-pty-helper
/usr/lib/x86_64-linux-gnu/utempter/utempter
/usr/lib/xorg/Xorg.wrap
/sbin/unix_chkpwd
root@deb:~#for i in `df --local -P | awk {'if (NR!=1) print $6'} | grep -E -v '/dev|/run|/sys' | xargs -I '{}' find '{}' -xdev -type f -perm -2000 -print`; do ls -la $i; done

-rwxr-sr-x 1 root utmp 457608 May 23  2017 /usr/bin/screen
-rwxr-sr-x 1 root mail 10952 Dec 25  2016 /usr/bin/dotlock.mailutils
-rwxr-sr-x 1 root mail 19008 Jan 17  2017 /usr/bin/dotlockfile
-rwxr-sr-x 1 root crontab 40264 Oct  7 17:08 /usr/bin/crontab
-rwxr-sr-x 1 root tty 27448 Mar  7 21:59 /usr/bin/wall
-rwxr-sr-x 1 root shadow 71856 May 17  2017 /usr/bin/chage
-rwxr-sr-x 1 root shadow 22808 May 17  2017 /usr/bin/expiry
-rwxr-sr-x 1 root ssh 358624 Mar  1 18:47 /usr/bin/ssh-agent
-rwxr-sr-x 1 root utmp 100976 Jan 11  2012 /usr/bin/xiterm+thai
-rwxr-sr-x 1 root tty 14768 Apr 12  2017 /usr/bin/bsd-write
-rwxr-sr-x 1 root utmp 15000 Jun 23  2012 /usr/lib/libvte9/gnome-pty-helper
-rwxr-sr-x 1 root utmp 10232 Feb 18  2016 /usr/lib/x86_64-linux-gnu/utempter/utempter
-rwsr-sr-x 1 root root 10576 Oct 14 15:06 /usr/lib/xorg/Xorg.wrap
-rwxr-sr-x 1 root shadow 35592 May 27  2017 /sbin/unix_chkpwd

1.15 Check for Duplicate UIDs

هر کابری در لینوکس دارای یک unique UID باشد و نباید دو کاربر یک UID داشته باشند. اگر روی سیستمی این وضعیت موجود باشد نشاندهنده اینست که آن سیستم حک شده است. خروجی اسکریپت زیر نباید چیزی برگرداند. اگر خروجی داشت سیستم مشکل دارد.

root@deb:~#echo "The Output for the Audit of Control 9.2.15 - Check for Duplicate UIDs is"
/bin/cat /etc/passwd | cut -f3 -d":" | sort -n | /usr/bin/uniq -c |\
while read x ; do
[ -z "${x}" ] && break
set - $x
if [ $1 -gt 1 ]; then
users=`/bin/gawk -F: '($3 == n) { print $1 }' n=$2 \
/etc/passwd | /usr/bin/xargs`
echo "Duplicate UID ($2): ${users}"
fi
done

1.16 Check for Duplicate GIDs

هر گروهی در لینوکس دارای یک unique GID باشد و نباید دو گروه یک GID داشته باشند. اگر روی سیستمی این وضعیت موجود باشد نشاندهنده اینست که آن سیستم حک شده است. خروجی اسکریپت زیر نباید چیزی برگرداند. اگر خروجی داشت سیستم مشکل دارد.

root@deb:~#echo "The Output for the Audit of Control 9.2.16 - Check for Duplicate GIDs is"
/bin/cat /etc/group | cut -f3 -d":" | sort -n | /usr/bin/uniq -c |\
while read x ; do
[ -z "${x}" ] && break
set - $x
if [ $1 -gt 1 ]; then
grps=`/bin/gawk -F: '($3 == n) { print $1 }' n=$2 \
/etc/group | xargs`
echo "Duplicate GID ($2): ${grps}"
fi
done

1.17 Check for Duplicate User Names

روی سیستم نباید دو نام کاربری یکسان وجود داشته باشد. خروجی اسکریپت زیر نباید چیزی برگرداند. اگر خروجی داشت سیستم مشکل دارد.

root@deb:~#echo "The Output for the Audit of Control 9.2.18 - Check for Duplicate User Names is"
cat /etc/passwd | cut -f1 -d":" | sort -n | /usr/bin/uniq -c |\
while read x ; do
[ -z "${x}" ] && break
set - $x
if [ $1 -gt 1 ]; then
uids=`/bin/gawk -F: '($1 == n) { print $3 }' n=$2 \
/etc/passwd | xargs`
echo "Duplicate User Name ($2): ${uids}"
fi
done

1.18 Check for Duplicate Group Names

روی سیستم نباید دو گروه یکسان وجود داشته باشد. خروجی اسکریپت زیر نباید چیزی برگرداند. اگر خروجی داشت سیستم مشکل دارد.

root@deb:~#echo "The Output for the Audit of Control 9.2.19 - Check for Duplicate Group Names is"
cat /etc/group | cut -f1 -d":" | sort -n | /usr/bin/uniq -c |\
while read x ; do
[ -z "${x}" ] && break
set - $x
if [ $1 -gt 1 ]; then
gids=`/bin/gawk -F: '($1 == n) { print $3 }' n=$2 \
/etc/group | xargs`
echo "Duplicate Group Name ($2): ${gids}"
fi
done

1.19 Banners and identification

root@deb:~#cat /etc/motd /etc/issue /etc/issue.net

===========================================================================

PROPRIETARY INFORMATION

All content of this system and its associated sub-systems are PROPRIETARY
INFORMATION and remain the sole and exclusive property of this company.
This system may be accessed and used by authorized personnel only.
Authorized users may only perform authorized activities and may not exceed
the limits of such authorization. Disclosure of information found in this
system for any unauthorized use is *STRICTLY PROHIBITED*. All activities on
this system are subject to monitoring. Intentional misuse of this system
can result in disciplinary action or criminal prosecution.

===========================================================================
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

02-Linux Hardening - سخت سازی سرور - OpenSSH security and hardening

 

2. Securing the OpenSSH service

امروزه روش معمول ارتباط بین سرورها و تجهیزات شبکه از طریق پروتکل ارتباطی SSH (Secure SHell) می باشد. و بنابراین سخت سازی تنطیمات آن از اهمیت بالایی برخوردار است

2.1 OpenSSH server hardening

MaxSessions
MaxAuthTries
Change LogLevel
Change Default Port
Set SSH protocol
Disable root login
Empty passwords
Use HashKnownHosts
DNS hostname checking
Public key authentication
Restrict allowable commands
Maximum authentication attempts
Usage of AllowUsers and DenyUsers
Disable rhosts
Disable Compression
Disable TCPKeepAlive
Disable X11Forwarding
Disable AllowTcpForwarding
Change ClientAliveInterval
Change ClientAliveCountMax
Disable AllowAgentForwarding

 برای پیکربندی SSH Server می بایست فایل پیکربندی سرویس آن /etc/ssh/sshd_config ویرایش شود و مطابق زیر پارمترهای آن ویرایش گردند. جهت سهولت می توانید نرم افزار augtool را نصب کنید و به صورت یکجا همه پارمترهای سرویس را ویرایش کنید. و یا به صورت دستی اینکار را انجام دهید من از نرم افزار augtool استفاده میکنم.

2.2 Augeas installation on RHEL\CentOS 7x and Debian 9x
[root@centos7 ~]# yum -y install augeas
root@deb:~# apt-get install augeas-tools

ابتدا از فایل پیکربندی یک نسخه بک آپ میگیریم.

2.2 Configure SSH Server on RHEL\ CentOS 7x and Debian 9x
root@deb:~#cp /etc/ssh/sshd_config /etc/ssh/sshd_config-orig
 حال با استفاده از نر افزار augtool پیکربندی مورد نظر را اعمال میکنیم. با استفاده از این نر افزار می توانید هر فایل پیکربندی لینوکس خود را ویرایش نمایید.
root@deb:~#augtool << EOF
set /files/etc/ssh/sshd_config/ListenAddress 0.0.0.0
set /files/etc/ssh/sshd_config/PermitRootLogin no
set /files/etc/ssh/sshd_config/ChallengeResponseAuthentication no
set /files/etc/ssh/sshd_config/PasswordAuthentication yes
set /files/etc/ssh/sshd_config/UsePAM yes
set /files/etc/ssh/sshd_config/UseDNS no
set /files/etc/ssh/sshd_config/Port 2212
set /files/etc/ssh/sshd_config/Protocol 2
set /files/etc/ssh/sshd_config/LogLevel VERBOSE
set /files/etc/ssh/sshd_config/MaxAuthTries 3
set /files/etc/ssh/sshd_config/MaxSessions 2
set /files/etc/ssh/sshd_config/AllowAgentForwarding no
set /files/etc/ssh/sshd_config/AllowTcpForwarding no
set /files/etc/ssh/sshd_config/X11Forwarding no
set /files/etc/ssh/sshd_config/TCPKeepAlive no
set /files/etc/ssh/sshd_config/Compression no
set /files/etc/ssh/sshd_config/ClientAliveInterval 300
set /files/etc/ssh/sshd_config/ClientAliveCountMax 0
set /files/etc/ssh/sshd_config/IgnoreRhosts yes
set /files/etc/ssh/sshd_config/PubkeyAuthentication yes
set /files/etc/ssh/sshd_config/Protocol 2
set /files/etc/ssh/sshd_config/AllowTcpForwarding no
save
EOF
Saved 1 file(s)
root@deb:~#
2.3 Configure Debian 9x
 تنظیم یکی از دو پارامتر
AllowGroups adm
AllowUsers bahmani
را که مشخص میکند چه کاربر و یا گروهی بتواند ssh کند را مشخص میکنیم دقت کنید با هم این دو پارمتر را استفاده نکنید. زیرا ترکیب هر دو یا And می شود.
 
root@deb:~#sudo cat /etc/ssh/sshd_config
....
AllowGroups adm bahmani
2.4 Configure RHEL\ CentOS 7x
 دو پارامتر
AllowGroups adm
AllowUsers bahmani
را که مشخص میکند چه کاربر و گروهی بتواند ssh کند را مشخص میکنیم یا به صورت دستی یا با استفاده از دو دستور awk در روش زیر
 
[root@centos7 ~]#sudo cat /etc/ssh/sshd_config
....
AllowGroups wheel bahmani
 بررسی تنظیمات اعمال شده
root@deb:~#grep -E 'AllowTcpForwarding|ListenAddress|PubkeyAuthentication|AllowTcpForwarding|Protocol|IgnoreRhosts|PasswordAuthentication|ChallengeResponseAuthentication|Compression|LogLevel|MaxAuthTries|MaxSessions|TCPKeepAlive|X11Forwarding|AllowAgentForwarding|Port|Permit|AllowUsers|ClientAliveInterval|ClientAliveCountMax|AllowGroup' /etc/ssh/sshd_config |grep -v ^#

Port 2212
ListenAddress 0.0.0.0
LogLevel VERBOSE
PermitRootLogin no
MaxAuthTries 1
MaxSessions 2
ChallengeResponseAuthentication no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
TCPKeepAlive no
Compression no
ClientAliveInterval 300
ClientAliveCountMax 0
PasswordAuthentication no
IgnoreRhosts yes
PubkeyAuthentication yes
Protocol 2
AllowGroups adm bahmani

root@deb:~#

 حال سرویس را ری استارت میکنیم.

root@deb:~# systemctl restart sshd.service
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

03-Linux Hardening - سخت سازی کرنل - Kernel Hardening

 

3. Kernel Hardening

کرنل لینوکس بخش مهمی از این سیستم عامل می باشد و بنابراین توجه به پارمترهای مهم امنیتی باعث می شود تا بتوانید از بسیاری از حملات مخرب جلوگیری نمایید.

3.1 Configure sysctl.conf
[root@deb ~]#cat <<EOF>> /etc/sysctl.conf
#Anti-DDoS Kernel Settings (sysctl.conf)
kernel.printk = 4 4 1 7
kernel.panic = 10
kernel.sysrq = 0
kernel.shmmax = 4294967296
kernel.shmall = 4194304
kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
vm.swappiness = 20
vm.dirty_ratio = 80
vm.dirty_background_ratio = 5
fs.file-max = 2097152
net.core.netdev_max_backlog = 262144
net.core.rmem_default = 31457280
net.core.rmem_max = 67108864
net.core.wmem_default = 31457280
net.core.wmem_max = 67108864
net.core.somaxconn = 65535
net.core.optmem_max = 25165824
net.ipv4.neigh.default.gc_thresh1 = 4096
net.ipv4.neigh.default.gc_thresh2 = 8192
net.ipv4.neigh.default.gc_thresh3 = 16384
net.ipv4.neigh.default.gc_interval = 5
net.ipv4.neigh.default.gc_stale_time = 120
net.netfilter.nf_conntrack_max = 10000000
net.netfilter.nf_conntrack_tcp_loose = 0
net.netfilter.nf_conntrack_tcp_timeout_established = 1800
net.netfilter.nf_conntrack_tcp_timeout_close = 10
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 20
net.netfilter.nf_conntrack_tcp_timeout_last_ack = 20
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 20
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 20
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.ip_no_pmtu_disc = 1
net.ipv4.route.flush = 1
net.ipv4.route.max_size = 8048576
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_congestion_control = htcp
net.ipv4.tcp_mem = 65536 131072 262144
net.ipv4.udp_mem = 65536 131072 262144
net.ipv4.tcp_rmem = 4096 87380 33554432
net.ipv4.udp_rmem_min = 16384
net.ipv4.tcp_wmem = 4096 87380 33554432
net.ipv4.udp_wmem_min = 16384
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 400000
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rfc1337 = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
net.ipv4.tcp_ecn = 2
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 60
net.ipv4.tcp_keepalive_probes = 10
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
kernel.ctrl-alt-del = 0
kernel.kptr_restrict = 2
kernel.randomize_va_space = 2
net.ipv4.conf.all.bootp_relay = 0
net.ipv4.conf.all.forwarding = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.all.proxy_arp = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.log_martians = 1

#To avoid duplicate in sysctl.conf
#cat /etc/sysctl.conf|grep -v ^#|grep -v ^$|awk -F"=" '{print $1}'|uniq -c|awk '{print $1}'|grep -v 1

#Bahmani
#To reduce the delay timeout for UDP connections
net.netfilter.nf_conntrack_udp_timeout = 10
EOF
3.2 To avoid duplicate in sysctl.conf
[root@deb ~]#cat /etc/sysctl.conf|grep -v ^#|grep -v ^$|awk -F"=" '{print $1}'|uniq -c|awk '{print $1}'|grep -v 1
3.3 Load sysctl settings from the file /etc/sysctl.conf file
[root@deb ~]#  modprobe ip_conntrack ;sysctl -p
 
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

04-Linux Hardening - تعریف کاربر ادمین در لینوکس - Setup Linux Admin User

4.setup Admin user (Just admin user can switch to root)

4.1 Create an admin User
root@deb:~#useradd bahmani
root@deb:~#passwd bahmani
root@deb:~#exit
4.2 Make bahmani user who can switch to root as an admin user.
4.2.1 Debian
root@deb:~#usermod -aG adm bahmani
root@deb:~#usermod -aG sudo bahmani
4.2.2 RHEL
root@deb:~#usermod -aG wheel bahmani
root@deb:~#usermod -aG sudo bahmani
4.3 Edit /etc/pam.d/su
root@deb:~#grep adm  /etc/pam.d/su
4.3.1 Debian line 15: uncomment and add the follows
...
auth       required   pam_wheel.so group=adm
...
root@deb:~#reboot
4.3.2 RHEL uncomment and add the follows
...
# uncomment the following line
auth            required        pam_wheel.so use_uid
...
root@deb:~#reboot
4.4 Test: Other User except admin can not switch to root
root@deb:~#su - soroush
soroush@deb:~$ su -
Password:
su: Permission denied
soroush@deb:~$

 

مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

05-Linux Hardening - ثبت همه دستورات کاربران لینوکس توسط Process Accounting

 

تجربه نشان داده است که بر روی سیستم های لینوکسی که چندین کاربر دارند همیشه شما نیازمند مکانیزمی هستید که دستوراتی را که ادمین های سیستم وارد می کنند لاگ کنید. تا در مواقع مورد نیاز بتوانید تشخیص دهید که مشکلات ناشی از اجرای دستورات ادمین ها توسط چه شخصی بوجود آمده است.نرمافزار Process Accounting این امکان را به ما می دهد. تا همه دستورات کاربران را ثبت نماییم.و حتی هنگامی که کاربر history دستوراتش را پاک می کند به لیست دستوراتی که اجرا کرده دسترسی داشته باشیم. وهمچنین میزان استفاده از CPU و Memory هر پروسس را هم داشته باشیم.

  • The ac command displays statistics about how long users have been logged on.
  • The lastcomm command displays information about previous executed commands.
  • The accton command turns process accounting on or off.
  • The sa command summarizes information about previously executed commmands.

در ادامه روش نصب و استفاده آن را در سیستم های RHEL وDebian توضیح میدهم.

5.1 Install psacct or acct package

Use yum command if you are using    CentOS/Fedora Linux / RHEL:
rhel7x@itstorage:~ $ sudo yum install -y psacct
Use apt-get command if you are using Ubuntu / Debian Linux:
rhel7x@itstorage:~ $ sudo apt-get install acct

5.2 Start psacct/acct service

CentOS/Fedora Linux / RHEL:
rhel6x@itstorage:~ $ sudo chkconfig psacct on && sudo service psacct start
rhel7x@itstorage:~ $ sudo systemctl enable psacct && sudo systemctl enable psacct
Ubuntu / Debian Linux:
rhel7x@itstorage:~ $sudo systemctl enable acct && sudo systemctl start acct
RHEL 7x Status psacct/acct service
rhel7x@itstorage:~ $systemctl status psacct
● psacct.service - Kernel process accounting
   Loaded: loaded (/usr/lib/systemd/system/psacct.service; enabled; vendor preset: disabled)
   Active: active (exited) since Sun 2018-05-06 15:58:45 +0430; 7s ago
  Process: 2500 ExecStart=/usr/sbin/accton /var/account/pacct (code=exited, status=0/SUCCESS)
  Process: 2498 ExecStartPre=/usr/libexec/psacct/accton-create (code=exited, status=0/SUCCESS)
 Main PID: 2500 (code=exited, status=0/SUCCESS)

May 06 15:58:45 rhel7x.itstorage.co systemd[1]: Starting Kernel process accounting...
May 06 15:58:45 rhel7x.itstorage.co  accton[2500]: Turning on process accounting, file set to...'.
May 06 15:58:45 rhel7x.itstorage.co systemd[1]: Started Kernel process accounting.
Hint: Some lines were ellipsized, use -l to show in full.

5.3 Usage psacct/acct

Display last executed command by bahmani user:
linux@itstorage:~ $ sudo lastcomm bahmani
ls                         bahmani  pts/5      0.00 secs Sat Jun 25 16:24
bash              F     bahmani  pts/5      0.00 secs Sat Jun 25 16:24
ls                         bahmani  pts/5      0.00 secs Sat Jun 25 16:24
bash              F    bahmani  pts/5      0.00 secs Sat Jun 25 16:24
dircolors               bahmani  pts/5      0.00 secs Sat Jun 25 16:24
tput                      bahmani  pts/5      0.00 secs Sat Jun 25 16:24
Search the accounting logs by command name:
linux@itstorage:~ $ sudo lastcomm ls
ls bahmani pts/5 0.00 secs Sat Jun 25 16:24
ls bahmani pts/5 0.00 secs Sat Jun 25 16:24
ls root __ 0.00 secs Sat Jun 25 16:07
Search the accounting logs by terminal name pts/1
linux@itstorage:~ $ sudo lastcomm pts/1
Printing all Users activities
linux@itstorage:~ $ sa
   10797  400831.42re    2013.84cp         0avio     11630k
   6    56937.47re       808.37cp         0avio    114345k   ***other*
   4    3186.58re      487.12cp         0avio     39788k   Xorg
   2     609.88re     308.11cp         0avio    217536k   simplescreenrec
Printing all Users activities
linux@itstorage:~ $ sa -u

root     0.00     cpu     1084k     mem 0 io debian-sa1
root     0.00     cpu     1084k     mem 0 io sh
root     0.00     cpu     7884k     mem 0 io cron *
root     0.02     cpu     0k         mem 0 io kworker/dying *
Debian-e 0.00     cpu     13312k     mem 0 io exim4 *
root     0.00     cpu     13310k     mem 0 io exim4 *
root     0.00     cpu     13310k     mem 0 io exim4
root     0.08     cpu     3164k     mem 0 io sa
Display Day-Wise Logn Time of User
linux@itstorage:~ $ sudo ac -d bahmani
Jun 3 total 14.90
Jun 4 total 24.11
Jun 5 total 12.99
Jun 6 total 16.30

 

مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

06-Linux Hardening - نرم افزار inotify-tools برای بررسی همه اتفاقات روی دایرکتوریها و فایلها در لینوکس

 

 در این آموزش itstorage به معرفی و نصب نرم افزار inotify-tools برای بررسی همه اتفاقات روی دایرکتوریها و فایلها در لینوکس می پردازیم.

گاهی اوقات لازم است بر روی یک دایرکتوری نظارت دقیق انجام شود و هر گونه تغییری در فایلها و دایرکتوری های داخل آن ثبت شود و به مدیر سیستم اطلاع رسانی گردد.
یکی از ابزارهایی که می توان از ان استفاده نمود نرم افزار inotify-tools  می باشد.

 inotify

این قابلیت از کرنل نسخه 2.6.13   به کرنل اضافه شد و به همین دلیل نیازی نیست تا فایل سیسام به صورت منظم اسکن شود بلکه بررسی و کنترل در سطح کرنل انجام می گیرد.
برای اینکه بتوانید نرمافزارهای جانبی برای inotify بنویسید از زبان های متعددی می توانید استفاده کنید مانند: Perl یا Python
 
 
 

6.1  Install inotify tools

Debian

debian@itstorage$ sudo apt-get update
debian@itstorage$ sudo apt-get install inotify-tools
RHEL
rhel7x@itstorage$ sudo yum --enablerepo=epel -y install inotify-tools   # install from EPEL

6.2  work with inotify tools

می خواهیم مسیر /etc را مانیتور کنیم و ایجاد، حذف، تغییر و انتقال فایلها را لاگ کنیم روش کار به شرح زیر است.
linux@itstorage$ sudo inotifywait -e create,delete,modify,move -mrq /etc &
حال در مسیر /etc یک فایل را ایجاد، انتقال،  و حذف می کنیم در هر کدام از موارد شناسایی انجام و یک پیام بر روی صفحه نمایش داده می شود.
linux@itstorage# touch /etc/test.txt 
/etc/ CREATE test.txt# detected
linux@itstorage# mv /etc/test.txt /etc/test.conf 
/etc/ MOVED_FROM test.txt
/etc/ MOVED_TO test.conf# detected
linux@itstorage# rm -f /etc/test.conf 
/etc/ DELETE test.conf# detected

استفاده از نرم افزارinotify  در قالب Shell Script

می توان از یک Shell Script ساده برای استفاده از نرم افزار inotify استفاده نمود روش بعدی استفاده از init script می باشد که در ادامه توضیح داده می شود. ابتدا فایل اسکریبپ را به شکل زیر ایجاد میکنیم و مطابق با نیاز تنظیمات رو انجام می دهیم.

linux@itstorage#cat my_audit_files.sh
#!/bin/bash
# my_audit_files.sh
watchdir=/home/bahmani/
logfile=/home/bahmani/my_audit_files.txt
while : ; do
        inotifywait $watchdir|while read path action file; do
                ts=$(date +"%C%y%m%d%H%M%S")
                echo "$ts :: file: $file :: $action :: $path">>$logfile
        done
done
exit
کافی است که به اسکریپ فوق دسترسی اجرا بدهیم و سپس وارد دایرکتوری که در مسیر watchdir در اسکریپت ست شده است برویم و آنرا اجرا نماییم و سپس چند فایل را ایجاد و تغییر می دهیم و لاگ را مشاهده می کنیم.
linux@itstorage#chmod +x watch-test.sh
linux@itstorage# ./watch-test.sh &
linux@itstorage# touch test1.txt
linux@itstorage# touch test2.txt
linux@itstorage# cp test1.txt /home/bahmani/
linux@itstorage# mv test2.txt /home/bahmani/
linux@itstorage# echo hi mahdi >> /home/bahmani/test2.txt
linux@itstorage# cat /home/bahmani/test1.txt
hi mahdi

linux@itstorage# cat watchlog.txt
20170206161636 :: file: test1.txt :: CREATE :: /home/bahmani/
20170206161643 :: file: test2.txt :: MOVED_TO :: /home/bahmani/
20170206161655 :: file: test1.txt :: MODIFY :: /home/bahmani/
20170206161703 :: file: test1.txt :: OPEN :: /home/bahmani/

استفاده از نرم افزارinotify به عنوان سرویس در قالب init script در سیستم های ردهت بیس

ایجاد فایل پیکربندی در مسیر /etc

linux@itstorage#vi /etc/inotifywait.conf
# create config file
# specify log file

LOGFILE=/var/log/inotify.log
# specify target directory for monitoring

MONITOR=/etc
# specify target events for monitoring ( comma separated )

# refer ro "man inotifywait" for kinds of events

EVENT=create,delete,modify,move

ایجاد فایل init script در مسیر

vi /etc/rc.d/init.d/inotifywait
# create init script

#!/bin/bash

# inotifywait: Start/Stop inotifywait
#
# chkconfig: - 80 20
# description: inotifywait waits for changes to files using inotify.
#
# processname: inotifywait

. /etc/rc.d/init.d/functions
. /etc/sysconfig/network
. /etc/inotifywait.conf

LOCK=/var/lock/subsys/inotifywait

RETVAL=0
start() {
   echo -n $"Starting inotifywait: "
   /usr/bin/inotifywait \
   --format '%w%f %e %T' \
   --timefmt '%Y/%m/%d-%H:%M:%S' \
   --exclude '.*\.sw[pox].*' \
   -e $EVENT \
   -o $LOGFILE \
   -dmrq $MONITOR

   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && touch $LOCK
   return $RETVAL
}
stop() {
   echo -n $"Stopping inotifywait: "
   killproc inotifywait
   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && rm -f $LOCK
   return $RETVAL
}
case "$1" in
   start)
      start
      ;;
   stop)
      stop
      ;;
   status)
      status inotifywait
      ;;
   restart)
      stop
      start
      ;;
   *)
      echo $"Usage: $0 {start|stop|status|restart}"
      exit 1
esac
exit $?

linux@itstorage# chmod 755 /etc/rc.d/init.d/inotifywait
linux@itstorage# /etc/rc.d/init.d/inotifywait start
Starting inotifywait:
linux@itstorage# chkconfig --add inotifywait
linux@itstorage# chkconfig inotifywait on

تست و بررسی log

# try to do some actions
linux@itstorage# touch /etc/test.txt
linux@itstorage# mv /etc/test.txt /etc/test.conf
linux@itstorage# vi /etc/test.conf

# edit something
linux@itstorage# rm -f /etc/test.conf

# logs are taken like follows
linux@itstorage#cat /var/log/inotify.log
/etc/test.txt MOVED_FROM 2017/02/06-19:13:06
/etc/test.conf MOVED_TO 2017/02/06-19:13:06
/etc/4913 CREATE 2017/02/06-19:13:25
/etc/4913 DELETE 2017/02/06-19:13:25
/etc/test.conf MOVED_FROM 2017/02/06-19:13:25
/etc/test.conf~ MOVED_TO 2017/02/06-19:13:25
/etc/test.conf CREATE 2017/02/11-19:13:25
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

07-Linux Hardening - پیکربندی فایروال در لینوکس Configure Iptables

 

Introduction
Iptables is the software firewall that is included with most Linux distributions by default. This cheat sheet-style guide provides a quick reference to iptables commands that will create firewall rules are useful in common, everyday scenarios. This includes iptables examples of allowing and blocking various services by port, network interface, and source IP address.
Chains
These are 3 predefined chains in the filter table to which we can add rules for processing IP packets passing through those chains. These chains are:

INPUT
All packets destined for the host computer.

OUTPUT
All packets originating from the host computer.
FORWARD
All packets neither destined for nor originating from the host computer, but passing through (routed by) the host computer. This chain is used if you are using your computer as a router.
For the most part, we are going to be dealing with the INPUT chain to filter packets entering our machine - that is, keeping the bad guys out.
Rules are added in a list to each chain. A packet is checked against each rule in turn, starting at the top, and if it matches that rule, then an action is taken such as accepting (ACCEPT) or dropping (DROP) the packet. Once a rule has been matched and an action taken, then the packet is processed according to the outcome of that rule and isn't processed by further rules in the chain. If a packet passes down through all the rules in the chain and reaches the bottom without being matched against any rule, then the default action for that chain is taken. This is referred to as the default policy and may be set to either ACCEPT or DROP the packet.
We can set a default policy to DROP all packets and then add rules to specifically allow (ACCEPT) packets that may be from trusted IP addresses, or for certain ports on which we have services running such as bittorrent, FTP server, Web Server, Samba file server etc.
 
Install package
Debian / Ubuntu

iptables/ip6tables — administration tool for IPv4/IPv6 packet filtering and NAT

root@deb:~#apt-get install iptables iptables-persistent
root@deb:~#ls /etc/iptables
rules.v4  rules.v6
iptables help

iptables/ip6tables — administration tool for IPv4/IPv6 packet filtering and NAT

root@deb:~#man iptables
RHEL / CentOS
root@deb:~#cat <<EOF> /root/bin/fw.stop
Listing rules

Now, say that we’ve blocked a couple of IPs by appending rules. If you want to see these rules later, you can use the -L switch. Also, as we will see in the next section, it’s very helpful to see line numbers for these rules, so we’ll also use the --line-numbers switch.

root@deb:~#iptables -L --line-numbers
Chain port-scanning (0 references)
num  target     prot opt source               destination         
1    RETURN     tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,ACK/RST limit: avg 1/sec burst 2
2    DROP       all  --  anywhere             anywhere 
...
Deleting rules

Now, say you’ve blocked the IP range 221.194.47.0/24 by mistake. Removing it is easy: simply replace -A with -D, which deletes a rule:

root@deb:~#iptables -D INPUT -s 221.194.47.0/24 -j REJECT

You can also delete rules through their line numbers. If you want to delete the second rule from the INPUT chain, the command would be:

Tips:When you delete a rule that isn’t the last rule, the line numbers change

root@deb:~#iptables -D INPUT 2
Inserting and replacing rules

So far, we have seen examples of appending and deleting rules.

Insert rule
root@deb:~#iptables -L --line-numbers
root@deb:~#iptables -I INPUT 3 -s 59.45.175.10 -j ACCEPT
Replace rule
root@deb:~#iptables -R INPUT 1 -s 59.45.175.10 -j ACCEPT
Flushing All iptables's rules
root@deb:~#cat <<EOF> /root/bin/fw.stop
#!/bin/bash
### 00: Clear and Flush iptables rules.
echo "Stopping firewall and allowing everyone..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
EOF
root@deb:~#chmod u+x /root/bin/fw.*
root@deb:~#sh /root/bin/fw.stop
Writing a Perfect Rule Set of iptables
root@deb:~#cat <<EOF> /root/bin/fw.start 
#!/bin/bash
echo "Starting firewall..."
#
# Creating default policies for INPUT, FORWARD and OUTPUT chains
#
iptables -P INPUT DROP
iptables -P FORWARD DROP #If we're not a router
iptables -P OUTPUT ACCEPT

### 01: SSH brute-force protection ###
# Allow SSH connections on tcp port 2212
iptables -A INPUT -p tcp --dport 2212 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 2212 -m state --state NEW -j ACCEPT
#Change Default Port to 2212
#Prevent brute-force attacks by logging and blocking repeated attempts to login from the same IP address
/sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate \
NEW -m recent --set

/sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate \
NEW -m recent --update --seconds 60 --hitcount 10 -j DROP

iptables -A INPUT -p tcp --dport 2212 -m state --state NEW -m recent \
--set --name ssh --rsource

iptables -A INPUT -p tcp --dport  2212 -m state --state NEW -m recent \
! --rcheck --seconds 60 --hitcount 4 --name ssh --rsource -j ACCEPT
 

### 03. Allow traffic on loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

### 04. Allow previously established connections to continue uninterupted
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

### 05. Accept packets belonging to established and related connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

### 06. Allow WWW connections on tcp port 80 443
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 80 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 10000 -m state --state NEW -j ACCEPT

### 07. Allow DNS
iptables -A INPUT -p udp -m udp --dport 53 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 53 -m state --state NEW -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 69 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 69 -m state --state NEW -j ACCEPT
### 08. Allow SMTP
iptables -A INPUT -p tcp -m tcp --dport 25 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 110 -m state --state NEW -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 123 -m state --state NEW -j ACCEPT
### 09. Allow SMTP
iptables -A INPUT -p tcp --dport 25 -j ACCEPT

### 10. Allows pop and pops connections
iptables -A INPUT -p tcp --dport 110 -j ACCEPT
iptables -A INPUT -p tcp --dport 995 -j ACCEPT

### 11. Allow Allows imap and imaps connections
iptables -A INPUT -p tcp --dport 143 -j ACCEPT
iptables -A INPUT -p tcp --dport 993 -j ACCEPT


#The Complete IPtables Anti-DDoS Rules
### 1: Drop invalid packets ###
/sbin/iptables -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP
iptables -A INPUT   -m state --state INVALID -j DROP
iptables -A FORWARD -m state --state INVALID -j DROP
iptables -A OUTPUT  -m state --state INVALID -j DROP

### 2: Drop TCP packets that are new and are not SYN ###
/sbin/iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP

### 3: Drop SYN packets with suspicious MSS value ###
/sbin/iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP

### 4: Block packets with bogus TCP flags ###
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP
/sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

### 05. Protection against port scanning ###
/sbin/iptables -N port-scanning
/sbin/iptables -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN
/sbin/iptables -A port-scanning -j DROP

# Anyone who tried to portscan us is locked out for an entire day.
iptables -A INPUT   -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DROP

# Once the day has passed, remove them from the portscan list
#iptables -A INPUT   -m recent --name portscan --remove
#iptables -A FORWARD -m recent --name portscan --remove

# These rules add scanners to the portscan list, and log the attempt.
iptables -A INPUT   -p tcp -m tcp --dport 139 \
    -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A INPUT   -p tcp -m tcp --dport 139 \
    -m recent --name portscan --set -j DROP

iptables -A FORWARD -p tcp -m tcp --dport 139 \
    -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A FORWARD -p tcp -m tcp --dport 139 \
    -m recent --name portscan --set -j DROP

### 6: Drop ICMP (you usually don't need this protocol) ###
/sbin/iptables -t mangle -A PREROUTING -p icmp -j DROP

### 7: Drop fragments in all chains ###
/sbin/iptables -t mangle -A PREROUTING -f -j DROP

### 8: Limit connections per source IP ###
#/sbin/iptables -A INPUT -p tcp -m connlimit --connlimit-above 111 -j REJECT --reject-with icmp-port-unreachable
/sbin/iptables -A INPUT -p tcp -m connlimit --connlimit-above 111 -j REJECT --reject-with icmp-port-unreachable

### 9: Limit RST packets ###
/sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP

### 10: Limit new TCP connections per second per source IP ###
/sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT
/sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP

### 11: Use SYNPROXY on all ports (disables connection limiting rule) ###
#/sbin/iptables -t raw -D PREROUTING -p tcp -m tcp --syn -j CT --notrack
#/sbin/iptables -D INPUT -p tcp -m tcp -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460
#/sbin/iptables -D INPUT -m conntrack --ctstate INVALID -j DROP

### 12: Protect against SYN floods
# Protect against SYN floods by rate limiting the number of new
# connections from any host to 60 per second.  This does *not* do rate
# limiting overall, because then someone could easily shut us down by
# saturating the limit.
iptables -A INPUT -m state --state NEW -p tcp -m tcp --syn \
    -m recent --name synflood --set
iptables -A INPUT -m state --state NEW -p tcp -m tcp --syn \
    -m recent --name synflood --update --seconds 1 --hitcount 60 -j DROP


#Incoming Connections
##To restrict the number of connections used by a single IP address, use iptables' connlimit module. For example:
iptables -I INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 25 -j REJECT --reject-with icmp-port-unreachable
iptables -I INPUT -p tcp --syn --dport 443 -m connlimit --connlimit-above 25 -j REJECT --reject-with icmp-port-unreachable

echo "save Configurations iptable-save > /etc/iptables/rules.v4"
iptables-save > /etc/iptables/rules.v4
EOF
root@deb:~#chmod u+x /root/bin/fw.*
root@deb:~#sh /root/bin/fw.start

 

مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

08-Linux Hard Disk Encryption With LUKS - Linux Hardening

 

8. Linux Hard Disk Encryption With LUKS

8.1 Install packages
root@deb:~#apt-get install cryptsetup cryptmount iproute2 net-tools moreutils
8.2 LUKS-formatting

#The LUKS-formatting command above has the following options:
#--verify-passphrase - ensures the passphrase is entered twice to avoid an incorrect passphrase being used
#-c aes -s 256 - uses 256-bit AES encryption
#-h sha256 - uses the 256-bit SHA hashing algorithm

root@deb:~#cryptsetup --verify-passphrase luksFormat /dev/vda2 -c aes -s 256 -h sha256
8.3 luksOpen
root@deb:~#cryptsetup luksOpen /dev/vda2 mydata
Enter passphrase for /dev/vda2:
8.4 Format encrypted disk

#The mkfs options above are as follows:
#-t ext4 - create an ext3 filesystem
#-m 2 - reduce the reserved super-user space down from the default of 5% to 2% of the total size - useful for large filesystems
#-O dir_index - speed-up lookups in large directories
#-O filetype - store filetype info in directories
#-O sparse_super - create fewer superblock backup copies - useful for large filesystems

root@deb:~#mkfs -t ext4 -m 2 -O dir_index,filetype,sparse_super /dev/mapper/mydata
8.5 Edit crypttab, fstab

When system is boot up, system ask you for passphrase to open encrypted disk and then mount it.

root@deb:~#cat /etc/crypttab
# <target name>    <source device>        <key file>    <options>
mydata        /dev/vda2    none luks
root@deb:~#cat /etc/fstab

/dev/mapper/mydata     /home   ext4   data=ordered,relatime,rw,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv1     0       2
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

09-How to Protect DDoS Attacks on Linux Services by Fail2Ban P1- Linux Hardening

 

How to Protect DDoS Attacks on Linux Services Part I

Training and initial installation of File2Ban service

امروزه حملات اینترنتی بسیار گسترده هستند، تنوع بالایی دارند و حفظ امنیت سرورها بیش از پیش دغدغه مدیران سیستم می باشد. استفاده از سرورهای لینوکس انتخاب اول ادمین ها می باشد. ولی اغلب این تصور اشتباه وجود دارد که لینوکس به خودی خود دارای امنیت است. و این تصور اشتباده است. و می بایست سیستم لینوکس خود را در تمام لایه ها سخت سازی نمایید. در یک سلسله مقاله نحوه سخت سازی لینوکس را در فضای نا امن اینترنت به شما آموزش میدهم و این آموزش  که چند قسمت می باشد در خصوص fail2ban می باشد.

Fail2Ban can help protect your Linux server from attack. It’s a Python package that monitors log files and dynamically adjusts firewall rules to block malicious IP addresses.
You can set (or use pre-configured) Python regexes - in Fail2Ban parlance, ‘filters’ - to determine malicious requests. If Fail2Ban detects a particular frequency of the filter regex in a specified log file, an iptables rule is dynamically generated that bans the abusive IP address for a set period of time.

Fail2Ban چیست و چطور کار میکند؟

Fail2Ban سرویسی بر روی لینوکس می باشد که کاربرد آن جبوگیری از حملات DOS و DDOS می باشد. حال روش کار چگونه می باشد؟ روش کار به این صورت است که لاگ های مربوط به سرویس مورد نظر را بررسی میکند و اگر در یک بازه زمانی تعداد درخواست ها نامتعارف بود و یا تعداد خطاهاب دسترسی از یک حدی بالاتر بود آن هنگام یک  Iptables Rule ایجاد میکند. و دسترسی ip حمله کننده Attacker را یه سرور شما میبندد یا Ban می کند. و بعد از آن بازه زمانی دوباره دسترسی برقرار میشود.
برای بررسی فایلها از Regex استفاده میشود که به صورت مفصل در آموزش LPIC1 که به صورت رایگان در دسترس  عموم قرار دارد توضیح داده ام.
برای هر سرویس یک section در فایل jail.local ایجاد میکنیم و ویژگی های مورد نظر از قبیل مسیر لاگ، Action مورد نظر، تعداد maxretry، زمان bantime و .. را مشخص میکنیم.

Install Fail2ban on Debian / Ubuntu / RHEL / CentOS

Debian / Ubuntu
root@debian:~#apt update
root@debian:~#apt install fail2ban
root@debian:~#systemctl enable fail2ban
RHEL / CentOS
root@rhel:~#yum install epel-release -y
root@rhel:~#yum install fail2ban fail2ban-systemd -y
root@rhel:~#systemctl enable fail2ban

If you have SELinux installed, then update the SELinux policies:

root@rhel:~# yum update -y selinux-policy* 

Fail2ban has four configuration file types:

root@debian:~#ls /etc/fail2ban
action.d       fail2ban.d  jail.conf  jail.local     paths-debian.conf
fail2ban.conf  filter.d    jail.d     paths-common.conf  paths-opensuse.conf
fail2ban.conf

Fail2Ban global configuration (such as logging)

filter.d/*.conf

Filters specifying how to detect authentication failures

بر اساس این فیلتر ها که همان Regular expression هستند جستجو در لاگ فایل ها انجام میگیرد برای هر section یک Regex وجود دارد.

root@debian:~#ls /etc/fail2ban/filter.d/
3proxy.conf            dropbear.conf         named-refused.conf    selinux-ssh.conf
apache-auth.conf       drupal-auth.conf      nginx-botsearch.conf  sendmail-auth.conf
apache-badbots.conf      ejabberd-auth.conf    nginx-http-auth.conf  sendmail-reject.conf
apache-botsearch.conf   exim-common.conf      nginx-limit-req.conf  sieve.conf
apache-common.conf       exim.conf             nsd.conf           slapd.conf
apache-fakegooglebot.conf  exim-spam.conf        openhab.conf       sogo-auth.conf
apache-modsecurity.conf    freeswitch.conf       openwebmail.conf      solid-pop3d.conf
apache-nohome.conf       froxlor-auth.conf     oracleims.conf       squid.conf
apache-noscript.conf       groupoffice.conf      pam-generic.conf      squirrelmail.conf
apache-overflows.conf      gssftpd.conf          perdition.conf       sshd.conf
apache-pass.conf       guacamole.conf        php-url-fopen.conf    sshd-ddos.conf
apache-shellshock.conf     haproxy-http-auth.conf portsentry.conf   stunnel.conf
assp.conf           horde.conf             postfix.conf      suhosin.conf
asterisk.conf           ignorecommands         postfix-rbl.conf  tine20.conf
botsearch-common.conf      joomla-login-errors.conf  postfix-sasl.conf uwimap-auth.conf
common.conf           kerio.conf             proftpd.conf      vsftpd.conf
counter-strike.conf       lighttpd-auth.conf        pure-ftpd.conf    webmin-auth.conf
courier-auth.conf       mongodb-auth.conf         qmail.conf        wordpress-login-errors.conf
courier-smtp.conf       monit.conf             recidive.conf     wuftpd.conf
cyrus-imap.conf           murmur.conf             roundcube-auth.conf   xinetd-fail.conf
directadmin.conf       mysqld-auth.conf         screensharingd.conf
dovecot.conf            nagios.conf             selinux-common.conf
action.d/*.conf

Actions defining the commands for banning and unbanning of IP address

root@debian:~#ls /etc/fail2ban/action.d/
apf.conf               iptables.conf                osx-ipfw.conf
badips.conf               iptables-ipset-proto4.conf         pf.conf
badips.py               iptables-ipset-proto6-allports.conf  route.conf
blocklist_de.conf           iptables-ipset-proto6.conf        sendmail-buffered.conf
bsd-ipfw.conf               iptables-multiport.conf             sendmail-common.conf
cloudflare.conf               iptables-multiport-log.conf         sendmail.conf
complain.conf               iptables-new.conf            sendmail-geoip-lines.conf
dshield.conf               iptables-xt_recent-echo.conf         sendmail-whois.conf
dummy.conf               mail-buffered.conf            sendmail-whois-ipjailmatches.conf
firewallcmd-allports.conf      mail.conf                sendmail-whois-ipmatches.conf
firewallcmd-ipset.conf         mail-whois-common.conf             sendmail-whois-lines.conf
firewallcmd-multiport.conf     mail-whois.conf                 sendmail-whois-matches.conf
firewallcmd-new.conf           mail-whois-lines.conf             shorewall.conf
firewallcmd-rich-logging.conf  mynetwatchman.conf            shorewall-ipset-proto6.conf
firewallcmd-rich-rules.conf    nftables-allports.conf             smtp.py
hostsdeny.conf               nftables-common.conf            symbiosis-blacklist-allports.conf
ipfilter.conf               nftables-multiport.conf             ufw.conf
ipfw.conf               npf.conf                    xarf-login-attack.conf
iptables-allports.conf         nsupdate.conf
iptables-common.conf           osx-afctl.conf
jail.conf
Configuration for the fail2ban server. jails defining combinations of Filters with Actions.
فایل پیکربندی پیش فرض که با هر بار بروز رسانی تغییر میکند بنابراین ما از فایل jail.local استفاده میکنیم. و پیکربندی های دلخواه خود را در آن قرار میدهیم.

JAIL CONFIGURATION FILE(S) (jail.conf)

logpath

Filename(s) of the log files to be monitored, separated by new lines.

action
Action shortcuts. To be used to define action parameter. Default banning action (e.g. iptables, iptables-new, iptables-multiport, shorewall, etc) It is used to define action_* variables. Can be overridden globally or per section within jail.local file
banaction = iptables-multiport
banaction_allports = iptables-allports

# The simplest action to take: ban only
action

ولی در این پیکربندی ها من از action_mw استفاده میکنم.

# ban & send an e-mail with whois report to the destemail.
action_mw
ignoreip

List of IPs not to ban. They can include a CIDR mask too. The list of IP addresses should be given with a space separator. This parameter is used to set your personal IP address (if you access the server from a fixed IP).

bantime

Effective ban duration (in seconds). Parameter is used to set the duration of seconds for which a host needs to be banned.

findtime

Findtime is the parameter which is used to check if a host must be banned or not. When the host generates maxrety in its last findtime, it is banned.

maxretry

Maxretry is the parameter used to set the limit for the number of retry's by a host, upon exceeding this limit, the host is banned.

backend

Backend to be used to detect changes in the logpath. It defaults to "auto" which will try "pyinotify", "gamin", "systemd" before "polling". Any of these can be specified. "pyinotify" is only valid on Linux systems with the "pyinotify" Python libraries. "gamin" requires the "gamin" libraries.

Port

Parameter may be changed to a new value such as port=1212, as is the case. When using port 22, there is no need to change this parameter.

Configure settings for Fail2Ban

root@debian:~#cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Open the jail.local file for editing in Nano with the following command.

Add a jail file to protect SSH.

Create a new file with the cat cmd.

root@debian:~#cat <<EOF>/etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = ssh
#action = firewallcmd-ipset
logpath = %(sshd_log)s
maxretry = 5
bantime = 86400
EOF
root@debian:~#ls /etc/fail2ban/jail.d/sshd.local
sshd.local
root@debian:~#ls /etc/fail2ban/filter.d/sshd.conf
sshd.conf

Running Fail2Ban service

Debian / Ubuntu
root@debian:~#systemctl enable fail2ban
root@debian:~#systemctl start fail2ban
RHEL / CentOS

When you are not running the CentOS Firewall yet, then start it:

root@rhel:~#systemctl enable firewalld
root@rhel:~#systemctl start firewalld
root@rhel:~#systemctl enable fail2ban
root@rhel:~#systemctl start fail2ban

Examining a jail - failregex

در پیکربندی سرویس fail2ban اغلب اشتباهات در قسمتی صورت می گیرد که log ها را مشخص میکنید می بایست هر مسیر لاگی که مشخص میکنید وجود داشته باشد. و همچنین صحت عملکرد فیلتر یا regex مورد نظر بررسی نمایید چند مثال را در ادامه برایتان اجرا میکنم.

root@debian:~# fail2ban-regex <logfile> <failregex>
root@debian:~# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed:    0
|  |- Total failed:    0
|  `- File list:    /var/log/auth.log
`- Actions
   |- Currently banned:    0
   |- Total banned:    0
   `- Banned IP list:   
root@debian:~# fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

Monitor Fail2ban Logs and Firewall Configuration

It's important to know that a service like Fail2ban is working as-intended. Start by using systemctl to check the status of the service:

root@debian:~#systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
   Loaded: loaded (/etc/systemd/system/fail2ban.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-10-12 10:49:54 +0330; 7h ago
     Docs: man:fail2ban(1)
  Process: 14859 ExecStop=/usr/bin/fail2ban-client stop (code=exited, status=0/SUCCESS)
  Process: 15404 ExecStart=/usr/bin/fail2ban-client -x start (code=exited, status=0/SUCCESS)
 Main PID: 15407 (fail2ban-server)
    Tasks: 37 (limit: 4915)
   CGroup: /system.slice/fail2ban.service
           └─15407 /usr/bin/python3 /usr/bin/fail2ban-server -s /var/run/fail2ban/fail2ban.sock -p /var/run/fail2

Oct 12 10:49:51 mx systemd[1]: Starting Fail2Ban Service...
Oct 12 10:49:52 mx fail2ban-client[15404]: 2018-10-12 10:49:52,537 fail2ban.server         [15405]: INFO    Start
Oct 12 10:49:52 mx fail2ban-client[15404]: 2018-10-12 10:49:52,544 fail2ban.server         [15405]: INFO    Start
Oct 12 10:49:54 mx systemd[1]: Started Fail2Ban Service.
lines 1-15/15 (END)

If something seems amiss here, you can troubleshoot by checking logs for the fail2ban unit since the last boot:

root@debian:~#journalctl -b -u fail2ban

Follow Fail2ban's log for a record of recent actions (press Ctrl-C to exit):

root@debian:~#journalctl -b -u fail2ban -f
root@debian:~#journalctl -b -u fail2ban.service -o cat
Stopping Fail2Ban Service...
Shutdown successful
Stopped Fail2Ban Service.
Starting Fail2Ban Service...
ERROR Failed during configuration: While reading from '/etc/fail2ban/jail.conf' [line 873]: section 'recidive' a
fail2ban.service: Control process exited, code=exited status=255
Failed to start Fail2Ban Service.
fail2ban.service: Unit entered failed state.
fail2ban.service: Failed with result 'exit-code'.

...
root@debian:~#tail -F /var/log/fail2ban.log
root@debian:~#tailf -40 /var/log/fail2ban.log
2018-10-10 12:41:34,780 fail2ban.jail           [10726]: INFO    Jail 'ssh-ddos' uses pyinotify {}
2018-10-10 12:41:34,784 fail2ban.jail           [10726]: INFO    Initiated 'pyinotify' backend
2018-10-10 12:41:34,786 fail2ban.filter         [10726]: INFO    Set maxRetry = 6
2018-10-10 12:41:34,786 fail2ban.filter         [10726]: INFO    Set jail log file encoding to UTF-8
2018-10-10 12:41:34,786 fail2ban.actions        [10726]: INFO    Set banTime = 31536000
2018-10-10 12:41:34,787 fail2ban.server         [10726]: INFO    Jail ssh-ddos is not a JournalFilter instance
2018-10-10 12:41:34,796 fail2ban.jail           [10726]: INFO    Creating new jail 'apache'
2018-10-10 12:41:34,796 fail2ban.jail           [10726]: INFO    Jail 'apache' uses pyinotify {}
2018-10-10 12:41:34,800 fail2ban.jail           [10726]: INFO    Initiated 'pyinotify' backend
2018-10-10 12:41:34,801 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/apache2/error.log
2018-10-10 12:41:34,802 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/artben.ir_error_log
2018-10-10 12:41:34,803 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/mbctux.com_error_log
2018-10-10 12:41:34,804 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/error_log
2018-10-10 12:41:34,805 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/merdasco.net_error_log
2018-10-10 12:41:34,806 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/mbctux.comm_error_log
2018-10-10 12:41:34,807 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/artfbs.com_error_log
2018-10-10 12:41:34,808 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/xashayar.ir_error_log
2018-10-10 12:41:34,808 fail2ban.filter         [10726]: INFO    Added logfile = /var/log/virtualmin/itstorage.co_error_log
2018-10-10 12:41:34,809 fail2ban.filter         [10726]: INFO    Set jail log file encoding to UTF-8
2018-10-10 12:41:34,809 fail2ban.filter         [10726]: INFO    Set maxRetry = 3
2018-10-10 12:41:34,810 fail2ban.filter         [10726]: INFO    Set findtime = 600
2018-10-10 12:41:34,810 fail2ban.actions        [10726]: INFO    Set banTime = 31536000
2018-10-10 12:41:34,841 fail2ban.jail           [10726]: INFO    Jail 'sshd' started

Next, use fail2ban-client to query the overall status of fail2ban-server, or any individual jail:

root@debian:~#fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed:    0
|  |- Total failed:    0
|  `- File list:    /var/log/auth.log
`- Actions
   |- Currently banned:    0
   |- Total banned:    0
   `- Banned IP list:   
root@debian:~#fail2ban-client status
Status
|- Number of jail:    1
`- Jail list:    sshd
root@debian:~#fail2ban-client status postfix-sasl
Status for the jail: postfix-sasl
|- Filter
|  |- Currently failed:    0
|  |- Total failed:    0
|  `- File list:    /var/log/mail.warn
`- Actions
   |- Currently banned:    14
   |- Total banned:    14
   `- Banned IP list:    94.180.245.230 94.180.195.42 94.230.153.106 94.26.187.40 61.160.90.214 94.136.55.2 99.230.112.235

Show iptables rules in a format that reflects the commands necessary to enable each rule:

root@debian:~#iptables -S

The following command is used to get a list of banned IP addresses which were recognized as brute force threats.

root@debian:~#iptables -L
root@debian:~#iptables -L -n

Brute-force testing of fail2ban

Possibility of DOS attack by a local user

Because syslog entries can be 'forged' by a regular user, e.g.:

root@debian:~#for ((i=0; i < 7; i++ )); do logger -p auth.warning -t 'sshd[123]' 'Illegal user user1 from 1.2.3.4'; done
root@debian:~#tailf  /var/log/fail2ban.log 2018-10-13 07:15:18,014 fail2ban.jail           [14366]: INFO    Jail 'postfix' started
2018-10-13 07:15:18,061 fail2ban.jail           [14366]: INFO    Jail 'dovecot' started
2018-10-13 07:15:18,165 fail2ban.jail           [14366]: INFO    Jail 'sieve' started
2018-10-13 07:15:18,270 fail2ban.jail           [14366]: INFO    Jail 'postfix-sasl' started
2018-10-13 07:15:18,344 fail2ban.jail           [14366]: INFO    Jail 'named-refused' started
2018-10-13 07:15:18,430 fail2ban.jail           [14366]: INFO    Jail 'mysqld-auth' started
2018-10-13 07:15:18,501 fail2ban.jail           [14366]: INFO    Jail 'joomla-login-errors' started
2018-10-13 07:15:18,607 fail2ban.jail           [14366]: INFO    Jail 'wordpress-login-errors' started
2018-10-13 07:15:18,655 fail2ban.jail           [14366]: INFO    Jail 'ssh-ddos' started
2018-10-13 07:15:18,778 fail2ban.jail           [14366]: INFO    Jail 'apache' started


2018-10-13 07:46:17,288 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:25,213 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:26,502 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:27,008 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:27,468 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:34,644 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4
2018-10-13 07:46:35,161 fail2ban.actions        [14366]: NOTICE  [sshd] Ban 1.2.3.4
2018-10-13 07:46:35,213 fail2ban.filter         [14366]: INFO    [sshd] Found 1.2.3.4

Unbanning an IP address

In order to remove an IP address from the banned list, parameter IPADDRESS is set to appropriate IP which needs unbanning. The name "sshd" is the name of the jail, in this case the "sshd" jail that we configured above. The following command does the job.

root@debian:~#fail2ban-client set sshd unbanip IPADDRESS

How Stop Fail2Ban

root@debian:~#service fail2ban stop
root@debian:~#ps -ef |grep fail2ban |awk '{print $2}'|xargs kill -9

How Start Fail2Ban

root@debian:~#iptables -F
root@debian:~#iptables -X
root@debian:~#iptables -t nat -F
root@debian:~#iptables -t nat -X
root@debian:~#iptables -t mangle -F
root@debian:~#iptables -t mangle -X
root@debian:~#iptables -P INPUT ACCEPT
root@debian:~#iptables -P FORWARD ACCEPT
root@debian:~#iptables -P OUTPUT ACCEPT

root@debian:~#service fail2ban start

Increase the debugging to help figure out why fail2ban isn't blocking anything when your regexs work with your configured log file.

root@debian:~#fail2ban-client set loglevel DEBUG

Fail2ban reload one jail or filter after change

After modifying the filter configuration you can update an already running instance of Fail2Ban using:

root@debian:~#fail2ban-client reload sshd
root@debian:~#fail2ban-client reload wordpress-login-errors

Fail2ban tree

root@debian:~#tree /etc/fail2ban
/etc/fail2ban
├── action.d
│   ├── apf.conf
│   ├── badips.conf
│   ├── badips.py
│   ├── blocklist_de.conf
│   ├── bsd-ipfw.conf
│   ├── cloudflare.conf
│   ├── complain.conf
│   ├── dshield.conf
│   ├── dummy.conf
│   ├── firewallcmd-allports.conf
│   ├── firewallcmd-ipset.conf
│   ├── firewallcmd-multiport.conf
│   ├── firewallcmd-new.conf
│   ├── firewallcmd-rich-logging.conf
│   ├── firewallcmd-rich-rules.conf
│   ├── hostsdeny.conf
│   ├── ipfilter.conf
│   ├── ipfw.conf
│   ├── iptables-allports.conf
│   ├── iptables-common.conf
│   ├── iptables.conf
│   ├── iptables-ipset-proto4.conf
│   ├── iptables-ipset-proto6-allports.conf
│   ├── iptables-ipset-proto6.conf
│   ├── iptables-multiport.conf
│   ├── iptables-multiport-log.conf
│   ├── iptables-new.conf
│   ├── iptables-xt_recent-echo.conf
│   ├── mail-buffered.conf
│   ├── mail.conf
│   ├── mail-whois-common.conf
│   ├── mail-whois.conf
│   ├── mail-whois-lines.conf
│   ├── mynetwatchman.conf
│   ├── nftables-allports.conf
│   ├── nftables-common.conf
│   ├── nftables-multiport.conf
│   ├── npf.conf
│   ├── nsupdate.conf
│   ├── osx-afctl.conf
│   ├── osx-ipfw.conf
│   ├── pf.conf
│   ├── route.conf
│   ├── sendmail-buffered.conf
│   ├── sendmail-common.conf
│   ├── sendmail.conf
│   ├── sendmail-geoip-lines.conf
│   ├── sendmail-whois.conf
│   ├── sendmail-whois-ipjailmatches.conf
│   ├── sendmail-whois-ipmatches.conf
│   ├── sendmail-whois-lines.conf
│   ├── sendmail-whois-matches.conf
│   ├── shorewall.conf
│   ├── shorewall-ipset-proto6.conf
│   ├── smtp.py
│   ├── symbiosis-blacklist-allports.conf
│   ├── ufw.conf
│   └── xarf-login-attack.conf
├── fail2ban.conf
├── fail2ban.d
├── filter.d
│   ├── 3proxy.conf
│   ├── apache-auth.conf
│   ├── apache-badbots.conf
│   ├── apache-botsearch.conf
│   ├── apache-common.conf
│   ├── apache-fakegooglebot.conf
│   ├── apache-modsecurity.conf
│   ├── apache-nohome.conf
│   ├── apache-noscript.conf
│   ├── apache-overflows.conf
│   ├── apache-pass.conf
│   ├── apache-shellshock.conf
│   ├── assp.conf
│   ├── asterisk.conf
│   ├── botsearch-common.conf
│   ├── common.conf
│   ├── counter-strike.conf
│   ├── courier-auth.conf
│   ├── courier-smtp.conf
│   ├── cyrus-imap.conf
│   ├── directadmin.conf
│   ├── dovecot.conf
│   ├── dropbear.conf
│   ├── drupal-auth.conf
│   ├── ejabberd-auth.conf
│   ├── exim-common.conf
│   ├── exim.conf
│   ├── exim-spam.conf
│   ├── freeswitch.conf
│   ├── froxlor-auth.conf
│   ├── groupoffice.conf
│   ├── gssftpd.conf
│   ├── guacamole.conf
│   ├── haproxy-http-auth.conf
│   ├── horde.conf
│   ├── ignorecommands
│   │   └── apache-fakegooglebot
│   ├── joomla-login-errors.conf
│   ├── kerio.conf
│   ├── lighttpd-auth.conf
│   ├── mongodb-auth.conf
│   ├── monit.conf
│   ├── murmur.conf
│   ├── mysqld-auth.conf
│   ├── nagios.conf
│   ├── named-refused.conf
│   ├── nginx-botsearch.conf
│   ├── nginx-http-auth.conf
│   ├── nginx-limit-req.conf
│   ├── nsd.conf
│   ├── openhab.conf
│   ├── openwebmail.conf
│   ├── oracleims.conf
│   ├── pam-generic.conf
│   ├── perdition.conf
│   ├── php-url-fopen.conf
│   ├── portsentry.conf
│   ├── postfix.conf
│   ├── postfix-rbl.conf
│   ├── postfix-sasl.conf
│   ├── proftpd.conf
│   ├── pure-ftpd.conf
│   ├── qmail.conf
│   ├── recidive.conf
│   ├── roundcube-auth.conf
│   ├── screensharingd.conf
│   ├── selinux-common.conf
│   ├── selinux-ssh.conf
│   ├── sendmail-auth.conf
│   ├── sendmail-reject.conf
│   ├── sieve.conf
│   ├── slapd.conf
│   ├── sogo-auth.conf
│   ├── solid-pop3d.conf
│   ├── squid.conf
│   ├── squirrelmail.conf
│   ├── sshd.conf
│   ├── sshd-ddos.conf
│   ├── stunnel.conf
│   ├── suhosin.conf
│   ├── tine20.conf
│   ├── uwimap-auth.conf
│   ├── vsftpd.conf
│   ├── webmin-auth.conf
│   ├── wordpress-login-errors.conf
│   ├── wuftpd.conf
│   └── xinetd-fail.conf
├── jail.conf
├── jail.d
│   ├── defaults-debian.conf
│   ├── joomla-login-errors.conf
│   └── wordpress-login-errors.conf
├── jail.local
├── paths-common.conf
├── paths-debian.conf
└── paths-opensuse.conf

5 directories, 153 files

 

مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

10-How to Protect DDoS Attacks on Linux Services by Fail2Ban P2- Linux Hardening

How to Protect DDoS Attacks on Linux Services - Part II

SSH, Apache, Bind DNS, DDoS Protection with Fail2Ban

امروزه حملات اینترنتی بسیار گسترده هستند، تنوع بالایی دارند و حفظ امنیت سرورها بیش از پیش دغدغه مدیران سیستم می باشد. استفاده از سرورهای لینوکس انتخاب اول ادمین ها می باشد. ولی اغلب این تصور اشتباه وجود دارد که لینوکس به خودی خود دارای امنیت است. و این تصور اشتباده است. و می بایست سیستم لینوکس خود را در تمام لایه ها سخت سازی نمایید. در یک سلسله مقاله نحوه سخت سازی لینوکس را در فضای نا امن اینترنت به شما آموزش میدهم و این آموزش که چند قسمت می باشد در خصوص fail2ban می باشد.

Fail2Ban can help protect your Linux server from attack. It’s a Python package that monitors log files and dynamically adjusts firewall rules to block malicious IP addresses.
You can set (or use pre-configured) Python regexes - in Fail2Ban parlance, ‘filters’ - to determine malicious requests. If Fail2Ban detects a particular frequency of the filter regex in a specified log file, an iptables rule is dynamically generated that bans the abusive IP address for a set period of time.

Fail2Ban چیست و چطور کار میکند؟

Fail2Ban سرویسی بر روی لینوکس می باشد که کاربرد آن جبوگیری از حملات DOS و DDOS می باشد. حال روش کار چگونه می باشد؟ روش کار به این صورت است که لاگ های مربوط به سرویس مورد نظر را بررسی میکند و اگر در یک بازه زمانی تعداد درخواست ها نامتعارف بود و یا تعداد خطاهاب دسترسی از یک حدی بالاتر بود آن هنگام یک Iptables Rule ایجاد میکند. و دسترسی ip حمله کننده Attacker را یه سرور شما میبندد یا Ban می کند. و بعد از آن بازه زمانی دوباره دسترسی برقرار میشود.
برای بررسی فایلها از Regex استفاده میشود که به صورت مفصل در آموزش LPIC1 که به صورت رایگان در دسترس عموم قرار دارد توضیح داده ام.
برای هر سرویس یک section در فایل jail.local ایجاد میکنیم و ویژگی های مورد نظر از قبیل مسیر لاگ، Action مورد نظر، تعداد maxretry، زمان bantime و .. را مشخص میکنیم.

Install Fail2ban on Debian / Ubuntu / RHEL / CentOS

Debian / Ubuntu
root@debian:~#apt update
root@debian:~#apt install fail2ban
root@debian:~#systemctl enable fail2ban
RHEL / CentOS
root@rhel:~#yum install epel-release -y
root@rhel:~#yum install fail2ban fail2ban-systemd -y
root@rhel:~#systemctl enable fail2ban

If you have SELinux installed, then update the SELinux policies:

root@rhel:~# yum update -y selinux-policy*

Fail2ban has four configuration file types:

root@debian:~#ls /etc/fail2ban
action.d fail2ban.d jail.conf jail.local paths-debian.conf
fail2ban.conf filter.d jail.d paths-common.conf paths-opensuse.conf
fail2ban.conf

Fail2Ban global configuration (such as logging)

filter.d/*.conf

Filters specifying how to detect authentication failures

بر اساس این فیلتر ها که همان Regular expression هستند جستجو در لاگ فایل ها انجام میگیرد برای هر section یک Regex وجود دارد.

root@debian:~#ls /etc/fail2ban/filter.d/
3proxy.conf dropbear.conf named-refused.conf selinux-ssh.conf
apache-auth.conf drupal-auth.conf nginx-botsearch.conf sendmail-auth.conf
apache-badbots.conf ejabberd-auth.conf nginx-http-auth.conf sendmail-reject.conf
apache-botsearch.conf exim-common.conf nginx-limit-req.conf sieve.conf
apache-common.conf exim.conf nsd.conf slapd.conf
apache-fakegooglebot.conf exim-spam.conf openhab.conf sogo-auth.conf
apache-modsecurity.conf freeswitch.conf openwebmail.conf solid-pop3d.conf
apache-nohome.conf froxlor-auth.conf oracleims.conf squid.conf
apache-noscript.conf groupoffice.conf pam-generic.conf squirrelmail.conf
apache-overflows.conf gssftpd.conf perdition.conf sshd.conf
apache-pass.conf guacamole.conf php-url-fopen.conf sshd-ddos.conf
apache-shellshock.conf haproxy-http-auth.conf portsentry.conf stunnel.conf
assp.conf horde.conf postfix.conf suhosin.conf
asterisk.conf ignorecommands postfix-rbl.conf tine20.conf
botsearch-common.conf joomla-login-errors.conf postfix-sasl.conf uwimap-auth.conf
common.conf kerio.conf proftpd.conf vsftpd.conf
counter-strike.conf lighttpd-auth.conf pure-ftpd.conf webmin-auth.conf
courier-auth.conf mongodb-auth.conf qmail.conf wordpress-login-errors.conf
courier-smtp.conf monit.conf recidive.conf wuftpd.conf
cyrus-imap.conf murmur.conf roundcube-auth.conf xinetd-fail.conf
directadmin.conf mysqld-auth.conf screensharingd.conf
dovecot.conf nagios.conf selinux-common.conf
action.d/*.conf

Actions defining the commands for banning and unbanning of IP address

root@debian:~#ls /etc/fail2ban/action.d/
apf.conf iptables.conf osx-ipfw.conf
badips.conf iptables-ipset-proto4.conf pf.conf
badips.py iptables-ipset-proto6-allports.conf route.conf
blocklist_de.conf iptables-ipset-proto6.conf sendmail-buffered.conf
bsd-ipfw.conf iptables-multiport.conf sendmail-common.conf
cloudflare.conf iptables-multiport-log.conf sendmail.conf
complain.conf iptables-new.conf sendmail-geoip-lines.conf
dshield.conf iptables-xt_recent-echo.conf sendmail-whois.conf
dummy.conf mail-buffered.conf sendmail-whois-ipjailmatches.conf
firewallcmd-allports.conf mail.conf sendmail-whois-ipmatches.conf
firewallcmd-ipset.conf mail-whois-common.conf sendmail-whois-lines.conf
firewallcmd-multiport.conf mail-whois.conf sendmail-whois-matches.conf
firewallcmd-new.conf mail-whois-lines.conf shorewall.conf
firewallcmd-rich-logging.conf mynetwatchman.conf shorewall-ipset-proto6.conf
firewallcmd-rich-rules.conf nftables-allports.conf smtp.py
hostsdeny.conf nftables-common.conf symbiosis-blacklist-allports.conf
ipfilter.conf nftables-multiport.conf ufw.conf
ipfw.conf npf.conf xarf-login-attack.conf
iptables-allports.conf nsupdate.conf
iptables-common.conf osx-afctl.conf
jail.conf
Configuration for the fail2ban server. jails defining combinations of Filters with Actions.
فایل پیکربندی پیش فرض که با هر بار بروز رسانی تغییر میکند بنابراین ما از فایل jail.local استفاده میکنیم. و پیکربندی های دلخواه خود را در آن قرار میدهیم.

JAIL CONFIGURATION FILE(S) (jail.conf)

logpath

Filename(s) of the log files to be monitored, separated by new lines.

action
Action shortcuts. To be used to define action parameter. Default banning action (e.g. iptables, iptables-new, iptables-multiport, shorewall, etc) It is used to define action_* variables. Can be overridden globally or per section within jail.local file
banaction = iptables-multiport
banaction_allports = iptables-allports

# The simplest action to take: ban only
action

ولی در این پیکربندی ها من از action_mw استفاده میکنم.

# ban & send an e-mail with whois report to the destemail.
action_mw
ignoreip

List of IPs not to ban. They can include a CIDR mask too. The list of IP addresses should be given with a space separator. This parameter is used to set your personal IP address (if you access the server from a fixed IP).

bantime

Effective ban duration (in seconds). Parameter is used to set the duration of seconds for which a host needs to be banned.

findtime

Findtime is the parameter which is used to check if a host must be banned or not. When the host generates maxrety in its last findtime, it is banned.

maxretry

Maxretry is the parameter used to set the limit for the number of retry's by a host, upon exceeding this limit, the host is banned.

backend

Backend to be used to detect changes in the logpath. It defaults to "auto" which will try "pyinotify", "gamin", "systemd" before "polling". Any of these can be specified. "pyinotify" is only valid on Linux systems with the "pyinotify" Python libraries. "gamin" requires the "gamin" libraries.

Port

Parameter may be changed to a new value such as port=1212, as is the case. When using port 22, there is no need to change this parameter.

Configure settings for Fail2Ban

root@debian:~#cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Open the jail.local file for editing in Nano with the following command.

Add a jail file to protect SSH.

Create a new file with the cat cmd.

root@debian:~#cat <<EOF>/etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = ssh
#action = firewallcmd-ipset
logpath = %(sshd_log)s
maxretry = 5
bantime = 86400
EOF
sasl.conf
root@debian:~#ls /etc/fail2ban/jail.d/sshd.local
sshd.local
root@debian:~#/etc/fail2ban/filter.d/sshd.conf
sshd.conf

Running Fail2Ban service

Debian / Ubuntu
root@debian:~#systemctl enable fail2ban
root@debian:~#systemctl start fail2ban
RHEL / CentOS

When you are not running the CentOS Firewall yet, then start it:

root@rhel:~#systemctl enable firewalld
root@rhel:~#systemctl start firewalld
root@rhel:~#systemctl enable fail2ban
root@rhel:~#systemctl start fail2ban

Monitor Fail2ban Logs and Firewall Configuration

It's important to know that a service like Fail2ban is working as-intended. Start by using systemctl to check the status of the service:

root@debian:~#systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
Loaded: loaded (/etc/systemd/system/fail2ban.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2018-10-12 10:49:54 +0330; 7h ago
Docs: man:fail2ban(1)
Process: 14859 ExecStop=/usr/bin/fail2ban-client stop (code=exited, status=0/SUCCESS)
Process: 15404 ExecStart=/usr/bin/fail2ban-client -x start (code=exited, status=0/SUCCESS)
Main PID: 15407 (fail2ban-server)
Tasks: 37 (limit: 4915)
CGroup: /system.slice/fail2ban.service
└─15407 /usr/bin/python3 /usr/bin/fail2ban-server -s /var/run/fail2ban/fail2ban.sock -p /var/run/fail2

Oct 12 10:49:51 mx systemd[1]: Starting Fail2Ban Service...
Oct 12 10:49:52 mx fail2ban-client[15404]: 2018-10-12 10:49:52,537 fail2ban.server [15405]: INFO Start
Oct 12 10:49:52 mx fail2ban-client[15404]: 2018-10-12 10:49:52,544 fail2ban.server [15405]: INFO Start
Oct 12 10:49:54 mx systemd[1]: Started Fail2Ban Service.
lines 1-15/15 (END)

If something seems amiss here, you can troubleshoot by checking logs for the fail2ban unit since the last boot:

root@debian:~#journalctl -b -u fail2ban

Follow Fail2ban's log for a record of recent actions (press Ctrl-C to exit):

root@debian:~#journalctl -b -u fail2ban -f
root@debian:~#journalctl -b -u fail2ban.service -o cat
Stopping Fail2Ban Service...
Shutdown successful
Stopped Fail2Ban Service.
Starting Fail2Ban Service...
ERROR Failed during configuration: While reading from '/etc/fail2ban/jail.conf' [line 873]: section 'recidive' a
fail2ban.service: Control process exited, code=exited status=255
Failed to start Fail2Ban Service.
fail2ban.service: Unit entered failed state.
fail2ban.service: Failed with result 'exit-code'.

...
root@debian:~#tail -F /var/log/fail2ban.log
root@debian:~#tailf -40 /var/log/fail2ban.log
2018-10-10 12:41:34,780 fail2ban.jail [10726]: INFO Jail 'ssh-ddos' uses pyinotify {}
2018-10-10 12:41:34,784 fail2ban.jail [10726]: INFO Initiated 'pyinotify' backend
2018-10-10 12:41:34,786 fail2ban.filter [10726]: INFO Set maxRetry = 6
2018-10-10 12:41:34,786 fail2ban.filter [10726]: INFO Set jail log file encoding to UTF-8
2018-10-10 12:41:34,786 fail2ban.actions [10726]: INFO Set banTime = 31536000
2018-10-10 12:41:34,787 fail2ban.server [10726]: INFO Jail ssh-ddos is not a JournalFilter instance
2018-10-10 12:41:34,796 fail2ban.jail [10726]: INFO Creating new jail 'apache'
2018-10-10 12:41:34,796 fail2ban.jail [10726]: INFO Jail 'apache' uses pyinotify {}
2018-10-10 12:41:34,800 fail2ban.jail [10726]: INFO Initiated 'pyinotify' backend
2018-10-10 12:41:34,801 fail2ban.filter [10726]: INFO Added logfile = /var/log/apache2/error.log
2018-10-10 12:41:34,802 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/artben.ir_error_log
2018-10-10 12:41:34,803 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/mbctux.com_error_log
2018-10-10 12:41:34,804 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/error_log
2018-10-10 12:41:34,805 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/merdasco.net_error_log
2018-10-10 12:41:34,806 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/mbctux.comm_error_log
2018-10-10 12:41:34,807 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/artfbs.com_error_log
2018-10-10 12:41:34,808 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/xashayar.ir_error_log
2018-10-10 12:41:34,808 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/itstorage.co_error_log
2018-10-10 12:41:34,809 fail2ban.filter [10726]: INFO Set jail log file encoding to UTF-8
2018-10-10 12:41:34,809 fail2ban.filter [10726]: INFO Set maxRetry = 3
2018-10-10 12:41:34,810 fail2ban.filter [10726]: INFO Set findtime = 600
2018-10-10 12:41:34,810 fail2ban.actions [10726]: INFO Set banTime = 31536000
2018-10-10 12:41:34,841 fail2ban.jail [10726]: INFO Jail 'sshd' started

Next, use fail2ban-client to query the overall status of fail2ban-server, or any individual jail:

root@debian:~#fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:
root@debian:~#fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd
root@debian:~#fail2ban-client status postfix-sasl
Status for the jail: postfix-sasl
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- File list: /var/log/mail.warn
`- Actions
|- Currently banned: 14
|- Total banned: 14
`- Banned IP list: 94.180.245.230 94.180.195.42 94.230.153.106 94.26.187.40 61.160.90.214 94.136.55.2 99.230.112.235

Show iptables rules in a format that reflects the commands necessary to enable each rule:

root@debian:~#iptables -S

The following command is used to get a list of banned IP addresses which were recognized as brute force threats.

root@debian:~#iptables -L
root@debian:~#iptables -L -n

Unbanning an IP address

In order to remove an IP address from the banned list, parameter IPADDRESS is set to appropriate IP which needs unbanning. The name "sshd" is the name of the jail, in this case the "sshd" jail that we configured above. The following command does the job.

root@debian:~#fail2ban-client set sshd unbanip IPADDRESS
root@debian:~#fail2ban-regex /var/log/mail.log /etc/fail2ban/filter.d/postfix-sasl.conf 

Running tests
=============

Use failregex filter file : postfix-sasl, basedir: /etc/fail2ban
Use log file : /var/log/mail.log
Use encoding : UTF-8


Results
=======

Failregex: 2 total
|- #) [# of hits] regular expression
| 1) [2] ^(?:\[\])?\s*(?:<[^.]+\.[^.]+>\s+)?(?:\S+\s+)?(?:kernel: \[ *\d+\.\d+\]\s+)?(?:@vserver_\S+\s+)?(?:(?:(?:\[\d+\])?:\s+[\[\(]?postfix(-\w+)?/(?:submission/|smtps/)?smtp[ds](?:\(\S+\))?[\]\)]?:?|[\[\(]?postfix(-\w+)?/(?:submission/|smtps/)?smtp[ds](?:\(\S+\))?[\]\)]?:?(?:\[\d+\])?:?)\s+)?(?:\[ID \d+ \S+\]\s+)?warning: [-._\w]+\[<HOST>\]: SASL ((?i)LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(:[ A-Za-z0-9+/:]*={0,2})?\s*$
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
| [70580] (?:DAY )?MON Day 24hour:Minute:Second(?:\.Microseconds)?(?: Year)?
`-

Lines: 70580 lines, 0 ignored, 2 matched, 70578 missed
[processed in 4.54 sec]

Missed line(s): too many to print. Use --print-all-missed to print all 70578 lines
root@debian:~#cat /etc/fail2ban/jail.local |grep -v ^#
# Fail2ban overrides
# These rules override `/etc/fail2ban/jail.conf`.
# =============================================================
[INCLUDES]
#before = paths-distro.conf
before = paths-debian.conf

[DEFAULT]
# List of safe IP addresses
ignoreip = 127.0.0.1/8, 2.190.92.225/32

# ignorecommand = /path/to/command <ip>
ignorecommand =

# Ban bad hosts for one hour:
#bantime = 3600 # 1 hour
#bantime = 31536000 # 1 year
bantime = 1200 # 10Min

# E-mail
mta = mail
sender = fail2ban@localhost
destemail = این آدرس ایمیل توسط spambots حفاظت می شود. برای دیدن شما نیاز به جاوا اسکریپت دارید


# Action
#action = %(action_)s
action = %(action_mw)s
banaction = iptables-multiport
banaction_allports = iptables-allports

#
# JAILS
#
# ============================================================
# SSH Jails
# ============================================================
[sshd]
enabled = true
port = 22,2212
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 6
bantime = 1200

[ssh-ddos]
enabled = true
port = ssh,sftp,2212
filter = sshd-ddos
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 6
bantime = 1200

# ============================================================
# Email Service Jails
# ============================================================
[postfix]
enabled = true
port = smtp,465,submission
logpath = %(postfix_log)s
backend = %(postfix_backend)s
maxretry = 6
bantime = 1200

[postfix-sasl]
enabled = true
port = smtp,465,submission,imap,imaps,pop3,pop3s
logpath = %(postfix_log)s
backend = %(postfix_backend)s
maxretry = 3
bantime = 1200

[dovecot]
enabled = true
port = pop3,pop3s,imap,imaps,submission,465,sieve
logpath = %(dovecot_log)s
backend = %(dovecot_backend)s
maxretry = 3
bantime = 1200

[sieve]
enabled = true
port = smtp,465,submission
logpath = %(dovecot_log)s
backend = %(dovecot_backend)s
maxretry = 3
bantime = 1200

# ============================================================
# Named Jails
# ============================================================
[named-refused]
enabled = true
maxretry = 4
bantime = 1200

# ============================================================
# Apache Jails
# ============================================================

[apache]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log

maxretry = 3
findtime = 600
ignoreip = 127.0.0.1

[apache-noscript]
enabled = true
port = http,https
filter = apache-noscript
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log
maxretry = 3
findtime = 600
ignoreip = 127.0.0.1

[apache-overflows]
enabled = true
port = http,https
filter = apache-overflows
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log
maxretry = 2
findtime = 600
ignoreip = 127.0.0.1

[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/*access.log
/var/log/virtualmin/*access_log
maxretry = 2
findtime = 600
ignoreip = 127.0.0.1

[apache-fakegooglebot]
port = http,https
logpath = /var/log/apache2/*access.log
/var/log/virtualmin/*access_log
maxretry = 1
ignorecommand = %(ignorecommands_dir)s/apache-fakegooglebot <ip>

[apache-botsearch]

port = http,https
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log
maxretry = 2

[apache-nohome]

port = http,https
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log
maxretry = 2

[webmin-auth]
enabled = true
port = 10000
maxretry = 6
bantime = 1200


[apache-shellshock]
enabled = true
port = http,https
logpath = /var/log/apache2/*error.log
/var/log/virtualmin/*error_log
maxretry = 4
bantime = 1200


[php-url-fopen]
enabled = true
maxretry = 4
bantime = 1200


# ============================================================
# FTP Service Jails
# ============================================================

[proftpd]
enabled = true
port = ftp,ftp-data,ftps,ftps-data
maxretry = 6
bantime = 1200

# ============================================================
# Mysql Service Jails
# ============================================================

[mysqld-auth]
enabled = true
maxretry = 4
bantime = 1200

 

root@debian:~#fail2ban-client status
Status
|- Number of jail: 18
`- Jail list: apache-auth, apache-botsearch, apache-fakegooglebot, apache-nohome, apache-noscript, apache-overflows, apache-shellshock, dovecot, mysqld-auth, named-refused, php-url-fopen, postfix, postfix-sasl, proftpd, ssh-ddos, sshd, sshd-ddos, webmin-auth

root@debian:~#tailf -40 /var/log/fail2ban.log
2018-10-10 12:41:34,780 fail2ban.jail [10726]: INFO Jail 'ssh-ddos' uses pyinotify {}
2018-10-10 12:41:34,784 fail2ban.jail [10726]: INFO Initiated 'pyinotify' backend
2018-10-10 12:41:34,786 fail2ban.filter [10726]: INFO Set maxRetry = 6
2018-10-10 12:41:34,786 fail2ban.filter [10726]: INFO Set jail log file encoding to UTF-8
2018-10-10 12:41:34,786 fail2ban.actions [10726]: INFO Set banTime = 31536000
2018-10-10 12:41:34,787 fail2ban.server [10726]: INFO Jail ssh-ddos is not a JournalFilter instance
2018-10-10 12:41:34,796 fail2ban.jail [10726]: INFO Creating new jail 'apache'
2018-10-10 12:41:34,796 fail2ban.jail [10726]: INFO Jail 'apache' uses pyinotify {}
2018-10-10 12:41:34,800 fail2ban.jail [10726]: INFO Initiated 'pyinotify' backend
2018-10-10 12:41:34,801 fail2ban.filter [10726]: INFO Added logfile = /var/log/apache2/error.log
2018-10-10 12:41:34,802 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/artben.ir_error_log
2018-10-10 12:41:34,803 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/mbctux.com_error_log
2018-10-10 12:41:34,804 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/error_log
2018-10-10 12:41:34,805 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/merdasco.net_error_log
2018-10-10 12:41:34,806 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/mbctux.comm_error_log
2018-10-10 12:41:34,807 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/artfbs.com_error_log
2018-10-10 12:41:34,808 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/xashayar.ir_error_log
2018-10-10 12:41:34,808 fail2ban.filter [10726]: INFO Added logfile = /var/log/virtualmin/itstorage.co_error_log
2018-10-10 12:41:34,809 fail2ban.filter [10726]: INFO Set jail log file encoding to UTF-8
2018-10-10 12:41:34,809 fail2ban.filter [10726]: INFO Set maxRetry = 3
2018-10-10 12:41:34,810 fail2ban.filter [10726]: INFO Set findtime = 600
2018-10-10 12:41:34,810 fail2ban.actions [10726]: INFO Set banTime = 31536000
2018-10-10 12:41:34,841 fail2ban.jail [10726]: INFO Jail 'sshd' started
2018-10-10 12:41:34,848 fail2ban.jail [10726]: INFO Jail 'sshd-ddos' started
2018-10-10 12:41:34,852 fail2ban.jail [10726]: INFO Jail 'apache-badbots' started
2018-10-10 12:41:34,870 fail2ban.jail [10726]: INFO Jail 'apache-noscript' started
2018-10-10 12:41:34,884 fail2ban.jail [10726]: INFO Jail 'apache-overflows' started
2018-10-10 12:41:34,899 fail2ban.jail [10726]: INFO Jail 'apache-nohome' started
2018-10-10 12:41:34,914 fail2ban.jail [10726]: INFO Jail 'apache-botsearch' started
2018-10-10 12:41:34,927 fail2ban.jail [10726]: INFO Jail 'apache-shellshock' started
2018-10-10 12:41:34,946 fail2ban.jail [10726]: INFO Jail 'php-url-fopen' started
2018-10-10 12:41:34,963 fail2ban.jail [10726]: INFO Jail 'webmin-auth' started
2018-10-10 12:41:34,986 fail2ban.jail [10726]: INFO Jail 'proftpd' started
2018-10-10 12:41:35,007 fail2ban.jail [10726]: INFO Jail 'postfix' started
2018-10-10 12:41:35,027 fail2ban.jail [10726]: INFO Jail 'dovecot' started
2018-10-10 12:41:35,050 fail2ban.jail [10726]: INFO Jail 'postfix-sasl' started
2018-10-10 12:41:35,071 fail2ban.jail [10726]: INFO Jail 'named-refused' started
2018-10-10 12:41:35,092 fail2ban.jail [10726]: INFO Jail 'mysqld-auth' started
2018-10-10 12:41:35,112 fail2ban.jail [10726]: INFO Jail 'ssh-ddos' started
2018-10-10 12:41:35,123 fail2ban.jail [10726]: INFO Jail 'apache' started


root@debian:~#tailf /var/log/fail2ban.log
...

2018-10-09 23:28:19,393 fail2ban.actions [22651]: NOTICE [postfix-sasl] Ban 94.180.245.230
2018-10-09 23:28:19,726 fail2ban.actions [22651]: NOTICE [postfix-sasl] Ban 94.198.195.42
2018-10-09 23:28:20,058 fail2ban.actions [22651]: NOTICE [postfix-sasl] Ban 94.230.153.106
2018-10-09 23:28:20,389 fail2ban.actions [22651]: NOTICE [postfix-sasl] Ban 94.26.187.40

....

root@debian:~#journalctl -u fail2ban.service -f
-- Logs begin at Wed 2018-10-10 12:00:19 +0330. --
Oct 10 13:37:02 mx fail2ban-client[20333]: 2018-10-10 13:37:02,376 fail2ban.server [20334]: INFO Starting Fail2ban v0.9.6
Oct 10 13:37:02 mx fail2ban-client[20333]: 2018-10-10 13:37:02,377 fail2ban.server [20334]: INFO Starting in daemon mode
Oct 10 13:37:04 mx systemd[1]: Started Fail2Ban Service.
Oct 10 14:10:41 mx systemd[1]: Stopping Fail2Ban Service...
Oct 10 14:10:52 mx fail2ban-client[23587]: Shutdown successful
Oct 10 14:10:52 mx systemd[1]: Stopped Fail2Ban Service.
Oct 10 14:10:55 mx systemd[1]: Starting Fail2Ban Service...
Oct 10 14:10:56 mx fail2ban-client[23878]: 2018-10-10 14:10:56,021 fail2ban.server [23879]: INFO Starting Fail2ban v0.9.6
Oct 10 14:10:56 mx fail2ban-client[23878]: 2018-10-10 14:10:56,022 fail2ban.server [23879]: INFO Starting in daemon mode
Oct 10 14:10:56 mx systemd[1]: Started Fail2Ban Service.
...
root@debian:~#iptables -L
Chain INPUT (policy DROP)
target prot opt source destination
f2b-webmin-auth tcp -- anywhere anywhere multiport dports webmin
f2b-named-refused tcp -- anywhere anywhere multiport dports domain,953
f2b-dovecot tcp -- anywhere anywhere multiport dports pop3,pop3s,imap2,imaps,submission,urd,sieve
f2b-ssh-ddos tcp -- anywhere anywhere multiport dports ssh,sftp,2212
f2b-postfix tcp -- anywhere anywhere multiport dports smtp,urd,submission
f2b-apache-shellshock tcp -- anywhere anywhere multiport dports http,https
f2b-mysqld-auth tcp -- anywhere anywhere multiport dports mysql
REJECT tcp -- anywhere anywhere tcp dpt:https flags:FIN,SYN,RST,ACK/SYN #conn src/32 > 25 reject-with icmp-port-unreachable
REJECT tcp -- anywhere anywhere tcp dpt:http flags:FIN,SYN,RST,ACK/SYN #conn src/32 > 25 reject-with icmp-port-unreachable
f2b-proftpd tcp -- anywhere anywhere multiport dports ftp,ftp-data,ftps,ftps-data
f2b-php-url-fopen tcp -- anywhere anywhere multiport dports http,https
f2b-apache-overflows tcp -- anywhere anywhere multiport dports http,https
f2b-apache-botsearch tcp -- anywhere anywhere multiport dports http,https
f2b-apache-auth tcp -- anywhere anywhere multiport dports http,https
f2b-sshd-ddos tcp -- anywhere anywhere multiport dports ssh
f2b-apache-fakegooglebot tcp -- anywhere anywhere multiport dports http,https
f2b-apache-nohome tcp -- anywhere anywhere multiport dports http,https
f2b-apache-noscript tcp -- anywhere anywhere multiport dports http,https
f2b-sshd tcp -- anywhere anywhere multiport dports ssh,2212
ACCEPT tcp -- anywhere anywhere tcp dpt:2212
ACCEPT tcp -- anywhere anywhere tcp dpt:2212 state NEW
tcp -- anywhere anywhere tcp dpt:ssh ctstate NEW recent: SET name: DEFAULT side: source mask: 255.255.255.255
DROP tcp -- anywhere anywhere tcp dpt:ssh ctstate NEW recent: UPDATE seconds: 60 hit_count: 10 name: DEFAULT side: source mask: 255.255.255.255
ACCEPT tcp -- anywhere anywhere tcp dpt:smtp state NEW
ACCEPT tcp -- anywhere anywhere tcp dpt:pop3 state NEW
ACCEPT udp -- anywhere anywhere udp dpt:ntp state NEW
ACCEPT tcp -- anywhere anywhere tcp dpt:smtp
ACCEPT tcp -- anywhere anywhere tcp dpt:pop3
ACCEPT tcp -- anywhere anywhere tcp dpt:pop3s
ACCEPT tcp -- anywhere anywhere tcp dpt:imap2
ACCEPT tcp -- anywhere anywhere tcp dpt:imaps
DROP all -- anywhere anywhere state INVALID
DROP all -- anywhere anywhere recent: CHECK seconds: 86400 name: portscan side: source mask: 255.255.255.255
LOG tcp -- anywhere anywhere tcp dpt:netbios-ssn recent: SET name: portscan side: source mask: 255.255.255.255 LOG level warning prefix "Portscan:"
DROP tcp -- anywhere anywhere tcp dpt:netbios-ssn recent: SET name: portscan side: source mask: 255.255.255.255
REJECT all -- static-5-2-137-13.rdsnet.ro anywhere reject-with icmp-port-unreachable
REJECT all -- 12.2.202.242 anywhere reject-with icmp-port-unreachable
REJECT all -- home.ndst.pw anywhere reject-with icmp-port-unreachable
REJECT all -- 89.184.13.32 anywhere reject-with icmp-port-unreachable
REJECT all -- wimax-client.yota.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 109.248.253.18 anywhere reject-with icmp-port-unreachable
REJECT all -- 189-89-165-104.STATIC.itsweb.com.br anywhere reject-with icmp-port-unreachable
REJECT all -- 103-239-255-206.Dhaka.carnival.com.bd anywhere reject-with icmp-port-unreachable
REJECT all -- 83.169.208.183 anywhere reject-with icmp-port-unreachable
REJECT all -- c-98-193-60-252.hsd1.il.comcast.net anywhere reject-with icmp-port-unreachable
REJECT all -- wsip-98-190-241-3.hr.hr.cox.net anywhere reject-with icmp-port-unreachable
REJECT all -- 97-68-247-134.biz.bhn.net anywhere reject-with icmp-port-unreachable
REJECT all -- 241.72.9.96.sinet.com.kh anywhere reject-with icmp-port-unreachable
REJECT all -- 154.66.9.96.sinet.com.kh anywhere reject-with icmp-port-unreachable
REJECT all -- 96-85-0-37-static.hfc.comcastbusiness.net anywhere reject-with icmp-port-unreachable
REJECT all -- 96-81-206-233-static.hfc.comcastbusiness.net anywhere reject-with icmp-port-unreachable
REJECT all -- 96-74-120-206-static.hfc.comcastbusiness.net anywhere reject-with icmp-port-unreachable
REJECT all -- rrcs-96-11-59-253.central.biz.rr.com anywhere reject-with icmp-port-unreachable
REJECT all -- ip-95-87-14-2.trakiacable.bg anywhere reject-with icmp-port-unreachable
REJECT all -- 95.86.57.82 anywhere reject-with icmp-port-unreachable
REJECT all -- broadband-95-84-198-24.ip.moscow.rt.ru anywhere reject-with icmp-port-unreachable
REJECT all -- broadband-95-84-158-53.ip.moscow.rt.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95x79x56x53.static-business.nn.ertelecom.ru anywhere reject-with icmp-port-unreachable
REJECT all -- dynamicip-95-78-232-102.pppoe.nsk.ertelecom.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95.71.125.50 anywhere reject-with icmp-port-unreachable
REJECT all -- 95-65-89-131.starnet.md anywhere reject-with icmp-port-unreachable
REJECT all -- mail.balkurs.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95.56.231.15 anywhere reject-with icmp-port-unreachable
REJECT all -- static.res.bb.9547219144.dslon.ws anywhere reject-with icmp-port-unreachable
REJECT all -- 95.46.96.145 anywhere reject-with icmp-port-unreachable
REJECT all -- 95-31-245-50.broadband.corbina.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95-28-156-18.broadband.corbina.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95-24-229-79.broadband.corbina.ru anywhere reject-with icmp-port-unreachable
REJECT all -- customer.optima-east.net anywhere reject-with icmp-port-unreachable
REJECT all -- 95.215.150.60 anywhere reject-with icmp-port-unreachable
REJECT all -- 95-181-46-162.goodline.info anywhere reject-with icmp-port-unreachable
REJECT all -- 95.167.105.2 anywhere reject-with icmp-port-unreachable
REJECT all -- u11960.kuzia.net.ua anywhere reject-with icmp-port-unreachable
REJECT all -- 95-161-231-10.obit.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95-161-215-62.obit.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95-161-189-18.obit.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95-161-152-108.obit.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 95.158.44.212.best.net.ua anywhere reject-with icmp-port-unreachable
REJECT all -- 95.158.44.199.best.net.ua anywhere reject-with icmp-port-unreachable
REJECT all -- 95.158.167.238 anywhere reject-with icmp-port-unreachable
REJECT all -- 95.156.92.190 anywhere reject-with icmp-port-unreachable
REJECT all -- 95.154.70.151 anywhere reject-with icmp-port-unreachable
REJECT all -- 95.154.69.93 anywhere reject-with icmp-port-unreachable
REJECT all -- 95-143-135-226.client.ltnet.cz anywhere reject-with icmp-port-unreachable
REJECT all -- 95-143-133-180.client.ltnet.cz anywhere reject-with icmp-port-unreachable
REJECT all -- 95.137.133.119 anywhere reject-with icmp-port-unreachable
REJECT all -- 95.105.89.151.static.slv.ufanet.ru anywhere reject-with icmp-port-unreachable
REJECT all -- pool-94.24.233-74.is74.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 106.153.230.94.awnet.cz anywhere reject-with icmp-port-unreachable
REJECT all -- 249.399.bras-01.dianet.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 94-21-118-140.pool.digikabel.hu anywhere reject-with icmp-port-unreachable
REJECT all -- 94.204.189.41 anywhere reject-with icmp-port-unreachable
REJECT all -- 94.187.29.34 anywhere reject-with icmp-port-unreachable
REJECT all -- dynamicip-94-181-58-45.pppoe.chel.ertelecom.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 94x180x244x98.static-business.kzn.ertelecom.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 94x180x118x195.static-customer.nsk.ertelecom.ru anywhere reject-with icmp-port-unreachable
REJECT all -- 94.159.45.234 anywhere reject-with icmp-port-unreachable
REJECT all -- 94.154.73.63 anywhere reject-with icmp-port-unreachable
REJECT all -- 94.143.43.230 anywhere reject-with icmp-port-unreachable
REJECT all -- 94.141.245.232 anywhere reject-with icmp-port-unreachable

 

How Stop Fail2Ban

root@debian:~#service fail2ban stop
root@debian:~#ps -ef |grep fail2ban |awk '{print $2}'|xargs kill -9

 

How Start Fail2Ban

root@debian:~#iptables -F
root@debian:~#iptables -X
root@debian:~#iptables -t nat -F
root@debian:~#iptables -t nat -X
root@debian:~#iptables -t mangle -F
root@debian:~#iptables -t mangle -X
root@debian:~#iptables -P INPUT ACCEPT
root@debian:~#iptables -P FORWARD ACCEPT
root@debian:~#iptables -P OUTPUT ACCEPT

root@debian:~#service fail2ban start

Increase the debugging to help figure out why fail2ban isn't blocking anything when your regexs work with your configured log file.

root@debian:~#fail2ban-client set loglevel DEBUG

Joomla

root@debian:~#cat <<EOF> /etc/fail2ban/jail.d/joomla-login-errors.conf
[joomla-login-errors]
enabled = true
filter = joomla-login-errors
port = http,https
logpath = /home/itstorage/public_html/logs/error.php
/var/log/virtualmin/*access_log
/var/log/virtualmin/*error_log
backend = polling
maxretry = 6
bantime = 1200
EOF
root@debian:~#cat <<EOF> /etc/fail2ban/filter.d/joomla-login-errors.conf
[Definition]
failregex = ^.*INFO <HOST>.*joomlafailure.*(gmailfailure|gmailfailure|Username).*
root@debian:~#fail2ban-regex /home/yoursite/public_html/logs/error.php /etc/fail2ban/filter.d/joomla-login-errors.conf 

Running tests
=============

Use failregex filter file : joomla-login-errors, basedir: /etc/fail2ban
Use log file : /home/yoursite/public_html/logs/error.php
Use encoding : UTF-8


Results
=======

Failregex: 26 total
|- #) [# of hits] regular expression
| 1) [26] ^.*INFO <HOST>.*joomlafailure.*(gmailfailure|gmailfailure|Username).*
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
| [1159] Year-Month-Day[T ]24hour:Minute:Second(?:\.Microseconds)?(?:Zone offset)?
`-

Lines: 1159 lines, 0 ignored, 26 matched, 1133 missed
[processed in 0.40 sec]

Missed line(s): too many to print. Use --print-all-missed to print all 1133 lines

Wordpress

Using Fail2ban on wordpress wp-login.php and xmlrpc.php
root@debian:~#cat <<EOF> /etc/fail2ban/jail.d/wordpress-login-errors.conf
[wordpress]
enabled = true
port = http,https
filter = wordpress-login-errors
action = iptables-multiport[name=wordpress, port="http,https", protocol=tcp]
logpath = /var/log/httpd/access_log
/var/log/apache2/access*log
/var/log/virtualmin/*log
maxretry = 10
findtime = 600
EOF
root@debian:~#cat <<EOF> /etc/fail2ban/filter.d/wordpress-login-errors.conf
[Definition]
failregex = ^<HOST> .* "POST .*wp-login.php
^<HOST> .* "POST .*xmlrpc.php
ignoreregex =
root@debian:~#fail2ban-regex /var/log/virtualmin/access_log /etc/fail2ban/filter.d/wordpress-login-errors.conf 

Running tests
=============

Use failregex filter file : wordpress-login-errors, basedir: /etc/fail2ban
Use log file : /var/log/virtualmin/access_log
Use encoding : UTF-8


Results
=======

Failregex: 88 total
|- #) [# of hits] regular expression
| 1) [2] ^<HOST> .* "POST .*wp-login.php
| 2) [86] ^<HOST> .* "POST .*xmlrpc.php
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
| [93391] Day(?P<_sep>[-/])MON(?P=_sep)Year[ :]?24hour:Minute:Second(?:\.Microseconds)?(?: Zone offset)?
`-

Lines: 93391 lines, 0 ignored, 88 matched, 93303 missed
[processed in 20.41 sec]

Missed line(s): too many to print. Use --print-all-missed to print all 93303 lines

 

مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

11-How to Protect DDoS Attacks on Linux Services by Fail2Ban P3- Linux Hardening

 

9 Harden PHP

9.1 Change the allow_url_fopen line to: allow_url_fopen = Off, to disable downloads via PHP
root@deb:~#find /etc/php -type f -name php.ini
/etc/php/7.0/cgi/php.ini
/etc/php/7.0/cli/php.ini
/etc/php/7.0/apache2/php.ini
/etc/php/7.0/fpm/php.ini
root@deb:~#cat /etc/php/7.0/apache2/php.ini |grep  allow_url_fopen 
allow_url_fopen = On
root@deb:~#find ./ -type f -name php.ini -exec sed -i 's/allow_url_fopen\ \= \On/allow_url_fopen\ \= \Off/gI' {} \;
root@deb:~#cat /etc/php/7.0/apache2/php.ini |grep  allow_url_fopen 
allow_url_fopen = Off
9.2 Turn off PHP information exposure
root@deb:~#find /etc/php -type f -name php.ini
/etc/php/7.0/cgi/php.ini
/etc/php/7.0/cli/php.ini
/etc/php/7.0/apache2/php.ini
/etc/php/7.0/fpm/php.ini
root@deb:~#cat /etc/php/7.0/apache2/php.ini |grep  expose_php 
expose_php = On
root@deb:~#find ./ -type f -name php.ini -exec sed -i 's/expose_php\ \= \On/expose_php\ \= \Off/gI' {} \;
root@deb:~#cat /etc/php/7.0/apache2/php.ini |grep  expose_php 
expose_php = Off
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

12-Linux Hardening - Lynis System and security auditing tool

Install Lynis System and security auditing tool

Provide security professionals (up to the CISO) with powerful tools to measure their security efforts.

RHEL / CentOS

Ensure that cURL, NSS, openssl, and CA certificates are up-to-date.

Create /etc/yum.repos.d/cisofy-lynis.repo

root@rhel:~#cat << EOF > /etc/yum.repos.d/cisofy-lynis.repo

[lynis]
name=CISOfy Software - Lynis package
baseurl=https://packages.cisofy.com/community/lynis/rpm/
enabled=1
gpgkey=https://packages.cisofy.com/keys/cisofy-software-rpms-public.key
gpgcheck=1
priority=2
EOF
root@rhel:~#sudo yum makecache fast
root@rhel:~#yum install lynis
Debian / Ubuntu

Download the key from a central keyserver:

root@deb:~#sudo wget -O - https://packages.cisofy.com/keys/cisofy-software-public.key | sudo apt-key add -

The software repository uses preferably HTTPS for secure transport. Install the 'https' method for APT, if it was not available yet.

root@deb:~#sudo apt install apt-transport-https

Using your software in English? Then configure APT to skip downloading translations. This saves bandwidth and prevents additional load on the repository servers.

root@deb:~#echo 'Acquire::Languages "none";' | sudo tee /etc/apt/apt.conf.d/99disable-translations

Next step is adding the repository:

root@deb:~#echo "deb https://packages.cisofy.com/community/lynis/deb/ stable main" | sudo tee /etc/apt/sources.list.d/cisofy-lynis.list

Install Lynis

Refresh the local package database with the new repository data and install Lynis:

root@deb:~#apt update
root@deb:~#apt install lynis
Run lynis

Now you start using Lynis. First time users are advised to use the Get Started guide.

root@deb:~#lynis audit system
root@rhel:~#lynis audit system
crontab for  lynis
root@deb:~#crontab -l
0 4 * * * /usr/sbin/lynis --quick --cronjob 2>&1 | mail -s "lynis output of $(hostname -f)" این آدرس ایمیل توسط spambots حفاظت می شود. برای دیدن شما نیاز به جاوا اسکریپت دارید
root@rhel:~#crontab -l
0 4 * * * /bin/lynis --quick --cronjob 2>&1 | mail -s "lynis output of $(hostname -f)" این آدرس ایمیل توسط spambots حفاظت می شود. برای دیدن شما نیاز به جاوا اسکریپت دارید
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

 

Apache2 Permission denied - AH00035: access to / denied / apache2 Error permission

 

In this scenario we use virtaulmin and apache in suexec mode and when rename a user we get follwing error

1-Apache2 Permission denied - AH00035: access to / denied / apache2 Error permission

2-Permission denied because search permissions are missing on a component of the path, after chmod and chgrp

Check Logs

Check  suexec.log
CentOS7x@itstorage:~ $ sudo tailf /var/log/apache2/suexec.log
[2018-06-04 16:45:52]: target uid/gid (1011/1011) mismatch with directory (1012/1012) or program (1011/1012)
[2018-06-04 16:45:53]: uid: (1011/mbctux) gid: (1011/mbctux) cmd: php7.0.fcgi

Rename user and group in Linux

Current User name: peter

New Username: mbctux

Check  user status
CentOS7x@itstorage:~ $ id peter
uid=1011(peter) gid=1011(peter) groups=1011(peter)
CentOS7x@itstorage:~ $ grep ^mbctux /etc/passwd
peter:x:1011:1011:peter:/home/peter:/bin/false
Rename User and group

usermod -l new_username -m -d /new/home/dir old_username

CentOS7x@itstorage:~ $ sudo usermod -l mbctux -m -d /home/mbctux peter
CentOS7x@itstorage:~ $ sudo groupmod -n mbctux peter
CentOS7x@itstorage:~ $ id mbctux
uid=1012(mbctux) gid=1012(mbctux) groups=1012(mbctux)

IF SELinux is enabled

Configuring SELinux Policies for Apache2 and joomla

Change Permissions

Change Discretionary Access Control (DAC) Permissions
CentOS7x@itstorage:~ $sudo chown mbctux:mbctux /home/mbctux/ -R
CentOS7x@itstorage:~ $ sudo find /home/mbctux/public_html/ -type d -exec chmod 755 {} \;
CentOS7x@itstorage:~ $ sudo find /home/mbctux/public_html/ -type f -exec chmod 644 {} \;
Change Access Control Lists (ACL) Permissions
CentOS7x@itstorage:~ $ sudo find /home/mbctux -type f -exec sudo setfacl -m g:mbctux:rx {} \;
CentOS7x@itstorage:~ $ sudo find /home/mbctux -type d -exec sudo setfacl -m g:mbctux:rx {} \;

Change Apache Virtual Host Config

RHEL/CentOS
CentOS7x@itstorage:~ $cat /etc/httpd/conf.d/mbctux.com.conf 
<VirtualHost *:80>
SuexecUserGroup "#1012" "#1012"
ServerName  www.mbctux.com
ServerAlias mbctux.com
CentOS7x@itstorage:~ $ sudo systemctl restart httpd.service
Debian
CentOS7x@itstorage:~ $ cat /etc/apache2/sites-enabled/mbctux.com.conf 
<VirtualHost *:80>
SuexecUserGroup "#1012" "#1012"
ServerName  www.mbctux.com
ServerAlias mbctux.com
debian9x@itstorage:~ $sudo systemctl restart php5-fpm.service php7.0-fpm.service apache2.service
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

Centralized Linux User Management and Authentication with FreeIPA

What is FreeIPA?

FreeIPA is an integrated security information management solution combining Linux (Fedora), 389 Directory Server, MIT Kerberos, NTP, DNS, Dogtag (Certificate System). It consists of a web interface and command-line administration tools.
FreeIPA is an integrated Identity and Authentication solution for Linux/UNIX networked environments. A FreeIPA server provides centralized authentication, authorization and account information by storing data about user, groups, hosts and other objects necessary to manage the security aspects of a network of computers.
Multiple FreeIPA servers can easily be configured in a FreeIPA Domain in order to provide redundancy and scalability. The 389 Directory Server is the main data store and provides a full multi-master LDAPv3 directory infrastructure. Single-Sign-on authentication is provided via the MIT KerberosKDC. Authentication capabilities are augmented by an integrated Certificate Authority based on the Dogtag project. Optionally Domain Namescan be managed using the integrated ISC Bind server.
Security aspects related to access controldelegation of administration tasks and other network administration tasks can be fully centralized and managed via the Web UI or the ipa Command Line tool.

Resources

  • Roadmap: You may view FreeIPA's current roadmap for future features here.
  • Most of our activity happens on the freeipa-devel and freeipa-user mailing lists as well as on the #freeipa IRC channel on the irc.freenode.net.

References

FreeIPA takes advantage of different technologies:

  • MIT KDC - core of the FreeIPA's authentication.
  • 389 Directory Server - back end where FreeIPA keeps all data.
  • Dogtag Certificate System - FreeIPA includes CA & RA for certificate management functions.
  • SSSD - client side component that integrates FreeIPA as a authentication and identity provider in a better way than traditional NSS & PAM.

General FAQ

What's Available in FreeIPA Now? What's in the Pipeline?

FreeIPA (so far) is an integrated solution combining

  • Linux (currently Fedora or Red Hat Enterprise Linux)
  • 389 Directory Server
  • MIT Kerberos
  • NTP
  • DNS
  • Web and command line provisioning and administration tools
  • Dogtag Certificate System
  • Active Directory Integration
  • Integration with Weblogic server
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

Check Apache2 log

Install Needed pkgs

RHEL / CentOS
CentOS@itstorage:~ $ sudo yum install --enablerepo=epel apachetop lnav
Debian / Ubuntu
deb@itstorage:~ $ sudo apt-get install lnav apachetop

Check Apache2 Logs

apachetop - display real-time web server statistics
CentOS7x@itstorage:~ $ sudo apachetop -f /home/itstorage/logs/access_log
lnav - ncurses-based log file viewer
CentOS7x@itstorage:~ $ sudo lnav /home/itstorage/logs/access_log
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط

Configuring SELinux Policies for Apache2 and joomla

Security-Enhanced Linux is a Linux kernel security module that provides a mechanism for supporting access control security policies, including United States Department of Defense–style mandatory access controls. Wikipedia
Developed by: Red Hat
Stable release: 2.5 / 23 February 2016
Written in: C
Initial release: January 1, 1998
License: GNU GPL
Original authors: National Security AgencyRed Hat

Check All Directories

Check root of mbctux host
CentOS7x@itstorage:~ $ sudo ls /home/mbctux
awstats  etc       ftp    logs     public_html    ssl.cert      ssl.everything  tmp
cgi-bin  fcgi-bin  homes  Maildir  ssl.ca     ssl.combined  ssl.key         virtualmin-backup
Check www of mbctux host
CentOS7x@itstorage:~ $ sudo ls /home/mbctux/public_html
images         layouts     phpinfo      robots.txt.dist
administrator  components             includes   libraries    tmp  
awstats-icon   configuration.php        index.php  LICENSE.txt       
awstatsicons   logs     suexec.cgi bin        templates
cache          icon       language     modules    robots.txt  
Check CGI and FCGI
CentOS7x@itstorage:~ $ sudo ls /home/mbctux/fcgi-bin -la
total 16
drwxr-xr-x+  2 mbctux mbctux 4096 Jun  4 16:25 .
drwxr-x---+ 13 mbctux mbctux 4096 Jun  5 14:40 ..
-rwxr-xr-x+  1 mbctux mbctux  219 Jun  4 16:25 php5.fcgi
-rwxr-xr-x+  1 mbctux mbctux  167 Jun  4 16:25 php7.0.fcgi
CentOS7x@itstorage:~ $ sudo ls /home/mbctux/cgi-bin -la
total 20
drwxr-x---+  2 mbctux mbctux 4096 Jun  4 16:19 .
drwxr-x---+ 13 mbctux mbctux 4096 Jun  5 14:40 ..
-rwxr-xr-x+  1 mbctux mbctux   43 Jun  4 12:35 awstats.pl
lrwxrwxrwx   1 mbctux mbctux   23 Jun  4 12:35 lang -> /usr/share/awstats/lang
lrwxrwxrwx   1 mbctux mbctux   22 Jun  4 12:35 lib -> /usr/share/awstats/lib
-rwxr-xr-x+  1 mbctux mbctux  234 Jun  4 16:19 php5.cgi
-rwxr-xr-x+  1 mbctux mbctux  182 Jun  4 16:19 php7.0.cgi
lrwxrwxrwx   1 mbctux mbctux   26 Jun  4 12:35 plugins -> /usr/share/awstats/plugins

The SELinux is enabled

Install needed pkgs
CentOS7x@itstorage:~ $ sudo yum install -y policycoreutils-python setroubleshooting
Apache Context Types
httpd_sys_content_t     Read-only directories and files used by Apache
httpd_sys_rw_content_t  Readable and writable directories and files used by Apache. Assign this to directories where files can be created or modified by your application, or assign it to files directory to allow your application to modify them.
httpd_log_t     Used by Apache to generate and append to web application log files.
httpd_cache_t     Assign to a directory used by Apache for caching, if you are using mod_cache.

Create the Policies

httpd_sys_content_t context

Create a policy to assign the httpd_sys_content_t context to the /home/user directory, and all child directories and files.

CentOS7x@itstorage:~ $ sudo setsebool -P httpd_enable_homedirs 1 ; sudo setsebool -P httpd_enable_cgi 1
CentOS7x@itstorage:~ $ sudo chcon -R -t httpd_sys_content_t  "/home(/.*)?"
httpd_sys_script_exec_t context
CentOS7x@itstorage:~ $ sudo chcon -t httpd_sys_script_exec_t /home/mbctux/cgi-bin/php5.cgi
CentOS7x@itstorage:~ $ sudo chcon -t httpd_sys_script_exec_t /home/mbctux/cgi-bin/php7.0.cgi
CentOS7x@itstorage:~ $ sudo chcon -t httpd_sys_script_exec_t /home/mbctux/fcgi-bin/php5.fcgi
CentOS7x@itstorage:~ $ sudo chcon -t httpd_sys_script_exec_t /home/mbctux/fcgi-bin/php7.0.fcgi
httpd_log_t context

Create a policy to assign the httpd_log_t context to the logging directories.

CentOS7x@itstorage:~ $ sudo semanage fcontext -a -t httpd_log_t "/home/mbctux/logs(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a -t httpd_log_t "/home/mbctux/public_html/logs(/.*)?"
httpd_cache_t context

Create a policy to assign the httpd_cache_t context to our cache directories.

CentOS7x@itstorage:~ $ sudo semanage fcontext -a -t httpd_cache_t "/home/mbctux/public_html/cache(/.*)?"
Allowing ReadWrite Access httpd_sys_rw_content_t context

Create a policy to assign the httpd_sys_rw_content_t context to the tmp directory, all child files and joomla configuration files.

CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/tmp(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/home(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/awast(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/Maildir(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/virtualmin-backup(/.*)?"
CentOS7x@itstorage:~ $sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/public_html/tmp(/.*)?"
CentOS7x@itstorage:~ $sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/public_html/images(/.*)?"
CentOS7x@itstorage:~ $sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/public_html/templates(/.*)?"
CentOS7x@itstorage:~ $sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/public_html/administrator(/.*)?"
CentOS7x@itstorage:~ $ sudo semanage fcontext -a httpd_sys_rw_content_t "/home/mbctux/public_html/configuration.php"

Applying the SELinux Policy

CentOS7x@itstorage:~ $ sudo restorecon -Rv /home

Check Booleans

CentOS7x@itstorage:~ $ sudo getsebool -a | grep httpd  
allow_httpd_anon_write --> off  
allow_httpd_bugzilla_script_anon_write --> off  
allow_httpd_cvs_script_anon_write --> off  
allow_httpd_mod_auth_pam --> off  
allow_httpd_nagios_script_anon_write --> off  
allow_httpd_prewikka_script_anon_write --> off  
allow_httpd_squid_script_anon_write --> off  
allow_httpd_sys_script_anon_write --> off  
httpd_builtin_scripting --> on  
httpd_can_network_connect --> off  
httpd_can_network_connect_db --> off  
httpd_can_network_relay --> off  
httpd_can_sendmail --> on  
httpd_disable_trans --> off  
httpd_enable_cgi --> on  
httpd_enable_ftp_server --> off  
httpd_enable_homedirs --> on  
httpd_execmem --> off  
httpd_read_user_content --> off  
httpd_rotatelogs_disable_trans --> off  
httpd_setrlimit --> off  
httpd_ssi_exec --> off  
httpd_suexec_disable_trans --> off  
httpd_tty_comm --> on  
httpd_unified --> on  
httpd_use_cifs --> off  
httpd_use_nfs --> off

Change Permissions

Change Discretionary Access Control (DAC) Permissions
CentOS7x@itstorage:~ $sudo chown mbctux:mbctux /home/mbctux/ -R
CentOS7x@itstorage:~ $ sudo find /home/mbctux/public_html/ -type d -exec chmod 755 {} \;
CentOS7x@itstorage:~ $ sudo find /home/mbctux/public_html/ -type f -exec chmod 644 {} \;
Change Access Control Lists (ACL) Permissions
CentOS7x@itstorage:~ $ sudo find /home/mbctux -type f -exec sudo setfacl -m g:mbctux:rx {} \;
CentOS7x@itstorage:~ $ sudo find /home/mbctux -type d -exec sudo setfacl -m g:mbctux:rx {} \;
Change Attribute set "immutable" flag
CentOS7x@itstorage:~ $ sudo chattr +i /home/mbctux/cgi-bin/php5.cgi
CentOS7x@itstorage:~ $ sudo chattr +i /home/mbctux/cgi-bin/php7.0.cgi
CentOS7x@itstorage:~ $ sudo chattr +i /home/mbctux/fcgi-bin/php5.fcgi
CentOS7x@itstorage:~ $ sudo chattr +i /home/mbctux/fcgi-bin/php7.0.fcgi

Change Apache Virtual Host Config

CentOS7x@itstorage:~ $ cat /etc/httpd/conf.d/mbctux.com.conf 
<VirtualHost *:80>
SuexecUserGroup "#1012" "#1012"
ServerName  www.mbctux.com
ServerAlias mbctux.com
CentOS7x@itstorage:~ $ sudo systemctl restart httpd.service
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
مطالب و دوره های آموزشی مرتبط
1 2 3 4