Sunteți pe pagina 1din 60

centos 6.8 NOTES RHEL6.

8 NOTES
###########################
### RHEL/CentOS install ###
###########################
### Link for netinstall ##
http://ftp.astral.ro/distros/centos/6.8/os/x86_64/
###########
### yum ###
###########
yum update
# update toate pachetele si dependintele lor
yum search nume_pachet # cauta un anume pachet, pot fi mai multe pachete trecute
yum info nume_pachet # afiseaza detalii despre un anume pachet
yum list nume_pache
# afiseaza informatii despre un anumit pachet, instalat sau nu
yum list nume_pachet\* # afiseaza informatii despre toate pachetele care incep cu un nume
yum list all
# afiseaza toate pachetele disponibile
yum list installed *nume_pachet* # afiseaza pachetele instalate care contine un nume
yum list installed | grep reponame # afiseaza pachetele instalate dintr-un repo
yum list available # afiseaza pachetele disponibile in functie de repo-urile instalate
yum repolist
# afiseaza repo-urile instalate
yum gruplist
# afiseaza
yum install nume_pachet\* # instaleaza toate pachetele care incep cu un nume
yum downgrade nume_pachet
yum provides */nume_pachet # afiseaza fisierele care le detine un pachet
yum -v grouplist kde\* # listeaza toate pachetele ce tin de KDE
yum groupinstall KDE Software Compilation # instaleaza toate pachetele ce tin de KDE
yum groupinstall kde-desktop
yum install @kde-desktop # @ pentru a instala un grup
yum remove nume_pachet
yum groupremove KDE Software Compilation
yum groupremove kde-desktop
yum remove @kde-desktop
yum history list
yum history list nume_pachet
yum repolist all # list all repositories set up on your system
yum exclude=packagename\*
################
### yum.conf ###
################

### skip updating packages ###


yum -x nume_pachet update
yum exclude=nume_pachet update
sudo vim /etc/yum.conf # permanent
_______
[main]
exclude=nume_pachet1* nume_pachet2*
_______
yum disableexcludes=all update # disable exclude to check for an update
### Remove Old Kernels ###
# Package-cleanup set count as how many old kernels you want left #
package-cleanup oldkernels count=2
# Make Amount of Installed Kernels Permanent #
vim /etc/yum.conf # and set installonly_limit:
installonly_limit=2
### Removing dependencies ###
sudo vim /etc/yum.conf
______________________________
[main]
clean_requirements_on_remove=1
______________________________
###########
### RPM ###
###########
rpm -ivh package-2.7.9-5.el6.2.i686.rpm # Install an RPM Package
-i : install a package
-v : verbose for a nicer display
-h: print hash marks as the package archive is unpacked
rpm -qpR package-5.2.2-1.noarch.rpm # check dependencies of RPM Package before Installing
-q : Query a package
-p : List capabilities this package provides.
-R: List capabilities on which this package depends..
rpm -ivh nodeps package-5.2.2-1.noarch.rpm # Install a RPM Package Without Dependencies
nodeps (Do not check dependencies)
rpm -q package # check an Installed RPM Package
rpm -ql package # List all files of an installed RPM package

rpm -qa last # List Recently Installed RPM Packages


rpm -qa
# List All Installed RPM Packages
rpm -Uvh package-3.5.0-2.el6.centos.i686.rpm # Upgrade a RPM Package
rpm -evv package # Remove a RPM Package
rpm -ev nodeps package # Remove an RPM Package Without Dependencies
-e (erase)
rpm -qi package # Query a Information of Installed RPM Package
-qi (query info)
rpm -qf /usr/bin/package # Query a file that belongs which RPM Package
-qf (query file)
rpm -qip package-1.3.3-1.noarch.rpm # Information of RPM Package Before Installing
-qip (query info package)
rpm -qdf /usr/bin/vmstat # Query documentation of Installed RPM Package
-qdf (query document file)
rpm -Vp package-1.3.3-1.noarch.rpm # Verify a RPM Package
-Vp (verify package)
rpm -Va # Verify all RPM Packages
rpm -qa gpg-pubkey* # List all Imported RPM GPG keys
######################
### YUM & RPM tips ###
######################
#Query packages not from CentOS #
rpm -qa qf %{NAME} %{VENDOR}\n | grep -v CentOS
# Reset File Permissions #
rpm setperms <packagename>
# View the Changelog of a package #
rpm -q changelog <packagename> | less
# quickly list documentation relating to a package #
rpm -qd <packagename>
# Query Package Install Order and Dates #
rpm -qa last > ~/RPMS_by_Install_Date

# Query Available Packages from a Repo #


yum disablerepo * enablerepo rpmforge list available
# Enable or Disable a Repo from the Command Line #
yum-config-manager enable c6-media
yum-config-manager disable c6-media
# Show all installed GPG keys #
rpm -q gpg-pubkey qf %{name}-%{version}-%{release} > %{summary}\n
### package-cleanup ###
package-cleanup orphans
package-cleanup leaves
package-cleanup dupes
package-cleanup problems
package-cleanup oldkernel
### Fonts config ###
vim ~/.fonts.conf
__________________________________________
<?xml version=1.0?>
<!DOCTYPE fontconfig SYSTEM fonts.dtd>
<fontconfig>
<match target=font>
<edit mode=assign name=rgba>
<const>rgb</const>
</edit>
</match>
<match target=font>
<edit mode=assign name=hinting>
<bool>true</bool>
</edit>
</match>
<match target=font>
<edit mode=assign name=hintstyle>
<const>hintslight</const>
</edit>
</match>
<match target=font>
<edit mode=assign name=antialias>
<bool>true</bool>
</edit>
</match>
<match target=font>
<edit mode=assign name=lcdfilter>
<const>lcddefault</const>
4

</edit>
</match>
</fontconfig>
__________________________________________
### Add an user to SUDOERS ###
su
visudo
sergiu
ALL=(ALL) ALL
Or add the user to wheel group and enable wheel from visudo
#############
### Repos ###
#############
rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
# Multimedia #
rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
rpm -Uvh http://li.nux.ro/download/nux/dextop/el6/x86_64/nux-dextop-release-02.el6.nux.noarch.rpm
sudo wget http://li.nux.ro/download/nux/misc/nux-misc.repo -P /etc/yum.repos.d/
sudo yum enablerepo=nux-dextop-testing install xbmc
# nVidia driver #
rpm -Uvh http://elrepo.org/elrepo-release-6-5.el6.elrepo.noarch.rpm
http://elrepo.org/linux/extras/el6/x86_64/RPMS/ # extras
http://elrepo.org/linux/testing/el6/x86_64/RPMS/ # testing
sudo yum install kmod-nvidia
sudo yum install nvidia-x11-drv
# Last kernel & lts kernel #
http://elrepo.org/linux/kernel/el6/x86_64/RPMS/ # kernel
sudo yum remove kernel-headers kernel-firmware
sudo yum enablerepo=elrepo-kernel install kernel-ml kernel-ml-devel kernel-ml-headers
kernel-ml-firmware # for last kernel
sudo yum enablerepo=elrepo-kernel install kernel-lt kernel-lt-devel kernel-lt-headers kernel-ltfirmware # for lts kernel
# Others #
rpm -Uvh http://download1.rpmfusion.org/free/el/updates/6/x86_64/rpmfusion-free-release-60.1.noarch.rpm http://download1.rpmfusion.org/nonfree/el/updates/6/x86_64/rpmfusion-nonfreerelease-6-0.1.noarch.rpm # (not needed if nux-dextop is installed)

### Install Google Chrome ###


wget http://chrome.richardlloyd.org.uk/install_chrome.sh
chmod u+x install_chrome.sh
./install_chrome.sh
sudo grep chrome /var/log/audit/audit.log | audit2allow -M mypol
sudo semodule -i mypol.pp
### Install Chromium ###
cd /etc/yum.repos.d
wget http://people.centos.org/hughesjr/chromium/6/chromium-el6.repo
yum install chromium
sudo setsebool -P mmap_low_allowed 1
### Install lastest Firefox ###
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
yum enablerepo=remi install firefox
### Others ###
yum install bash-completion
yum install nautilus-open-terminal
yum install flash-plugin
yum install gconf-editor
yum install gnome-utils
yum install file-roller
yum install ntfsprogs
### Apps ###
yum install pidgin pidgin-plugin-pack skype
yum install geany filezilla transmission mc
yum install radiotray tv-maxe xbmc clementine
### xscrennsaver ###
yum remove gnome-screensaver
yum install xscreensaver
xscreensaver -nosplash # open Startup Applications and add Xscreensaver to startup
### Change the hostname ###
hostname # to check your hostname
sudo hostname RedHat
vim /etc/sysconfig/network
### Dropbox ###
vim /etc/sysconfig/dropbox # DROPBOX_USERS=sergiu
echo -b /usr/libexec/dropbox/ > /etc/prelink.conf.d/dropbox.conf
yum enablerepo rpmforge reinstall dropbox

### Install LibreOffice 4.1.2 ###


wget
http://download.documentfoundation.org/libreoffice/stable/4.1.2/rpm/x86_64/LibreOffice_4.1.2_
Linux_x86-64_rpm.tar.gz
tar -xvf LibreOffice_4.1.2*
cd LibreOffice_4.1.2*
yum localinstall RPMS/*.rpm RPMS/desktop-integration/libreoffice4.1-freedesktop-menus4.1.2*.noarch.rpm
### Install vbox additions ###
yum install gcc kernel-devel kernel-headers dkms make bzip2
KERN_DIR=/usr/src/kernels/`uname -r`
export KERN_DIR
cd /media/VirtualBoxGuestAdditions
./VBoxLinuxAdditions.run
### Remove boot splash screen ###
vim /etc/grub.conf # remove rhgb and quiet
### Remove Desktop icons ###
yum install gconf-editor
apps > nautilus > desktop
### Multimedia support ###
sudo yum install gstreamer gstreamer-plugins-base gstreamer-plugins-good gstreamer-pluginsbad-free
sudo yum install gstreamer-plugins-bad gstreamer-plugins-ugly gstreamer-ffmpeg
### Save alsamixer settings ###
sudo alsactl store
ls -Z /etc/asound.* # to see SElinux label
sudo vim /etc/pulse/daemon.conf
_______________________________
enable-remixing = yes
enable-lfe-remixing = yes
default-sample-format = s32le
default-sample-rate = 48000
default-sample-channels = 6
default-fragments = 8
default-fragment-size-msec = 5
________________________________
pulseaudio -k # restart pulseaudio

### Disable window move with alt + left mouse button ###
# conf-editor
# /apps/metacity/general
# mouse_button_modifier option change <Alt> to <Super>
####################################
### CentOS Protection & Security ###
####################################
# Securing and Hardening Red Hat Linux Production Systems
http://www.puschitz.com/SecuringLinux.shtml
https://access.redhat.com/site/documentation/enUS/Red_Hat_Enterprise_Linux/6/html/Security_Guide/index.html
### SElinux ###
Two important documentations about Selinux can be found here:
http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/SecurityEnhanced_Linux/index.html
http://docs.redhat.com/docs/enUS/Red_Hat_Enterprise_Linux/6/html/Managing_Confined_Services/index.html
# You can view current status of SELinux mode from the command line using these:
system-config-selinux
getenforce # if you get back a 1 selinux is turned on if you get back a 0 its turned off
sestatus
# If it is disabled, enable SELinux using the following command.
setenforce enforcing # changes do not persist through a system reboot
To make changes persistent through a system reboot, edit the SELINUX= line in
/etc/selinux/config for either enforcing, permissive, or disabled. For example:
SELINUX=permissive
# SElinux logs (/var/log/audit/audit.log) #
yum install setroubleshoot
setroubleshootd
sealert -a /var/log/audit/audit.log # if you only have a console available and no X-Window
System
sealert -b # if you have gui
# SElinux re-labelling #
touch /.autorelabel
sudo reboot
### Password Protect Grub and Single-User Mode ###
# It is highly important to protect your bootloader.
# There is a magic kernel parameter called init=/bin/sh. This makes any user/login restrictions
totally useless. Then mount -o remount,rw /
8

grub-crypt
vim /etc/grub.conf
______________________________________________
default=0
timeout=2
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
password encrypted $6$w1lrwrXOMm5ueR4M$..
______________________________________________
vim /etc/sysconfig/init
_______________________
PROMPT=no
SINGLE=/sbin/sulogin
_______________________
### Modifying fstab ###
vim /etc/fstab
____________________________________________________________________
/dev/sda1 /boot ext4 defaults,nosuid,noexec,nodev 1 2
/dev/sda2 swap swap defaults
00
/dev/sda3 / ext4 defaults
11
/dev/sda4 /home ext4 defaults,nosuid,nodev
12
# Others partitions
/tmp ext4 defaults,nosuid,noexec,nodev 1 2
/var/tmp ext4 defaults,nosuid,noexec,nodev 1 2
/var ext4 defaults,nosuid
12
/var/www ext4 defaults,nosuid,nodev
12
/dev/shm tmpfs
defaults
00
devpts
/dev/pts devpts gid=5,mode=620
sysfs
/sys sysfs defaults
00
proc
/proc proc defaults
00

00

____________________________________________________________________
# Note that some packages (building nvidia-dkms for example) may require exec on /var
# Keep /boot as read-only #
# Note that you need to reset the change to read-write if you need to upgrade the kernel in future
/dev/sda1 /boot ext4 defaults,nosuid,noexec,nodev,ro 1 2
### Disable Control -Alt -Delete keys on the console mode ###
vim /etc/init/control-alt-delete.conf
______________________________
9

# start on control-alt-delete
# exec /sbin/shutdown -r now Control -Alt -Delete pressed
______________________________
### Umask restrictions ###
# Set a umask of 077 for maximum security, which makes new files not readable by users other
than the owner.
perl -npe s/umask\s+0\d2/umask 077/g -i /etc/bashrc
perl -npe s/umask\s+0\d2/umask 077/g -i /etc/csh.cshrc
### Find users with empty passwords ###
awk -F: ($2 == ) {print} /etc/shadow # Shouldnt see anything amiss here
awk -F: ($3 == 0) {print} /etc/passwd # Only the root user has uid 0. No other user should
ever have uid 0
### Disable USB mass storage ###
echo Disabling USB Mass Storage
echo blacklist usb-storage > /etc/modprobe.d/blacklist-usbstorage
### Disable USB stick to detect ###
vim /etc/modprobe.d/no-usb
_____________________________
install usb-storage /bin/true
_____________________________
### Narrowing rights ###
chmod 700 /root
# before 0550 dr-xr-x
chmod 700 /var/log/audit
# before 0750 drwxr-x
chmod 740 /etc/rc.d/init.d/iptables # before 0755 -rwxr-xr-x
chmod -R 700 /etc/skel
# before 0755 drwxr-xr-x
chmod 640 /etc/security/access.conf # before 0644 -rw-rr
chmod 600 /etc/sysctl.conf
# before 0644 -rw-rr
########################
### Network Security ###
########################
### Sysctl ###
vim /etc/sysctl.conf
_______________________________________________
### ipv4 Security options ###
# Disable IP Source Routing #
# Source Routing is used to specify a path or route through the network from source to
destination.
# This feature can be used by network people for diagnosing problems.
10

# However, if an intruder was able to send a source routed packet into the network, then he could
intercept the replies and your server might not know that its not communicating with a trusted
server.
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Disable ICMP Redirect Acceptance #
# ICMP redirects are used by routers to tell the server that there is a better path to other networks
than the one chosen by the server.
# However, an intruder could potentially use ICMP redirect packets to alter the hostss routing
table by causing traffic to use a path you didnt intend.
net.ipv4.conf.all.accept_redirects = 0
# Enable IP Spoofing Protection #
# IP spoofing is a technique where an intruder sends out packets which claim to be from another
host by manipulating the source address.
# IP spoofing is very often used for denial of service attacks.
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Enable Ignoring to ICMP Requests #
net.ipv4.icmp_echo_ignore_all = 1
# Enable Ignoring Broadcasts Request #
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable Bad Error Message Protection #
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Enable Logging of Spoofed Packets, Source Routed Packets, Redirect Packets #
net.ipv4.conf.all.log_martians = 1
# This help a little wtih SYN flood attacks. This suppliments a good firewall ruleset #
net.ipv4.tcp_syncookies = 1
# This is a server, not a router. Disable packet forwarding #
net.ipv4.ip_forward = 0
# Others ipv4 security options #
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.tcp_max_syn_backlog = 1280
net.ipv4.tcp_timestamps = 0
11

### ipv6 Security options ###


net.ipv6.conf.all.disable_ipv6 = 1
### Memory/Swap Use ###
vm.swappiness = 1
vm.vfs_cache_pressure = 50
_______________________________________________
sysctl -p
### IPTables ###
sudo vim /etc/sysconfig/iptables
____________________________________________________________________________
#Drop anything we arent explicitly allowing. All outbound traffic is okay
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp icmp-type echo-reply -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp icmp-type destination-unreachable -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp icmp-type time-exceeded -j ACCEPT
# Accept Pings
-A RH-Firewall-1-INPUT -p icmp icmp-type echo-request -j ACCEPT
# Log anything on eth0 claiming its from a local or non-routable network
# If youre using one of these local networks, remove it from the list below
-A INPUT -i eth0 -s 10.0.0.0/8 -j LOG log-prefix IP DROP SPOOF A:
-A INPUT -i eth0 -s 172.16.0.0/12 -j LOG log-prefix IP DROP SPOOF B:
-A INPUT -i eth0 -s 192.168.0.0/16 -j LOG log-prefix IP DROP SPOOF C:
-A INPUT -i eth0 -s 224.0.0.0/4 -j LOG log-prefix IP DROP MULTICAST D:
-A INPUT -i eth0 -s 240.0.0.0/5 -j LOG log-prefix IP DROP SPOOF E:
-A INPUT -i eth0 -d 127.0.0.0/8 -j LOG log-prefix IP DROP LOOPBACK:
# Accept any established connections
-A RH-Firewall-1-INPUT -m state state ESTABLISHED,RELATED -j ACCEPT
# Accept ssh traffic. Restrict this to known ips if possible.
#-A RH-Firewall-1-INPUT -m state state NEW -m tcp -p tcp dport 22 -j ACCEPT
#Log and drop everything else
-A RH-Firewall-1-INPUT -j LOG
-A RH-Firewall-1-INPUT -j DROP
COMMIT
______________________________________________________________________________

12

### Detecting Listening Network Ports ###


netstat -tulpn
### Services configuration ###
chkconfig list
# list all known services
chkconfig list | grep 3:on # list running services
chkconfig [service] on/off # turn on / off service
for i in atd blk-availability bluetooth mdmonitor lvm2-monitor iscsi iscsid nfslock rpcbind
rpcgssd rpcidmapd livesys livesys-late pcscd openct postfix fcoe ip6tables; do service $i stop;
chkconfig $i off; done
##############
### Others ###
##############
### Wake-on-lan ###
echo /usr/sbin/ethtool -s eth0 wol g >> /etc/rc.d/rc.local
or
vim /etc/sysconfig/network-scripts/ifcfg-eth0
_____________________
DEVICE=eth0
TYPE=EThernet
ONBOOT=yes
ETHTOOL_OPTS=wol g
______________________
chkconfig network on
Wake up the computer from internet
This involves enabling port forwarding of UDP port 9 to the destination computer in the routers
administration webpage.
To fully benefit from WOL you should configure a dynamic DNS service.
Just make sure to use your dynamic DNS provided address and the destination computers MAC.
### Wine & wine fonts ###
rpm -ev nodeps wine-tahoma-fonts.noarch
sudo setsebool -P wine_mmap_zero_ignore 1
sudo grep wine-preloader /var/log/audit/audit.log | audit2allow -M mypol
sudo semodule -i mypol.pp
wget http://files.polosatus.ru/winefontssmoothing_en.sh
bash winefontssmoothing_en.sh
# Wine bottles #
env WINEPREFIX=~/.wine/CounterStrike wine CounterStrike1.6.exe
13

### dd ###
# format a USB #
dd if=/dev/zero of=/dev/sdX
# see the progress of dd #
ps -A | grep dd
sudo kill -USR1 {nr of PID}
### mc ###
gnome-terminal geometry=23968 -e mc -S featured.ini
### GIT HUB ###
ssh-keygen -t rsa -C contact.sergiuniculescu@gmail.com
vim ~/.ssh/id_rsa.pub # copy key and paste it to github.com
git config global user.name Sergiu Niculescu
git config global user.email contact.sergiuniculescu@gmail.com
### Kernel compile ###
yum install gcc ncurses ncurses-devel
yum update
wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3
tar -jxvf linux-3*
cd linux-3*
make menuconfig # allows you to select the already running kernels configuration file (resides
in /boot/), and accepts the defaults for all options that were introduced between the old and the
new version of the kernel
make oldconfig # automatically finds the configuration file in /boot/ and asks you questions for
all the new configuration options
make
make modules_install install
### Find commands ###
find /home -iname name # Files Using Name and Ignoring Case
find / -type d -name directory_name # Find Directories Using Name
find / -perm /u=r # Find all Read Only files
find / -perm /a=x # Find all Executable files
find . -type f -perm 0777 -print # Find all the files whose permissions are 777
find / -type f -perm 0777 -print -exec chmod 644 {} \; # Find all 777 permission files and use
chmod command to set permissions to 644
find / -type d -perm 777 -print -exec chmod 755 {} \; # Find Directories with 777 Permissions
and Chmod to 755
find . -type f -name tecmint.txt -exec rm -f {} \; # To find a single file called tecmint.txt and
remove it
find . -type f -name *.mp3 -exec rm -f {} \;
# Find and remove Multiple File with
extension .mp3
find /tmp -type f -empty # To file all empty files under certain path
14

find /tmp -type d -empty # To file all empty directories under certain path
find /tmp -type f -name .* # File all Hidden Files
find / \( -perm -4000 -o -perm -2000 \) -print # Identify unwanted SUID and SGID Binaries
find / -path -prune -o -type f -perm +6000 -ls # Identify unwanted SUID and SGID Binaries
find /dir -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # Identify world writable files
find /dir -xdev \( -nouser -o -nogroup \) -print # Identify orphaned files and folders
### Netstat commands ###
netstat -a | more # Listing all the LISTENING Ports of TCP and UDP connections
netstat -at
# Listing only TCP (Transmission Control Protocol) port connections
netstat -au
# Listing only UDP (User Datagram Protocol ) port connections
netstat -l
# Listing all active listening ports connections
netstat -lt
# Listing all active listening TCP ports
netstat -lu
# Listing all active listening UDP ports
netstat -lx
# Listing all active UNIX listening ports
netstat -s
# Showing Statistics by Protocol
netstat -r
# Display Kernel IP routing table
### Change the MAC address of Network Interface ###
ifconfig eth0 hw ether AA:BB:CC:DD:EE:FF
### Mount an ISO Image ###
mount -t iso9660 -o loop /home/tecmint/Fedora-18-i386-DVD.iso /mnt/iso/
sudo umount /mnt/iso
### Mount a partition with read-write permission ###
mount -o remount,rw /
### Clone the boot partition ###
sudo dd if=/dev/sdb1 of=/dev/sdc1 bs=4096 conv=notrunc,noerror
dd if=/dev/sdb of=mbr.img bs=512 count=1
dd if=mbr.img of=/dev/sdc bs=446 count=1 # If you only want to restore the boot loader
dd if=mbr.img of=/dev/sdc bs=1 skip=446 count=64 # To restore only the partition table
### rsync ###
rsync -a progress rsync://ftp.astral.ro/distros/centos/6.8/os/x86_64/ /opt/mirror/centos
system-config-kickstart # A graphical interface for making kickstart files
#############
### Games ###
#############
### UrbanTerror ###
tar -xjvf UrbanTerror42.tar.gz
cd UrbanTerror42
15

chmod u+x UrTUpdater_Ded.x86_64 Quake3-UrT.x86_64


./UrTUpdater_Ded.x86_64
./Quake3-UrT.x86_64
June 24th, 2016 | Category: Centos | Leave a comment

Access authorization in Apache 2.4


In Apache 2.4 the authorization configuration setup has changed from previous versions. Satisfy,
Order, Deny and Allow have all been deprecated and replaced with new Require directives.
Below weve compiled some examples to guide you through the transition.
If you are upgrading a server using the legacy authorization directives you can make them
work quickly by enabling (it should be activated by default) mod_access_compat in
Apache:
sudo a2enmod access_compat

1. Apache Documentation
The documentation from Apache: Upgrading to 2.4 from 2.2 provides the following basic
examples. The old configuration settings are on the left, and the new ones for Apache 2.4 on the
right:
All requests are denied:
Order deny,allow Deny from allRequire all denied

All requests are allowed:


Order allow,deny Allow from allRequire all granted

Only hosts in the example.org domain are allowed access:


Order Deny,Allow Deny from all Allow from example.orgRequire host example.org

But this only scratches the surface of whats now available.

2. RequireAll and RequireAny


The most interesting new features are the RequireAll, RequireAny and RequireNone
authorization containers. They promise to be both more powerful and more human-readable than
the old syntax.

16

By default all Require directives are handled as though contained within a


<RequireAny>container directive. In other words, if any of the specified authorization
methods succeed, then authorization is granted.
Here is real world example where a website limits access by requiring a Basic Authentication
login for certain directories:
AuthType Basic AuthName "Password Protected" AuthUserFile
<path_to_your_htpasswd_file> SetEnvIf REQUEST_URI "^/(admin|secure)/"
PROTECTED Deny from all Satisfy any Allow from env=!PROTECTED Require validuserSetEnvIf REQUEST_URI "^/(admin|secure)/" PROTECTED <RequireAny>
<RequireAll> Require not env PROTECTED Require all granted </RequireAll>
<RequireAll> AuthType Basic AuthName "Password Protected" AuthUserFile
<path_to_your_htpasswd_file> Require valid-user </RequireAll> </RequireAny>

In both cases we set an environmental variable PROTECTED when the request is for a file in the
/admin/or /secure/ directories. The syntax for this part hasnt changed. If this variable is set,
then a password will be required for access.
While the old syntax works, its not immediately clear how it works. Basically to get access the
request has to meet (Satisfy) either the Allow or the Require directive.
In the new syntax this is more explicit. The request needs to pass at least one (RequireAny) of
the twoRequireAll container rulesets. The first container grants all users access to nonPROTECTED directories, while the second container requires a valid login.
You can keep nesting containers until all possible options are covered.
But seeing as the outer <RequireAny> is already implied, we should be able to remove it.
Actually we can remove quite a bit now that we know what were doing:
AuthType Basic AuthName "Password Protected" AuthUserFile
<path_to_your_htpasswd_file> SetEnvIf REQUEST_URI "^/(admin|secure)/"
PROTECTED <RequireAll> Require not env PROTECTED </RequireAll> Require validuser

Note that any Require not directives must always be enclosed in a RequireAll directive.
Otherwise you will see an alert logged:
[core:alert] ... negative Require directive has no effect in <RequireAny>
directive

See further down the page a version of this example that does away with the ENV variable
entirely by using an expr condition.

3. Require authorization providers


17

The Require directive comes with a number of build-in authorization providers, including some
already demonstrated above. Different modules provide different methods.
The following are provided by the mod_authz_core module:
all
Replaces Allow from all and Deny from all in the old syntax:
Require all grantedRequire all denied

env
Require env safe_zone<RequireAll> Require not env PROTECTED </RequireAll>

method
This example allows only GET and HEAD requests unless you are logged in:
<RequireAny> Require method GET HEAD Require valid-user </RequireAny>

The <RequireAny> container is not necessary here, but included for clarity:
expr
Require expr %{HTTP_USER_AGENT} != 'BadBot'

The following options are provided by the mod_authz_host module:


local
Require local

ip
<RequireAll> Require ip 192.168.1.0/24 Require not ip 192.168.1.104
</RequireAll>Require ip 2001:db8:1:1::/64

host
<RequireAll> Require host example.org Require not host blocked.example.org
</RequireAll>

4. Working with expressions


After a bit of messing about we were able to further simplify the previous example by removing
theSetEnvIf clause and replacing it with a Require expr regular expression condition.
18

AuthType Basic AuthName "Password Protected" AuthUserFile


<path_to_your_htpasswd_file> SetEnvIf REQUEST_URI "^/(admin|secure)/"
PROTECTED <RequireAll> Require not env PROTECTED </RequireAll> Require validuserAuthType Basic AuthName "Password Protected" AuthUserFile
<path_to_your_htpasswd_file> Require expr %{REQUEST_URI} !~ m#^/(admin|
secure)/# Require valid-user

The tricky part was working out how to include the forward slash / in the regular expression.
The solution is instead of the default format which doesnt allow a forward slash in the match:
Require expr %{REQUEST_URI} !~ /expr/

To use the alternative syntax:


Require expr %{REQUEST_URI} !~ m#expr#

For details on other SERVER variables and comparison operators that can be used see the link
under References below.

5. Granting local access


Another real world example is granting access only to the local network.
In this case were defining the local network as the server itself (localhost), plus the 192.168.1.*
subnet covering 192.168.1.0 192.168.1.255.
<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None
Order allow,deny Allow from 127.0.0.0/8 192.168.1 ::1 </Directory><Directory
"/path/to/your/website"> Options FollowSymlinks AllowOverride None Require
local Require ip 192.168.1 </Directory>

The local Requirement matches requests from the local host over IPv4 or IPv6 (so including
127.0.0.1/8 and ::1). We wrap this, along with Require ip 192.168.1, in a RequireAny
authorization container because we want to accept connections that match either condition.
We could also write 192.168.1.0/24 instead of just 192.168.1, but they have the same effect.
If you want to also allow connections from outside the local network, but requiring
authentication, the configuration becomes:
<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None
Require local Require ip 192.168.1 Require valid-user </Directory>

So were now granting access from localhost and the local network without authentication, plus
from all other locations, but then requiring authentication.
You can make this more secure by restricting outside access to only recognised locations:

19

<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None


Require local Require ip 192.168.1 <RequireAll> Require host example.org
Require not host badhost.example.org Require valid-user </RequireAll>
</Directory>

Now an external connection can only come from *.example.org and only in conjunction with a
valid login. To specify more than one domain or ip address in addition to example.org they will
need to be wrapped in yet another container:
<Directory "/path/to/your/website"> Options FollowSymlinks AllowOverride None
Require local Require ip 192.168.1 <RequireAll> <RequireAny> Require host
example.org example.com Require ip 8.8.8.8 </RequireAny> Require not host
badhost.example.org Require valid-user </RequireAll> </Directory>

For those getting confused, RequireAll means that all the requirements in that container need to
be met, while RequireAny means that only one or more of the contained requirements needs to
be met:
Require (local) OR (ip 192.168.1) OR [ [ (host example.org) OR (host
example.com) OR (ip 8.8.8.8) ] AND (NOT host badhost.example.com) AND (validuser) ]

6. Public file in Private directory


Thank you to Alfredo for this question how to have a password-protected directory (or website)
but allow access to a specific file.
If you have a directory ~/private/ then you can make the entire directory secure by adding
an.htaccess file ~/private/.htaccess with:
AuthType Basic AuthName "Password Required" AuthUserFile /path/to/.htpasswd
Require valid-user

But what if there is a file ~/private/public.html that you want to make globally accessible?
This wasnt possible in earlier versions of Apache, but can be done now quite simply:
AuthType Basic AuthName "Password Required" AuthUserFile /path/to/.htpasswd
Require expr %{REQUEST_URI} = "/private/public\.html" Require valid-user

How does it work? Remember that there is an explicit <RequireAny> wrapped around the two
Requirestatements, so it reads as: either the request is for the file public.html or require a
password.
June 23rd, 2016 | Category: Apache | Leave a comment

AMQ7017 queue manager log not available or corrupted


Problem
20

Your queue manager fails to start with the following error :


AMQ7017 Log not available

Cause
The qm.ini files had been altered and the LogPath entries were removed.
After making the change to qm.ini LogPath, the queue manager failed to start because
S0000001.log was not available. The log file was present and the permissions appeared to be
correct, but it seemed to be corrupted.

Solution
Edit the qm.ini file and specify the correct LogPath.
If the queue manager fails to start and you suspect a corrupted log file, then do the following:
Here are the steps to follow to recover from the damaged log file(s) in
/var/mqm/log/qmgrname/active. The queue manager is referred to as TESTQMGR.
cd /var/mqm/qmgrs
mv TESTQMGR TEST.OLD
NOTE:This will rename the TESTQMGR directory to be TEST.OLD, effectively backing up all
your queues and objects.
dltmqm TESTQMGR
Note: This command may not completely run and it may produce error messages. This is OK. At
the end of this command there are 3 places to check to make sure everything is cleaned up from
TESTQMGR and if it did not then you will need to manually remove
what is left.
There should not be a directory under /var/mqm/qmgrs by the name of TESTQMGR as it should
have been renamed to TEST.OLD.
In /var/mqm/log there should not be a directory name TESTQMGR. If there is a directory left
there, from /var/mqm/log issue the command rm -rf TESTQMGR to remove the old logs.
In /var/mqm there is a file called mqs.ini. Within file mqs.ini there will be QueueManager:
stanzas for each queue manager defined on this box. There should no longer be a stanza referring
to TESTQMGR. If there is a stanza for TESTQMGR, remove it; the whole
stanza (should be 4 lines.)
crtmqm TESTQMGR
cd /var/mqm/qmgrs
cp TESTQMGR/amqalchk.fil TEST.OLD
(This is to copy the new check point file over to the backup directory where you are saving our
old queue manager files.)
21

rm -rf TESTQMGR
(This will remove the new qmgr files you just created so you can replace them with the files
from the old queue manager that you had saved.)
mv TEST.OLD TESTQMGR
(This is where you just restored the old definitions. At this point you should have a new queue
manager created with new logs but you should have our old queues and channels still there.)
strmqm TESTQMGR
(Start up the queue manager. Everything should be back to normal except there will be no
attempt to recover any in-flight UOWs because you have nothing in the logs.)
another path ?

Failure recovery and the queue manager


After a full system failure and recovery, the queue manager might fail to start, displaying this
message:
AMQ7017 Log not available.

This typically indicates that the log file is missing or damaged, or that the log path to the queue
manager is inaccessible.
To remedy the problem, create a dummy queue manager and copy its header log file and
transaction log files over to the actual queue manager. This will allow you to restart the queue
manager.

When start being given AMQ7017 MQ queue manager: Log not available, the following
example
$ strmqm
AMQ7017: Log not available.
For this problem solving process is more complex, as an example to the queue manager QM2
about the recovery process:
1, the backup queue manager QM2 objects

22

# su mqm
$ cd /var/mqm/qmgrs
$ mv QM2 QM2_OLD
2, delete the queue manager QM2
$ dltmqm QM2
MQSeries queue manager deleted.
3, delete directory directory /var/mqm/log under the QM2
$ cd /var/mqm/log
$ rm -rf QM2
4? the file does not ensure /var/mqm/mqs.ini QM2 project, if it is deleted.
$ vi /var/mqm/mqs.ini
AllQueueManagers:
DefaultPrefix=/var/mqm
ClientExitPath:
ExitsDefaultPath=/var/mqm/exits
LogDefaults:
LogPrimaryFiles=3
LogSecondaryFiles=2
LogFilePages=1024
LogType=CIRCULAR
LogBufferPages=17
LogDefaultPath=/var/mqm/log
QueueManager:

23

Name=QM3
Prefix=/var/mqm
Directory=QM3
5? re-create the queue manager QM2
$ crtmqm QM2
MQSeries queue manager created.
Creating or replacing default objects for QM2.
Default objects statistics : 29 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.
?? /var/mqm/mqs.ini ?????
$ vi /var/mqm/mqs.ini
AllQueueManagers:
DefaultPrefix=/var/mqm
ClientExitPath:
ExitsDefaultPath=/var/mqm/exits
LogDefaults:
LogPrimaryFiles=3
LogSecondaryFiles=2
LogFilePages=1024
LogType=CIRCULAR
LogBufferPages=17
LogDefaultPath=/var/mqm/log

24

QueueManager:
Name=QM3
Prefix=/var/mqm
Directory=QM3
QueueManager:
Name=QM2
Prefix=/var/mqm
Directory=QM2
6? Copy the new check point before the backup file to a directory in QM2_OLD
$ cd /var/mqm/qmgrs
$ cp QM2/amqalchk.fil QM2_OLD
7 Remove the new queue manager object directory /var/mqm/qmgrs/QM2
$ rm -rf QM2
8?the object manager object data backup to restore the directory to the directory QM2
QM2_OLD
$ mv QM2_OLD QM2
9 start the queue manager QM2, problems get.
$ strmqm QM2
MQSeries queue manager QM2 started.
June 18th, 2016 | Category: MQ Server | Leave a comment

How to setup Pagespeed module in Nginx using rpm or yum


on CentOS 7
How to setup Pagespeed module in Nginx using rpm or yum on CentOS 7
Adding Pagespeed module in Apache is very easy with package manager:
25

sudo yum install at # if you do not already have at installed


sudo rpm -U mod-pagespeed-*.rpm
but if we want to add Pagespeed module in Nginx, first thing we think of is compiling its
source along with the Pagespeed module. What if Nginx is installed in our server from yum or
rpm? The process we need is to repackage RPM and that is what this tutorial will show.
Prepare tools
The following procedures are tested on my Linode server running Centos 7 64-bit Linux
distribution.
First we need to install the necessary tools to repackage RPM:
sudo yum install rpm-build gcc-c++ pcre-devel zlib-devel make unzip
It is recommended to not to use root user in building RPM, so we will create a new user:
useradd -m builder
* The -m is to create home directory
Select the latest version of Nginx RPM source here and download (as of this writing the latest is
nginx-1.8.1-1.el7.ngx.src.rpm):
rpm -Uvh http://nginx.org/packages/centos/7/SRPMS/nginx-1.8.1-1.el7.ngx.src.rpm
Move the Nginx RPM source to the new user created builder home directory:
mv /root/rpmbuild /home/builder/ && chown -R builder. /home/builder/rpmbuild
Pagespeed source
Login as builder and go to RPM source directory:
su builder
cd ~/rpmbuild/SOURCES/
Download and extract the latest version of Pagespeed:
wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.11.33.0-beta.zip
unzip release-1.11.33.0-beta.zip
rm release-1.11.33.0-beta.zip
Inside the extracted Pagespeed source directory, download and extract its required PSOL library:
cd ngx_pagespeed-release-1.11.33.0-beta/
wget https://dl.google.com/dl/page-speed/psol/1.11.33.0.tar.gz

26

tar -zxvf 1.11.33.0.tar.gz


rm 1.11.33.0.tar.gz
Archive both Pagespeed and PSOL as one:
cd ..
tar -zcvf ngx_pagespeed-release-1.11.33.0-beta.tar.gz ngx_pagespeed-release-1.11.33.0-beta/
rm -r ngx_pagespeed-release-1.11.33.0-beta/
cd ~
Enable Pagespeed in Nginx spec
Open and edit nginx.spec file:
vi ~/rpmbuild/SPECS/nginx.spec
Search for Source0: http://nginx.org/download/%{name}-%{version}.tar.gz and add above it:
%define pagespeed_version 1.11.33.0-beta
Note: 1.11.33.0-beta is the version of Pagespeed.
Scroll down and search Source10: nginx.suse.logrotate and add under it:
Source11: ngx_pagespeed-release-%{pagespeed_version}.tar.gz
Again scroll down and search %setup -q and add under it:
%{__tar} zxvf %{SOURCE11}
%setup -T -D -a 11
And scroll down and search with-cc-opt=%{optflags} $(pcre-config cflags) \ and add
under it (Note: there are two of these):
add-module=%{_builddir}/%{name}-%{version}/ngx_pagespeed-release-%
{pagespeed_version} \
And save the nginx.spec file.
Build and install the new Nginx with Pagespeed module
Build the Nginx RPM package:
rpmbuild -ba ~/rpmbuild/SPECS/nginx.spec
After the compilation completed you should see output message at the end something like these:

27

Wrote: /home/builder/rpmbuild/SRPMS/nginx-1.8.1-1.el7.centos.ngx.src.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debug-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debuginfo-1.8.11.el7.centos.ngx.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.lWzVrm
+ umask 022
+ cd /home/builder/rpmbuild/BUILD
+ cd nginx-1.8.1
+ /usr/bin/rm -rf /home/builder/rpmbuild/BUILDROOT/nginx-1.8.1-1.el7.centos.ngx.x86_64
+ exit 0
As we can see the Nginx RPM package bundled with Pagespeed is saved in ~/rpmbuild/RPMS/
Login as root in able to install the compiled Nginx RPM:
su
You can use yum or rpm to install it:
yum update /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
If the current nginx is higher version than we have compiled (like in my case I have nginx
v1.9.4), execute the following to force install the Nginx RPM we have build:
yum downgrade /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh oldpackage /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
Make sure it auto-start upon reboot:
chkconfig nginx on
To check if Pagespeed is included in Nginx:
nginx -V
If you dont want to build the RPM in your production server, you may use other machine.

28

In my case, I just build my RPM in my laptop using CentOS 7 64-bit Vagrant box. Just make
sure they have both the same system type (OS and processor).
For PageSpeed Nginx configuration,
May 25th, 2016 | Category: Nginx | Leave a comment

GlusterFS servers on RHEL 7 and Centos 7


GlusterFS servers on RHEL 7 and Centos 7
vi /etc/hosts
192.168.1.71 apache1.rmohan.com apache1
192.168.1.72 apache2.rmohan.com apache2
192.168.1.74 apache3.rmohan.com apache3
For this lab, we disabled both firewall and SELinux
vi /etc/selinux/config
egrep ^SELINUX= /etc/sysconfig/selinux
SELINUX=disabled
systemctl is-enabled firewalld
disabled
systemctl disable firewalld
yum update
yum -y install wget openssh* net-tools ntp
ntpdate -u 0.centos.pool.ntp.org
Before proceeding with the installation, we need to enable both EPEL (Exta Packages for
Enterprise Linux) and GlusterFS repositories on both the servers to resolve the external
dependencies at the time of installation. If you have enabled only GlusterFS repository and not
enabled EPEL repository then it is likely that you will hit the following error message while
installing glusterfs-server:
> Finished Dependency Resolution
Error: Package: glusterfs-server-3.7.11-1.el7.x86_64 (glusterfs-epel)
Requires: liburcu-cds.so.1()(64bit)
Error: Package: glusterfs-server-3.7.11-1.el7.x86_64 (glusterfs-epel)
Requires: liburcu-bp.so.1()(64bit)
You could try using skip-broken to work around the problem
You could try running: rpm -Va nofiles nodigest
EPEL installation
Retrieve EPEL repository : all 3 servers
wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-6.noarch.rpm

29

Gluster installation :
Retrieve GlusterFS repository : all 3 servers
wget -P /etc/yum.repos.d
http://download.gluster.org/pub/gluster/glusterfs/LATEST/RHEL/glusterfs-epel.repo
Download GlusterFS packages : all 3 servers
yum -y install glusterfs-server
Now, start the service and keep it started across reboot :
[root@apache3 ~]# systemctl start glusterd && systemctl enable glusterd
Created symlink from /etc/systemd/system/multi-user.target.wants/glusterd.service to
/usr/lib/systemd/system/glusterd.service.
[root@apache3 ~]#
Update /etc/hosts :
192.168.1.71 apache1.rmohan.com apache1
192.168.1.72 apache2.rmohan.com apache2
192.168.1.74 apache3.rmohan.com apache3
Check the 2 GlusterFS servers
[root@apache1 ~]# gluster peer probe apache2
peer probe: success.
[root@apache1 ~]# gluster peer probe apache3
peer probe: success.
[root@apache1 ~]#
[root@apache2 ~]# gluster peer probe apache3
peer probe: success. Host apache3 port 24007 already in peer list
[root@apache2 ~]# gluster peer probe apache1
peer probe: success. Host apache1 port 24007 already in peer list
[root@apache2 ~]#
[root@apache3 ~]# gluster peer probe apache1
peer probe: success. Host apache1 port 24007 already in peer list
[root@apache3 ~]# gluster peer probe apache2
peer probe: success. Host apache2 port 24007 already in peer list
[root@apache3 ~]#
Check the Peers :
root@apache1 ~]# gluster peer status
Number of Peers: 2
Hostname: apache2
Uuid: 09db776a-ab96-47a3-ad77-6bc77906566b
State: Peer in Cluster (Connected)
Hostname: apache3
Uuid: 14db2875-378d-481d-968c-552a10f2fd7e
30

State: Peer in Cluster (Connected)


[root@apache1 ~]#
[root@apache2 ~]# gluster peer status
Number of Peers: 2
Hostname: apache1.rmohan.com
Uuid: 16612fd4-8b94-4006-8ed7-24ac33c564e0
State: Peer in Cluster (Connected)
Other names:
apache1
Hostname: apache3
Uuid: 14db2875-378d-481d-968c-552a10f2fd7e
State: Peer in Cluster (Connected)
[root@apache3 ~]# gluster peer status
Number of Peers: 2
Hostname: apache1.rmohan.com
Uuid: 16612fd4-8b94-4006-8ed7-24ac33c564e0
State: Peer in Cluster (Connected)
Other names:
apache1
Hostname: apache2
Uuid: 09db776a-ab96-47a3-ad77-6bc77906566b
State: Peer in Cluster (Connected)
Create GlusterFS volume
We add 2 new drives from VMware ESXi (in fact, the 3 GlusterFS servers are 3 virtual
machines) : do the below commands on all 3 servers
[root@apache1 ~]# for HOST in $(ls /sys/class/scsi_host) ; do echo - ->/sys/class/scsi_host/
$HOST/scan ; done
[root@apache1 ~]# lsblk -f
NAME FSTYPE LABEL UUID MOUNTPOINT
sda
??sda1 xfs be8c0a37-1ed9-4743-b4ef-03d59ba3d06d /boot
??sda2 LVM2_member YXOIJV-EPlD-dXwg-ePQX-D7av-jPdr-Grb4rp
??centos-root xfs d2c46dc9-6365-4345-9b60-021aabfd0525 /
??centos-swap swap 74c70324-6875-40e6-9d8f-591d3325c06e [SWAP]
??centos-home xfs bd8e9210-bc95-4af9-be87-a33da31f8dbb /home
sdb
sr0 iso9660 CentOS 7 x86_64 2016-04-01-13-21-01-00
[root@apache1 ~]#
[root@apache1 ~]# parted -s /dev/sdb mklabel gpt && parted -s /dev/sdb mkpart primary xfs 0%
100% && mkfs.xfs -f /dev/sdb
31

meta-data=/dev/sdb isize=256 agcount=4, agsize=1310720 blks


= sectsz=512 attr=2, projid32bit=1
= crc=0 finobt=0
data = bsize=4096 blocks=5242880, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal log bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
[root@apache1 ~]#
Create gluster and mount on all 3 nodes
[root@apache1 ~]# mkdir /gluster
[root@apache1 ~]# vi /etc/fstab
[root@apache1 ~]# grep -i gluster /etc/fstab
/dev/sdb /gluster xfs defaults 0 0
[root@apache1 ~]#
[root@apache1 ~]# mount -a
[root@apache1 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/centos-root xfs 38G 1.2G 37G 3% /
devtmpfs devtmpfs 1.8G 0 1.8G 0% /dev
tmpfs tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs tmpfs 1.9G 8.6M 1.9G 1% /run
tmpfs tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 186M 312M 38% /boot
/dev/mapper/centos-home xfs 19G 33M 19G 1% /home
tmpfs tmpfs 371M 0 371M 0% /run/user/0
/dev/sdb xfs 20G 33M 20G 1% /gluster
[root@apache1 ~]#
Create a directory within the file system on the servers :
mkdir -p /gluster/briks
Create the GlusterFS volume based on those 3 replicas :
gluster volume create appgluster_vol replica 3 apache1:/gluster/briks apache2:/gluster/briks
apache3:/gluster/briks
[root@apache1 ~]# gluster volume create appgluster_vol replica 3 apache1:/gluster/briks
apache2:/gluster/briks apache3:/gluster/briks
volume create: appgluster_vol: success: please start the volume to access data
[root@apache1 ~]#
Then, start this volume :

32

[root@apache1 ~]# gluster volume start appgluster_vol


volume start: appgluster_vol: success
[root@apache1 ~]#
[root@apache1 ~]# gluster volume info
Volume Name: appgluster_vol
Type: Replicate
Volume ID: 856f1052-9d19-49ee-b0c1-1e53d32b86f4
Status: Started
Number of Bricks: 1 x 3 = 3
Transport-type: tcp
Bricks:
Brick1: apache1:/gluster/briks
Brick2: apache2:/gluster/briks
Brick3: apache3:/gluster/briks
Options Reconfigured:
performance.readdir-ahead: on
[root@apache1 ~]#
[root@apache1 ~]# gluster volume status
Status of volume: appgluster_vol
Gluster process TCP Port RDMA Port Online Pid

Brick apache1:/gluster/briks 49152 0 Y 3108


Brick apache2:/gluster/briks 49152 0 Y 2923
Brick apache3:/gluster/briks 49152 0 Y 2892
NFS Server on localhost 2049 0 Y 3128
Self-heal Daemon on localhost N/A N/A Y 3136
NFS Server on apache2 2049 0 Y 2943
Self-heal Daemon on apache2 N/A N/A Y 2951
NFS Server on apache3 2049 0 Y 2912
Self-heal Daemon on apache3 N/A N/A Y 2920
Task Status of Volume appgluster_vol

There are no active volume tasks


[root@apache1 ~]#
Client side
Both firewall and SELinux are disabled :
192.168.1.21 clusterserver2.rmohan.com clusterserver2
192.168.1.26 clusterserver3.rmohan.com clusterserver3
one the clinet side add the host file
192.168.1.21 clusterserver2.rmohan.com clusterserver2
33

192.168.1.26 clusterserver3.rmohan.com clusterserver3


192.168.1.71 apache1.rmohan.com apache1
192.168.1.72 apache2.rmohan.com apache2
192.168.1.74 apache3.rmohan.com apache3
[root@clusterserver3 ~]# mount.glusterfs apache1:/appgluster_vol /mnt/
[root@clusterserver3 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/centos-root xfs 50G 3.6G 47G 8% /
devtmpfs devtmpfs 1.8G 0 1.8G 0% /dev
tmpfs tmpfs 1.9G 16K 1.9G 1% /dev/shm
tmpfs tmpfs 1.9G 17M 1.8G 1% /run
tmpfs tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/loop0 ext4 1.9G 6.1M 1.7G 1% /srv/node/swiftloopback
/dev/mapper/centos-home xfs 46G 33M 46G 1% /home
/dev/sda1 xfs 497M 213M 285M 43% /boot
tmpfs tmpfs 371M 0 371M 0% /run/user/0
apache1:/appgluster_vol fuse.glusterfs 20G 33M 20G 1% /mnt
[root@clusterserver3 ~]#
[root@clusterserver3 ~]# echo here is a GlusterFS file > /mnt/file
[root@apache1 ~]# cat /gluster/briks/file
here is a GlusterFS file
[root@apache2 ~]# cat /gluster/briks/file
here is a GlusterFS file
[root@apache2 ~]#
[root@apache3 ~]# cat /gluster/briks/file
here is a GlusterFS file
[root@apache3 ~]#
May 25th, 2016 | Category: Centos RHEL 7 | Leave a comment

How to setup Pagespeed module in Nginx using rpm or yum


on CentOS 7
How to setup Pagespeed module in Nginx using rpm or yum on CentOS 7
Adding Pagespeed module in Apache is very easy with package manager:
sudo yum install at # if you do not already have at installed
sudo rpm -U mod-pagespeed-*.rpm
but if we want to add Pagespeed module in Nginx, first thing we think of is compiling its
source along with the Pagespeed module. What if Nginx is installed in our server from yum or

34

rpm? The process we need is to repackage RPM and that is what this tutorial will show.
Prepare tools
The following procedures are tested on my Linode server running Centos 7 64-bit Linux
distribution.
First we need to install the necessary tools to repackage RPM:
sudo yum install rpm-build gcc-c++ pcre-devel zlib-devel make unzip
It is recommended to not to use root user in building RPM, so we will create a new user:
useradd -m builder
* The -m is to create home directory
Select the latest version of Nginx RPM source here and download (as of this writing the latest is
nginx-1.8.1-1.el7.ngx.src.rpm):
rpm -Uvh http://nginx.org/packages/centos/7/SRPMS/nginx-1.8.1-1.el7.ngx.src.rpm
Move the Nginx RPM source to the new user created builder home directory:
mv /root/rpmbuild /home/builder/ && chown -R builder. /home/builder/rpmbuild
Pagespeed source
Login as builder and go to RPM source directory:
su builder
cd ~/rpmbuild/SOURCES/
Download and extract the latest version of Pagespeed:
wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.11.33.0-beta.zip
unzip release-1.11.33.0-beta.zip
rm release-1.11.33.0-beta.zip
Inside the extracted Pagespeed source directory, download and extract its required PSOL library:
cd ngx_pagespeed-release-1.11.33.0-beta/
wget https://dl.google.com/dl/page-speed/psol/1.11.33.0.tar.gz
tar -zxvf 1.11.33.0.tar.gz
rm 1.11.33.0.tar.gz
Archive both Pagespeed and PSOL as one:

35

cd ..
tar -zcvf ngx_pagespeed-release-1.11.33.0-beta.tar.gz ngx_pagespeed-release-1.11.33.0-beta/
rm -r ngx_pagespeed-release-1.11.33.0-beta/
cd ~
Enable Pagespeed in Nginx spec
Open and edit nginx.spec file:
vi ~/rpmbuild/SPECS/nginx.spec
Search for Source0: http://nginx.org/download/%{name}-%{version}.tar.gz and add above it:
%define pagespeed_version 1.11.33.0-beta
Note: 1.11.33.0-beta is the version of Pagespeed.
Scroll down and search Source10: nginx.suse.logrotate and add under it:
Source11: ngx_pagespeed-release-%{pagespeed_version}.tar.gz
Again scroll down and search %setup -q and add under it:
%{__tar} zxvf %{SOURCE11}
%setup -T -D -a 11
And scroll down and search with-cc-opt=%{optflags} $(pcre-config cflags) \ and add
under it (Note: there are two of these):
add-module=%{_builddir}/%{name}-%{version}/ngx_pagespeed-release-%
{pagespeed_version} \
And save the nginx.spec file.
Build and install the new Nginx with Pagespeed module
Build the Nginx RPM package:
rpmbuild -ba ~/rpmbuild/SPECS/nginx.spec
After the compilation completed you should see output message at the end something like these:
Wrote: /home/builder/rpmbuild/SRPMS/nginx-1.8.1-1.el7.centos.ngx.src.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debug-1.8.1-1.el7.centos.ngx.x86_64.rpm
Wrote: /home/builder/rpmbuild/RPMS/x86_64/nginx-debuginfo-1.8.11.el7.centos.ngx.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.lWzVrm
36

+ umask 022
+ cd /home/builder/rpmbuild/BUILD
+ cd nginx-1.8.1
+ /usr/bin/rm -rf /home/builder/rpmbuild/BUILDROOT/nginx-1.8.1-1.el7.centos.ngx.x86_64
+ exit 0
As we can see the Nginx RPM package bundled with Pagespeed is saved in ~/rpmbuild/RPMS/
Login as root in able to install the compiled Nginx RPM:
su
You can use yum or rpm to install it:
yum update /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.1-1.el7.centos.ngx.x86_64.rpm
If the current nginx is higher version than we have compiled (like in my case I have nginx
v1.9.4), execute the following to force install the Nginx RPM we have build:
yum downgrade /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
or:
rpm -Uvh oldpackage /home/builder/rpmbuild/RPMS/x86_64/nginx-1.8.11.el7.centos.ngx.x86_64.rpm
Make sure it auto-start upon reboot:
chkconfig nginx on
To check if Pagespeed is included in Nginx:
nginx -V
If you dont want to build the RPM in your production server, you may use other machine.
In my case, I just build my RPM in my laptop using CentOS 7 64-bit Vagrant box. Just make
sure they have both the same system type (OS and processor).
For PageSpeed Nginx configuration,
May 17th, 2016 | Category: Centos RHEL 7, Nginx | Leave a comment

37

How to setup Memcache on CentOS 7 for Drupal site


How to setup Memcache on CentOS 7 for Drupal site
One way to optimize the authenticated users experience in Drupal site is to use Memcache. It
works between the database and Drupal.
Typically the queries are cached in the database but with Memcache the queries sent from Drupal
to database are intercepted by Memcache and it serves them from RAM and this avoid hits to the
disk or database. We see often that half of the queries are served by Memcache and we are
looking significant improvement in authenticated users hits.
Lets take a look how to setup Memcache on CentOS 7 for Drupal site.
Install the Memcache daemon:
yum -y install memcached
Configure Memcache daemon:
vi /etc/sysconfig/memcached
Change the following:
CACHESIZE=256
OPTIONS=-l 127.0.0.1
CACHESIZE is the RAM you allot to Memcache daemon. Start it:
systemctl start memcached.service
systemctl enable memcached.service
Confirm the Memcache service running status:
memcached-tool 127.0.0.1:11211 stats
Check the remote connectivity:
watch echo stats | nc 127.0.0.1 11211
To integrate PHP and Memcache we need to install php-pecl-memcache:
yum -y install php-pecl-memcache
In your Drupal sites settings.php file, append the following codes:
/**
* Memcache configurations
*/
38

$conf[cache_backends][] = sites/all/modules/memcache/memcache.inc;
$conf[lock_inc] = sites/all/modules/memcache/memcache-lock.inc;
$conf[memcache_stampede_protection] = TRUE;
$conf[cache_default_class] = MemCacheDrupal;
// The cache_form bin must be assigned to non-volatile storage.
$conf[cache_class_cache_form] = DrupalDatabaseCache;
// Dont bootstrap the database when serving pages from the cache.
$conf[page_cache_without_database] = TRUE;
$conf[page_cache_invoke_hooks] = FALSE;
// If this server has multiple Drupal installation
// assign unique key for memcache namespace purposes
$conf[memcache_key_prefix] = www_yoursite_com;
May 17th, 2016 | Category: Centos RHEL 7 | Leave a comment

Mitigate DDoS attack with ngx_http_limit_req_module and


fail2ban
Mitigate DDoS attack with ngx_http_limit_req_module and fail2ban
The fail2ban do have comprehensive collection of scripts that scan log files and ban IPs that
match malicious activities.
But we are going to look on how to use ngx_http_limit_req_module logs to ban IPs that shows
sign of Distributed Denial of Service (DDoS) attack on your website.
It is assumed in this tutorial that Nginx server is installed in your server.
The following procedures are tested on running Centos 7 64-bit Linux distribution.
Enable ngx_http_limit_req_module by adding the following script in your Nginx configuration:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

server {

limit_req zone=one burst=5;


}
}
Restart Nginx server:
systemctl restart nginx.service
You will see entry something like this in Nginx error log if theres abuse detected:
39

2015/08/27 02:18:05 [error] 21235#21235: *326 limiting requests, excess: 5.297 by zone one,
client: 91.214.169.44, server: www.webfoobar.com, request: GET /node/8 HTTP/1.1, host:
www.webfoobar.com, referrer: https://www.webfoobar.com/archive/201502
We will use this sample log entry for our fail2ban filter script.
Install fail2ban:
yum install -y fail2ban
Create fail2ban filter script based on the Nginx error log entry:
vi /etc/fail2ban/filter.d/nginx-ddos.conf
The content of this filter file:
[Definition]
failregex = limiting requests, excess:.* by zone.*client:
ignoreregex =
We will use the /etc/hosts.deny to block the IP of the DDoS attacker so we will need to create
new fail2ban action script:
vi /etc/fail2ban/action.d/hostsdeny.conf
Add the following script as its content:
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = IP= &&
printf %%b : $IP\n >>
actionunban = IP= && sed -i.old /ALL:\ $IP/d
[Init]
file = /etc/hosts.deny
daemon_list = ALL
Enable the newly created fail2ban filter:
vi /etc/fail2ban/jail.local
Append the following script:
[nginx-ddos]
enabled = true
40

port = http,https
banaction = hostsdeny
findtime = 120
bantime = 7200
maxretry = 30
logpath = %(nginx_error_log)s
Start the fail2ban service:
systemctl start fail2ban
systemctl enable fail2ban.service
systemctl list-unit-files | grep fail2ban
To check the status of this fail2ban filter:
fail2ban-client status nginx-ddos
You will see something like this:
Status for the jail: nginx-ddos
|- Filter
| |- Currently failed: 18
| |- Total failed: 770
| `- File list:
/var/log/nginx/nginx_error_log
`- Actions
|- Currently banned: 1
|- Total banned: 8
`- Banned IP list: 91.214.169.44
To test if the fail2ban nginx-ddos filter working:
fail2ban-regex /var/log/nginx/nginx_error_log /etc/fail2ban/filter.d/nginx-ddos.conf
You can use apache-bench to test the whole system:
ab -n 20 -c 10 http://www.example.com
Execute the following command to monitor the fail2ban log:
watch -n 1 tail -n 20 /var/log/fail2ban.log
And you will something like this while testing with apache-bench:
May 17th, 2016 | Category: Centos RHEL 7 | Leave a comment

Nginx as reverse proxy for Apache


41

Setup Nginx as reverse proxy for Apache with Virtualmin support


We know that Nginx is more faster than Apache and most of us prefer to replace Apache with
Nginx as their web server.
Nginx is known to serve faster static content and run with less RAM. As of this writing,
Virtualmin supports Apache as its web server.
To take advantage of Nginx, we will install it as reverse proxy for Apache and continue using
Virtualmin to manage your domains. Nginx configurations for virtual host are tailored for Drupal
site and microcache is used here.
The following procedures are tested on my Linode server running Centos 7 64-bit Linux
distribution.
Install Nginx
If you need to install Nginx with Pagespeed module please follow the steps here instead and
jump to configure Nginx section.
In able to install the latest Nginx server we will need to register Nginx repository:
vi /etc/yum.repos.d/nginx.repo
Have the following codes as its content:
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=0
priority=1
enabled=0
Note: if just in case the nginx does not install try to hard code the $releasever with value of 7
Install Nginx using yum:
yum enablerepo=nginx -y install nginx
Make Nginx auto-start upon reboot:
chkconfig nginx on
Configure Nginx
Edit the main Nginx file /etc/nginx/nginx.conf to match the following:
user nginx;
# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesnt benefit from more than one worker per CPU.)
worker_processes auto;
42

error_log /var/log/nginx/error.log error;


pid /var/run/nginx.pid;
# Number of file descriptors used for Nginx. This is set in the OS with ulimit -n 200000
# or using /etc/security/limits.conf
worker_rlimit_nofile 200000;
events {
# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
worker_connections 1024;
# Accept as many connections as possible,
# after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main $remote_addr $remote_user [$time_local] $request
$status $body_bytes_sent $http_referer
$http_user_agent $http_x_forwarded_for;
## Use sendfile() syscall to speed up I/O operations and speed up
## static file serving.
# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring
# data to and from the user space.
sendfile on;
## Handling of IPs in proxied and load balancing situations.
set_real_ip_from 0.0.0.0/32; # all addresses get a real IP.
real_ip_header X-Forwarded-For; # the ip is forwarded from the load balancer/proxy
## If you are using CloudFlare, uncomment the lines below
## CloudFlare IPs https://www.cloudflare.com/ips
#set_real_ip_from 199.27.128.0/21;
#set_real_ip_from 173.245.48.0/20;
#set_real_ip_from 103.21.244.0/22;
#set_real_ip_from 103.22.200.0/22;
#set_real_ip_from 103.31.4.0/22;
#set_real_ip_from 141.101.64.0/18;
#set_real_ip_from 108.162.192.0/18;
#set_real_ip_from 190.93.240.0/20;
#set_real_ip_from 188.114.96.0/20;
#set_real_ip_from 197.234.240.0/22;
#set_real_ip_from 198.41.128.0/17;
#set_real_ip_from 162.158.0.0/15;
#set_real_ip_from 104.16.0.0/12;
#set_real_ip_from 172.64.0.0/13;
#set_real_ip_from 2400:cb00::/32;
43

#set_real_ip_from 2606:4700::/32;
#set_real_ip_from 2803:f800::/32;
#set_real_ip_from 2405:b500::/32;
#set_real_ip_from 2405:8100::/32;
#real_ip_header CF-Connecting-IP;
## Timeouts.
client_body_timeout 60;
client_header_timeout 60;
# Timeout for keep-alive connections. Server will close connections after this time.
keepalive_timeout 10 10;
send_timeout 60;
## Reset lingering timed out connections. Deflect DDoS.
reset_timedout_connection on;
## Body size.
client_max_body_size 10m;
## TCP options.
# dont buffer data-sends (disable Nagle algorithm).
# Good for sending frequent small bursts of data in real time.
tcp_nodelay on;
## Optimization of socket handling when using sendfile.
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers
# before calling sendfile, or for throughput optimization.
tcp_nopush on;
## Compression.
# Reduces the amount of data that needs to be transferred over the network
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 1;
gzip_http_version 1.1;
gzip_min_length 10;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml
application/xml+rss text/javascript image/x-icon application/vnd.ms-fontobject font/opentype
application/x-javascript application/x-font-ttf text/x-js;
gzip_vary on;
gzip_proxied any; # Compression for all requests.
gzip_disable MSIE [1-6]\.(?!.*SV1);
## Hide the Nginx version number.
server_tokens off;
## Use a SSL/TLS cache for SSL session resume. This needs to be
## here (in this context, for session resumption to work. See this
## thread on the Nginx mailing list:
## http://nginx.org/pipermail/nginx/2010-November/023736.html.
ssl_session_cache shared:SSL:30m;
ssl_session_timeout 1d;
## The server dictates the choice of cipher suites.
44

ssl_prefer_server_ciphers on;
## No SSL2 support.
## No SSLv3 support (SSLv3 POODLE Vulnerability)
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
## Pregenerated Diffie-Hellman parameters.
ssl_dhparam /etc/nginx/dh_param.pem;
## Curve to use for ECDH.
ssl_ecdh_curve secp521r1;
## Enable OCSP stapling. A better way to revocate server certificates.
ssl_stapling on;
## Enable verification of OCSP stapling responses by the server.
ssl_stapling_verify on;
## Use Googles DNS
resolver 8.8.4.4 8.8.8.8;
## Enable the builtin cross-site scripting (XSS) filter available
## in modern browsers. Usually enabled by default we just
## reinstate in case it has been somehow disabled for this
## particular server instance.
## https://www.owasp.org/index.php/List_of_useful_HTTP_headers.
add_header X-XSS-Protection 1; mode=block;
## Enable this if using HTTPS
#add_header Strict-Transport-Security max-age=7200;
## Block MIME type sniffing on IE.
add_header X-Content-Options nosniff;
## Add a cache miss/hit status header
add_header X-Micro-Cache $upstream_cache_status;
## Block HTTP methods.
map $request_method $not_allowed_method {
default 1;
GET 0;
HEAD 0;
POST 0;
}
## Add as many servers as needed.
## Cf. http://wiki.nginx.org/HttpUpstreamModule.
## Note that this configuration assumes by default that keepalive
## upstream connections are supported and that you have a Nginx
## version with the fair load balancer.
upstream phpapache {
## Use the least connection algorithm for load balancing
least_conn;
server 127.0.0.1:8000;
keepalive 5;
}
## Configuration for reverse proxy. Passing the necessary headers to
## the backend. Nginx doesnt tunnel the connection, it opens a new
45

## one. Hence whe need to send these headers to the backend so that
## the client(s) IP is available to them. The host is also sent.
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
## Hide the Drupal headers
proxy_hide_header X-Drupal-Cache;
proxy_hide_header X-Generator;
## Include blacklist for bad bot and referer blocking.
include blacklist.conf;
## Include the caching setup. Needed for using Drupal with an external cache.
include apps/drupal/drupal_map.conf;
## Defining the proxy cache zone for the microcache as presented at:
## http://fennb.com/microcaching-speed-your-app-up-250x-with-no-n.
proxy_cache_path /var/cache/nginx/microcache levels=1:2 keys_zone=microcache:5M
max_size=1G loader_threshold=2592000000 loader_sleep=1 loader_files=100000;
## To build optimal server_names_hash
server_names_hash_bucket_size 72;
## Include all vhosts.
include /etc/nginx/sites-enabled/*;
}
Create the file /etc/nginx/dh_param.pem and add the following to it:
BEGIN DH PARAMETERS
MIIBCAKCAQEAkD39jm2I+Sr1j1+YPB5TbgUvIWUv3Gzj1s1rtpuZJUhCQ8MElafR
XrjrNXtgN8yjX6J5+Nuj0G9SytrvtKU9T3pLDVjZiV2l0m+/pvzaW3qCSlegpA/S
bkIQPg4n7CP/dhs7JcQD0Ny6TX9iYioDz5/kGfrBHTfAW8A6gPinAiC/+8Osz6mP
UghuQPkFVxJmleIdGU7ll3tAKARJpe8HyHNMNoRGbWTCH1mc8Z/la0E7xjs5R2mh
rYxofg/TMFJyvnnjtTLRQ9edvdA+K9JNsF23t8qvY78ppHNEP7u1PA7ORtePagJk
vcSF5yMYeDzUQLWpOuK5B0yHtltZzANH6wIBAg==
END DH PARAMETERS
Create the file /etc/nginx/blacklist.conf and add the following to it:
## Add here all user agents that are to be blocked.
map $http_user_agent $bad_bot {
default 0;
~*^Lynx 0; # Let Lynx go through
libwww-perl 1;
~(?i)(httrack|htmlparser|libwww) 1;
}
## Add here all referrers that are to blocked.
map $http_referer $bad_referer {
default 0;
~(?i)(adult|babes|click|diamond|forsale|girl|jewelry|love|nudit|organic|poker|porn|
46

poweroversoftware|sex|teen|webcam|zippo|casino|replica) 1;
}
## Add here all hosts that should be spared any referrer checking.
geo $bad_referer {
127.0.0.1 0;
192.168.1.0/24 0;
}
Create the file /etc/nginx/drupal_map.conf and add the following to it:
## Let Ajax calls go through
map $uri $no_cache_ajax {
default 0;
/system/ajax 1;
}
## Check session cookie being present
map $http_cookie $no_cache_cookie {
default 0;
~SESS 1; # PHP session cookie
}
## Combine both results to get the cache bypassing mapping
map $no_cache_ajax$no_cache_cookie $no_cache {
default 1;
00 0;
}
## Cache bypassing mapping (auth).
map $no_cache_ajax $no_auth_cache {
default 0;
1 1;
}
## Set a cache_uid variable for authenticated users.
map $http_cookie $cache_uid {
default nil;
~SESS[[:alnum:]]+=(?[[:graph:]]+) $session_id;
}
Create the file /etc/nginx/drupal.conf and add the following to it:
location / {
## Let Drupal handle 404
error_page 404 /index.php;
## Regular private file serving (i.e. handled by Drupal).
location ^~ /system/files/ {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
47

## Rewrite the Host header to the value in the client request,


## or primary server name
proxy_set_header Host $host;
## For not signaling a 404 in the error log whenever the
## system/files directory is accessed add the line below.
## Note that the 404 is the intended behavior.
log_not_found off;
}
## Trying to access private files directly returns a 404.
location ^~ /sites/[\.\-[:alnum:]]+/files/private/ {
internal;
}
## Support for the file_force module
## http://drupal.org/project/file_force.
location ^~ /system/files_force/ {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
## For not signaling a 404 in the error log whenever the
## system/files directory is accessed add the line below.
## Note that the 404 is the intended behavior.
log_not_found off;
}
## If accessing an image generated by Drupal imagecache, serve it
## directly if available, if not relay the request to Drupal to (re)generate
## the image.
location ~* /imagecache/ {
## Image hotlinking protection. If you want hotlinking
## protection for your images uncomment the following line.
include hotlinking_protection.conf;
access_log off;
expires 30d;
try_files $uri $uri/ @drupal-noexp;
}
## Drupal generated image handling, i.e., imagecache in core. See:
## http://drupal.org/node/371374.
location ~* /files/styles/ {
## Image hotlinking protection. If you want hotlinking
## protection for your images uncomment the following line.
include hotlinking_protection.conf;
access_log off;
expires 30d;
try_files $uri $uri/ @drupal-noexp;
48

}
## Advanced Aggregation module CSS/JS
## support. http://drupal.org/project/advagg.
location ~ ^/sites/[\.\-[:alnum:]]+/files/advagg_(?:css|js)/ {
expires max;
gzip_static on;
add_header ETag ;
add_header Accept-Ranges ;
# Set a far future Cache-Control header to 52 weeks.
add_header Cache-Control max-age=31449600, no-transform, public;
location ~* (?:css|js)[_\-[:alnum:]]+\.(?:css|js)(\.gz)?$ {
access_log off;
try_files $uri $uri/ @drupal-noexp;
}
}
## All static files will be served directly.
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|htm|html|xml|txt|otf|ttf|eot|woff|svg|webp|webm|
zip|gz|tar|rar)$ {
access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
## Set the OS file cache.
open_file_cache max=3000 inactive=120s;
open_file_cache_valid 45s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
try_files $uri $uri/ @drupal-noexp;
}
## PDFs and powerpoint files handling.
location ~* ^.+\.(?:pdf|pptx?)$ {
access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
try_files $uri $uri/ @drupal-noexp;
}
## MP3 and Ogg/Vorbis files are served using AIO when supported. Your OS must support it.
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/mp3 {
location ~* .*\.mp3$ {
access_log off;
directio 4k; # for XFS
## If youre using ext3 or similar uncomment the line below and comment the above.
#directio 512; # for ext3 or similar (block alignments)
49

tcp_nopush off;
aio on;
output_buffers 1 2M;
try_files $uri $uri/ @drupal;
}
}
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/ogg {
location ~* .*\.ogg$ {
access_log off;
directio 4k; # for XFS
## If youre using ext3 or similar uncomment the line below and comment the above.
#directio 512; # for ext3 or similar (block alignments)
tcp_nopush off;
aio on;
output_buffers 1 2M;
try_files $uri $uri/ @drupal;
}
}
## Pseudo streaming of FLV files:
## http://wiki.nginx.org/HttpFlvStreamModule.
## If pseudo streaming isnt working, try to comment
## out in nginx.conf line with:
## add_header X-Frame-Options SAMEORIGIN;
location ~ ^/sites/[\.\-[:alnum:]]+/files/video/flv {
location ~* .*\.flv$ {
access_log off;
flv;
try_files $uri $uri/ @drupal;
}
}
## Pseudo streaming of H264/AAC files. This requires an Nginx
## version greater or equal to 1.0.7 for the stable branch and
## greater or equal to 1.1.3 for the development branch.
## Cf. http://nginx.org/en/docs/http/ngx_http_mp4_module.html.
location ~ ^/sites/[\.\-[:alnum:]]+/files/video/mp4 { # videos
location ~* .*\.(?:mp4|mov)$ {
access_log off;
mp4;
mp4_buffer_size 1M;
mp4_max_buffer_size 5M;
try_files $uri $uri/ @drupal;
}
}
location ~ ^/sites/[\.\-[:alnum:]]+/files/audio/m4a { # audios
location ~* .*\.m4a$ {
access_log off;
50

mp4;
mp4_buffer_size 1M;
mp4_max_buffer_size 5M;
try_files $uri $uri/ @drupal;
}
}
## Advanced Help module makes each module provided README available.
location ^~ /help/ {
location ~* ^/help/[^/]*/README\.txt$ {
access_log off;
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
}
}
## Replicate the Apache directive of Drupal standard
## .htaccess. Disable access to any code files. Return a 404 to curtail
## information disclosure. Hide also the text files.
location ~* ^(?:.+\.(?:htaccess|make|txt|engine|inc|info|install|module|profile|po|pot|sh|.*sql|test|
theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
return 404;
}
## First we try the URI and relay to the upstream server if not found.
try_files $uri $uri/ @drupal;
}
## Restrict access to the strictly necessary PHP files. Reducing the
## scope for exploits. Handling of PHP code and the Drupal event loop.
location @drupal {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
## Proxy microcache
include microcache_proxy.conf;
## The Cache-Control and Expires headers should be delivered untouched
## from the upstream to the client.
proxy_ignore_headers Cache-Control Expires;
## To avoid any interaction with the cache control headers we expire
## everything on this location immediately.
expires epoch;
}
51

## Restrict access to the strictly necessary PHP files. Reducing the


## scope for exploits. Handling of PHP code and the Drupal event loop.
location @drupal-noexp {
proxy_pass http://phpapache;
proxy_http_version 1.1; # keep alive to the Apache upstream
proxy_set_header Connection ;
## Rewrite the Host header to the value in the client request,
## or primary server name
proxy_set_header Host $host;
## Proxy microcache.
include microcache_proxy.conf;
}
## Disallow access to .bzr, .git, .hg, .svn, .cvs directories
## Return 404 as not to disclose information.
location ^~ /.bzr {
return 404;
}
location ^~ /.git {
return 404;
}
location ^~ /.hg {
return 404;
}
location ^~ /.svn {
return 404;
}
location ^~ /.cvs {
return 404;
}
## Disallow access to patches directory.
location ^~ /patches {
return 404;
}
## Disallow access to drush backup directory.
location ^~ /backup {
return 404;
}
## Disable access logs for robots.txt.
location = /robots.txt {
access_log off;
## Add support for the robotstxt module
## http://drupal.org/project/robotstxt.
try_files $uri $uri/ @drupal;
}
## RSS feed support.
location = /rss.xml {
52

try_files $uri $uri/ @drupal;


}
## XML Sitemap support.
location = /sitemap.xml {
try_files $uri $uri/ @drupal;
}
## Support for favicon.
## Return an 11 transparent GIF if it doesnt exist.
location = /favicon.ico {
expires 30d;
try_files /favicon.ico @empty;
}
## Return an in memory 11 transparent GIF.
location @empty {
expires 30d;
empty_gif;
}
## Any other attempt to access PHP files returns a 404.
location ~* ^.+\.php$ {
return 404;
}
Create the file /etc/nginx/microcache_proxy.conf and add the following to it:
## The cache zone referenced.
proxy_cache microcache;
## The cache key.
proxy_cache_key $cache_uid@$scheme$host$request_uri;
## For 200 and 301 make the cache valid for 5 seconds.
proxy_cache_valid 200 301 5s;
## For 302 make it valid for 1 minute.
proxy_cache_valid 302 1m;
## For 404 make it valid 1 second.
proxy_cache_valid 404 1s;
## If there are any upstream errors or the item has expired use
## whatever it is available.
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503
http_504 off;
proxy_pass_header Set-Cookie;
proxy_pass_header Cookie;
## Bypass the cache.
proxy_cache_bypass $no_auth_cache;
proxy_no_cache $no_auth_cache;
## Add a cache miss/hit status header.
add_header X-Micro-Cache $upstream_cache_status;
## Block MIME type sniffing on IE.
53

add_header X-Content-Options nosniff;


## Cache locking mechanism for protecting the backendof too many
## simultaneous requests.
proxy_cache_lock on;
Create the file /etc/nginx/hotlinking_protection.conf and add the following to it:
## Hotlinking protection for images. Include it in any context you
## want. Adjust the list of allowed referers to your liking.
valid_referers none blocked
www.yahoo.com
www.google.com.ph
www.google.com;
if ($invalid_referer) {
return 200 No hotlinking allowed\n;
}
Create the folders /etc/nginx/sites-available and /etc/nginx/sites-enabled:
mkdir /etc/nginx/sites-available /etc/nginx/sites-enabled
chown nginx. /etc/nginx/sites-available /etc/nginx/sites-enabled
In /etc/nginx/sites-available contains the physical file Nginx configurations for your virtual hosts
and to enable a virtual host Nginx configuration just create a soft link if this configuration file
from /etc/nginx/sites-available to /etc/nginx/sites-enabled. This is easy and good approach to
disable and enable a virtual host.
Restart Nginx:
systemctl restart nginx.service
Setup Nginx requirements
In this tutorial the Apache will use port 8000 and lets open this port to become accessible:
iptables -I INPUT -p tcp -m tcp dport 8000 -j ACCEPT
iptables line -vnL
service iptables save
service iptables restart
Create the Nginx cache path folder:
mkdir /var/cache/nginx/microcache
chown nginx:root /var/cache/nginx/microcache
chmod 700 /var/cache/nginx/microcache
Create Nginx logrotate script:
54

vi /etc/logrotate.d/websites_nginx_logs.conf
Content:
/var/log/virtualmin/*nginx_access_log /var/log/virtualmin/*nginx_error_log {
rotate 10
missingok
daily
compress
postrotate
service httpd graceful ; sleep 5
endscript
sharedscripts
}
Configure Apache
Since Nginx is reverse proxy to Apache, the IP address that Apache will get is the IP of the server
and we need to correct that. Apache 2.4 and above do have mod_remoteip and we will use that
module. Open mod_remoteips configuration file:
vi /etc/httpd/conf.d/remoteip.conf
Add the following codes:
# mod_remoteip settings
RemoteIPHeader X-Real-IP
RemoteIPInternalProxy 127.0.0.1
RemoteIPInternalProxy 188.8.8.8
Note: change 188.8.8.8 to your servers IP address.
Change the port of Apache:
vi /etc/httpd/conf/httpd.conf
Look for:
Listen 80
and change to:
Listen 8000
Restart Apache:
systemctl restart httpd.service
55

Configure Virtualmin
Set the virtual server template to listen to 8000. Login to Virtualmin, go to System Settings ->
Server Templates -> Default Settings and select from the dropdown Apache Website.
Change the Port number for virtual hosts from 80 to 8000. Restart webmin:
systemctl restart webmin.service
Lets build the necessary scripts that will automate the creation of Nginx virtual host file each
time Virtualmin created a new server. First the Nginx virtual host template:
vi /etc/nginx/sites-available/template.conf
The content:
## Configuration for {DOM}.
server {
## Replace XXX.XXX.XXX.XXX with your servers IPv4 address
listen XXX.XXX.XXX.XXX:80;
## Replace XXXX:XXXX::XXXX:XXXX:XXXX:XXXX with your servers IPv6 address
listen [XXXX:XXXX::XXXX:XXXX:XXXX:XXXX]:80;
server_name {DOM};
## Redirect permanently to domain with www
return 301 $scheme://www.{DOM}$request_uri;
}
server {
## Replace XXX.XXX.XXX.XXX with your servers IPv4 address
listen XXX.XXX.XXX.XXX:80;
## Replace XXXX:XXXX::XXXX:XXXX:XXXX:XXXX with your servers IPv6 address
listen [XXXX:XXXX::XXXX:XXXX:XXXX:XXXX]:80;
server_name www.{DOM};
## Access and error logs.
access_log /var/log/virtualmin/{DOM}_nginx_access_log;
error_log /var/log/virtualmin/{DOM}_nginx_error_log error;
## Root of the site and index.
root {HOME}/public_html;
index index.php;
## Deny access based on the User-Agent header.
if ($bad_bot) {
return 444;
}
## Deny access based on the Referer header.
if ($bad_referer) {
return 444;
}
## Protection against illegal HTTP methods. Only HEAD,
56

## GET and POST are allowed.


if ($not_allowed_method) {
return 405;
}
## Configuration for Drupal site
include drupal.conf;
}
vi /usr/local/bin/virtualmin.sh
#!/bin/sh
NGINX_CONF_FILE=/etc/nginx/sites-available/${VIRTUALSERVER_DOM}.conf
if [ $VIRTUALSERVER_ACTION = CREATE_DOMAIN ]; then
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
cp /etc/nginx/sites-available/template.conf $NGINX_CONF_FILE
perl -pi -e s#{DOM}#$VIRTUALSERVER_DOM#g $NGINX_CONF_FILE
perl -pi -e s#{SITE_IP}#$VIRTUALSERVER_IP#g $NGINX_CONF_FILE
perl -pi -e s#{HOME}#$VIRTUALSERVER_HOME#g $NGINX_CONF_FILE
ln -s $NGINX_CONF_FILE /etc/nginx/sites-enabled/${VIRTUALSERVER_DOM}.conf
nginx -s reload
fi
elif [ $VIRTUALSERVER_ACTION = DELETE_DOMAIN ]; then
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
rm /etc/nginx/sites-enabled/${VIRTUALSERVER_DOM}.conf
rm /etc/nginx/sites-available/${VIRTUALSERVER_DOM}.conf
rm /var/log/virtualmin/${VIRTUALSERVER_DOM}_nginx_*
nginx -s reload
fi
elif [ $VIRTUALSERVER_ACTION = MODIFY_DOMAIN ]; then
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
if [ ! -f $NGINX_CONF_FILE ]; then
cp /etc/nginx/sites-available/template.conf $NGINX_CONF_FILE
perl -pi -e s#{DOM}#$VIRTUALSERVER_DOM#g $NGINX_CONF_FILE
perl -pi -e s#{SITE_IP}#$VIRTUALSERVER_IP#g $NGINX_CONF_FILE
perl -pi -e s#{HOME}#$VIRTUALSERVER_HOME#g $NGINX_CONF_FILE
ln -s $NGINX_CONF_FILE /etc/nginx/sites-enabled/${VIRTUALSERVER_DOM}.conf
fi
fi
if [ $VIRTUALSERVER_DOM != $VIRTUALSERVER_OLDSERVER_DOM ]; then
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
OLD_NGINX_CONF_FILE=/etc/nginx/sites-available/$
57

{VIRTUALSERVER_OLDSERVER_DOM}.conf
mv $OLD_NGINX_CONF_FILE $NGINX_CONF_FILE
rm /etc/nginx/sites-enabled/${VIRTUALSERVER_OLDSERVER_DOM}.conf
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_DOM#$VIRTUALSERVER_DOM#g
$NGINX_CONF_FILE
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_IP#$VIRTUALSERVER_IP#g
$NGINX_CONF_FILE
perl -pi -e s#$VIRTUALSERVER_OLDSERVER_HOME#$VIRTUALSERVER_HOME#g
$NGINX_CONF_FILE
ln -s /etc/nginx/sites-available/${VIRTUALSERVER_DOM}.conf /etc/nginx/sites-enabled/$
{VIRTUALSERVER_DOM}.conf
fi
fi
if [ ${VIRTUALSERVER_WEB} = 1 ];
then
nginx -s reload
fi
fi
Make the script executable:
chmod u+x /usr/local/bin/virtualmin.sh
Let Virtualmin know about the virtualmin.sh. Login to Virtualmin, go to System Settings ->
Virtualmin Configuration and select from dropdown Actions upon server and user creation.
Populate the Command to run after making changes to a server field with:
/usr/local/bin/virtualmin.sh
May 17th, 2016 | Category: Nginx | Leave a comment

Banning visitors from a specific country using Fail2ban


CENTOS 7
This article, we will take a look on how to exempt from banning visitors from a specific country
using Fail2ban and geoip.
It is assumed that Fail2ban is already installed and configured in your server.
Lets install first the geoip:
yum install geoip
Create Fail2ban action script:
vi /etc/fail2ban/action.d/geohostsdeny.conf

58

Copy the following script:


[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart =
# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop =
# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
#
command is executed with Fail2Ban user rights.
#
Excludes PH|Philippines from banning.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = IP=<ip> &&
COUNTRY=$(geoiplookup $IP | egrep <country_list>) && [ $COUNTRY ] ||
(printf %%b <daemon_list>: $IP\n >> <file>
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
#
command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionunban = IP=<ip> && sed -i.old /ALL:\ $IP/d <file>
[Init]
# Option: country_list
# Notes.: List of exempted countries separated by pipe |
# Values: STR Default:
59

#
country_list = PH|Philippines
# Option: file
# Notes.: hosts.deny file path.
# Values: STR Default: /etc/hosts.deny
#
file = /etc/hosts.deny
# Option: daemon_list
# Notes: The list of services that this action will deny. See the man page
#
for hosts.deny/hosts_access. Default is all services.
# Values: STR Default: ALL
daemon_list = ALL
The script above will exempt from banning the visitors from Philippines which defined in
country_list.
To enable our action script in Fail2Ban:
vi /etc/fail2ban/jail.local
Copy the following line:
banaction = geohostsdeny
Restart Fail2Ban:
systemctl restart fail2ban

60

S-ar putea să vă placă și