Categories

MOD_REWRITE, A BEGINNERS GUIDE

mod_rewrite is used for rewriting a URL at the server level, giving the user output for that final page. So, for example, a user may ask for http://www.somesite.com/widgets/blue/, but will really be given http://www.somesite.com/widgets.php?colour=blue by the server.

You can use mod_rewrite to redirect all pages to one central PHP page, which then loads the data that the user wanted from an external data file. Lots of people use mod_rewrite to show an “alternative” image when people are hotlinking directly to their images.

Assuming the mod_rewrite module is loaded, then you’re good to go!

A simple mod_rewrite example

So, let’s write a simple mod_rewrite example. This isn’t going to be anything fancy; we’re just going to redirect people who ask for alice.html to the page bob.html instead. First, let’s create the Alice and Bob pages. Below is Alice’s webpage – create a similar one for Bob.

This is Alice’s webpage
Upload both of these to your web server, and check that you can view both of them. Now comes the fun – we’re going to add a couple of lines to your .htaccess file. The .htaccess file is a text file which contains Apache directives. Any directives which you place in it will apply to the directory which the .htaccess file sits in, and any below it. To ours, we’re going to add the following:

RewriteEngine on
RewriteRule ^alice.html$ bob.html
Upload this .htaccess file to the same directory as alice.html and bob.html, and reload Alice’s page. You should see Bob’s page being displayed, but Alice’s URL. If you still see Alice’s page being displayed, then check you’ve followed the instructions correctly (you may have to clear your cache). If things still aren’t working for you, then contact your technical support people and ask them to enable mod_rewrite and the FileInfo override in their httpd.conf file for you

The structure of a RewriteRule

RewriteRule Pattern Substitution [OptionalFlags]
The general structure of a RewriteRule is fairly simple if you already understand regular expressions. This article isn’t intended to be a tutorial about regular expressions though – there are already plenty of those available. RewriteRules are broken up as follows:

RewriteRule

This is just the name of the command.

Pattern

A regular expression which will be applied to the “current” URL. If any RewriteRules have already been performed on the requested URL, then that changed URL will be the current URL.

Substitution

Substitution occurs in the same way as it does in Perl, PHP, etc.

You can include backreferences and server variable names (%{VARNAME}) in the substitution. Backreferences to this RewriteRule should be written as $N, whereas backreferences to the previous RewriteCond should be written as %N.

A special substitution is -. This substitution tells Apache to not perform any substitution. I personally find that this is useful when using the F or G flags (see below), but there are other uses as well.

OptionalFlags

This is the only part of the RewriteRule which isn’t mandatory. Any flags which you use should be surrounded in square brackets, and comma separated. The flags which I find to be most useful are:

F – Forbidden. The user will receive a 403 error.
L – Last Rule. No more rules will be proccessed if this one was successful.
R[=code] – Redirect. The user’s web browser will be visibly redirected to the substituted URL. If you use this flag, you must prefix the substitution with http://www.somesite.com/, thus making it into a true URL. If no code is given, then a HTTP reponse of 302 (temporarily moved) is sent.
A full list of flags is given in the Apache mod_rewrite manual.

A slightly more complicated mod_rewrite example

Let’s try a slightly more meaty example now. Suppose you have a web page which takes a parameter. This parameter tells the page how to be displayed, and what content to pull into it. Humans don’t tend to like remembering the additional syntax of query strings for URLs, and neither do search engines. Both sets of people seem to much prefer a straight URL, with no extra bits tacked onto the end.

In our example, you’ve created a main index page with takes a page parameter. So, a link like index.php?page=software would take you to a software page, while a link to index.php?page=interests would take you to an interests page. What we’ll do with mod_rewrite is to silently redirect users from page/software/ to index.php?page=software etc.

The following is what needs to go into your .htaccess file to accomplish that:

RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]

Let’s walk through that RewriteRule, and work out exactly what’s going on:

^page/

Sees whether the requested page starts with page/. If it doesn’t, this rule will be ignored.

([^/.]+)

Here, the enclosing brackets signify that anything that is matched will be remembered by the RewriteRule. Inside the brackets, it says “I’d like one or more characters that aren’t a forward slash or a period, please”. Whatever is found here will be captured and remembered.

/?$

Makes sure that the only thing that is found after what was just matched is a possible forward slash, and nothing else. If anything else is found, then this RewriteRule will be ignored.

index.php?page=$1

The actual page which will be loaded by Apache. $1 is magically replaced with the text which was captured previously.

[L]

Tells Apache to not process any more RewriteRules if this one was successful.

Let’s write a quick page to test that this is working. The following test script will simply echo the name of the page you asked for to the screen, so that you can check that the RewriteRule is working.

The requested page was:
< ?php echo $_GET['page']; ?>
Again, upload both the index.php page, and the .htaccess file to the same directory. Then, test it! If you put the page in http://www.somesite.com/mime_test/, then try requesting http://www.somesite.com/mime_test/page/software. The URL in your browser window will show the name of the page which you requested, but the content of the page will be created by the index.php script! This technique can obviously be extended to pass multiple query strings to a page – all you’re limited by is your imagination.

Conditional Statements and mod_rewrite

But what happens when you start getting people hotlinking to your images (or other files)? Hot linking is the act of including an image, media file, etc from someone else’s server in one of your own pages as if it were your own. Obviously, as a webmaster, there are plenty of times when you don’t want people doing that. You’ll almost certainly have seen examples where someone has linked to one image on a website, only for a completely different, “nasty” one to be shown instead. So, how is this done?

It’s pretty simple really. All it takes are a couple of RewriteCond statements in your .htaccess file.

RewriteCond statements are as they sound – conditional statements for RewriteRules. The basic format for a RewriteCond is RewriteCond test_string cond_pattern. For our purpose, we will set the test_string to be the HTTP_REFERER. If the test string is neither empty nor our own server, then we will serve an alternative (low bandwidth) image, which tells the person who is hotlinking off for stealing our bandwidth.

Here’s how we do that:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?somesite.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.somesite.com/nasty.gif [R,L]
Here, the RewriteRule will only be performed if all the preceeding RewriteConds are fulfilled. In the second RewriteCond, [NC] simply means “No Case”, so it doesn’t matter whether the domain name was written in upper case, lower case or a mixture of the two. So, any requests for gif, jpg or png files from referers other than somesite.com will result in your “nasty” image being shown instead.

The [R,L] in the RewriteRule simply means “Redirect, Last”. So, the RewriteRule will visibly redirect output to “nasty.gif” and no more RewriteRules will be performed on this URL.

If you simply don’t want the hot linkers to see any image at all when they hot link to your images, then simply change the final line to RewriteRule \.(gif|jpg|png)$ – [F]. The – means “don’t rewrite the requested URL”, and the [F] means “Forbidden”. So, the hot linker will get a “403 Forbidden message”, and you don’t end up wasting your bandwidth.

Conclusion

mod_rewrite is an incredibly handy tool to have in your arsenal. This article only scratched the surface of what is possible with mod_rewrite, but should have given you enough information to go out and start mod_rewriting history yourself!

BLOCKING IMAGE BANDWIDTH THEFT/HOTLINKING WITH URL REWRITING

You can stop others from hotlinking your site’s files by placing a file called .htaccess in your Apache site root (main) directory. The period before the name means the file is hidden, so you may want to edit your file as htaccess.txt, upload it to your server, then rename the txt file to .htaccess in your directory or Apache config file httpd.conf
Contact your web host on how to access your directories and configure your .htaccess file.

Example: Your site url is www.mysite.com. To stop hotlinking of your images from other sites and display a replacement image called wtf.jpg placed in your images directory, place this code in your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?rmohan.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ /gfx/wtf.png [L]
The first line of the above code begins the rewrite. The second line matches any requests from your own mysite.com url. The [NC] code means “No Case”, meaning match the url regardless of being in upper or lower case letters. The third line means allow empty referrals. The last line matches any files ending with the extension jpeg, jpg, gif, bmp, or png. This is then replaced by the nohotlink.jpe file in your images directory. This JPEG image is using the extension jpe instead of jpg to prevent blocking your own replacement image.

To stop hotlinking from specific outside domains only, such as myspace.com, blogspot.com and livejournal.com, but allow any other web site to hotlink images:

RewriteEngine On
RewriteCond %{HTTP_REFERER} ^http://(.+.)?myspace.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+.)?blogspot.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+.)?livejournal.com/ [NC]
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpe [L]
You can add as many different domains as needed. Each RewriteCond line should end with the [NC,OR] code. NC means to ignore upper and lower case. OR means “Or Next”, as in, match this domain or the next line that follows. The last domain listed omits the OR code since you want to stop matching domains after the last RewriteCond line.

You can display a 403 Forbidden error code instead of an image. Replace the last line of the previous examples with this line:

RewriteRule .*.(jpe?g|gif|bmp|png)$ – [F]
Warning: Do not use .htaccess to redirect image hotlinks to another HTML page or server that isn’t your own (such as this web page). Hotlinked images can only be replaced by other images, not with an HTML page.

As with any htaccess rewrites, you may block some legitimate traffic (such as users behind proxies or firewalls) using these techniques.

TEMPORARY “SITE DOWN” NOTICE IN APACHE Linux Web

“Site down for maintenance” notice using Apache .htaccess and the mod_rewrite module.
I assume you know how to enable the Apache htaccess directive and the mod_rewrite module.

First you need to create a .htaccess file in your root level of your website.
Next you add the following lines to it

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/sitedown.html$
RewriteRule $ /sitedown.html [R=302,L]
The .htaccess file should be “active” immediately and you should see the content of your sitedown.html file. If not, try clearing your browsers cache.

If you as a maintenance user would like to access the site without seeing the sitedown.html file, add the following line to enable IP address exception

RewriteCond %{REMOTE_HOST} !^192\.168\.0\.12

Remember to replace the IP address with your address.

The .htaccess file should now look something like this.

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/sitedown.html$
RewriteCond %{REMOTE_HOST} !^192\.168\.0\.12
RewriteRule $ /sitedown.html [R=302,L]
Just delete the .htaccess file when you are done with your maintenance and your site will be available again.

Manage Time service on RH and CentOS 7

When Linux system first boots the hardware clock is read first. The time on the hardware clock read from local hardware clock in UTC – Universal Time. Local time is the actual time in the current time zone. System time, unlike Hardware clock maintained by operating system. System clock is completely independent of the hardware clock.
How to manage time
Command Description
date Manage local time
hwclock Manage hardware time
timedatectl Manage time on CentOS 7 or RH 7
Examples of using date
root@on ~]# date
Wed Jun 7 13:34:40 EDT 2017
[root@on ~]# date +%d-%m-%y
07-06-17
[root@on ~]# date -s 13:40:00
Wed Jun 7 13:40:00 EDT 2017
[root@on ~]# date
Wed Jun 7 13:40:05 EDT 2017
[root@on ~]#
Examples of using hwclock
[root@on ~]# hwclock -c
hw-time system-time freq-offset-ppm tick
1496857021 1496857310.458797
1496857031 1496857320.459274 48 0
1496857041 1496857330.459571 39 0
[root@on ~]# hwclock –systohc
[root@on ~]# hwclock -c
hw-time system-time freq-offset-ppm tick
1496857353 1496857353.012685
1496857363 1496857363.013179 49 0
1496857373 1496857373.013471 39 0
hwclock command meaning
hwclock -c shows the difference between hardware time and system time.
The output of this command is refreshed every 10 seconds. Listing 24.1 shows
the output of this command.
hwclock –systohc synchronizes current system time to the hardware clock.
hwclock –hctosys synchronizes current hardware time to the system clock.
Examples using timedatectl command
[root@on ~]# timedatectl
Local time: Wed 2017-06-07 13:48:01 EDT
Universal time: Wed 2017-06-07 17:48:01 UTC
RTC time: Wed 2017-06-07 17:48:01
Time zone: America/New_York (EDT, -0400)
NTP enabled: n/a
NTP synchronized: no
RTC in local TZ: no
DST active: yes
Last DST change: DST began at
Sun 2017-03-12 01:59:59 EST
Sun 2017-03-12 03:00:00 EDT
Next DST change: DST ends (the clock jumps one hour backwards) at
Sun 2017-11-05 01:59:59 EDT
Sun 2017-11-05 01:00:00 EST
[root@on ~]# timedatectl list-timezones
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Bamako
Africa/Bangui
….
[root@on ~]# timedatectl set-timezone America/Toronto
[root@on ~]# timedatectl
Local time: Wed 2017-06-07 13:50:09 EDT
Universal time: Wed 2017-06-07 17:50:09 UTC
RTC time: Wed 2017-06-07 17:50:09
Time zone: America/Toronto (EDT, -0400)
NTP enabled: n/a
NTP synchronized: no
RTC in local TZ: no
DST active: yes
Last DST change: DST began at
Sun 2017-03-12 01:59:59 EST
Sun 2017-03-12 03:00:00 EDT
Next DST change: DST ends (the clock jumps one hour backwards) at
Sun 2017-11-05 01:59:59 EDT
Sun 2017-11-05 01:00:00 EST
[root@on ~]#

LAMP on CentOS7

Many open source p[projects require LAMP with database and database user ready to go. Here we will look at basic commands on CentOS7 to get it up and running quickly.

After CentOS7 installed update all packages
yum update -y
Install apache web server
yum install httpd
Start service and enable it to start on boot
systemctl start httpd.service
systemctl enable httpd.service
Install MariaDB database server
yum install mariadb-server mariadb
Start mysql services
systemctl start mariadb
Secure mysql installation
mysql_secure_installation
Enable MariaDB to start on boot
systemctl enable mariadb.service
Install PHP with mysql support
yum install php php-mysql
Restart apache web server
systemctl restart httpd.service
Open necessary firewall ports for example http
firewall-cmd –zone=public –permanent –add-service=http
firewall-cmd –reload
And finally create database and user. See example below.
create database mydb;
grant usage on *.* to mydbuser@localhost identified by ‘mypassword’;
grant all privileges on mydb.* to user@localhost ;
FLUSH PRIVILEGES;

Open vSwitch installation on CentOS 7.2
Open vSwitch (OVS) is a production quality, multilayer virtual switch software available for various platforms. The server platforms include x86 based latest Linux distributions e.g. Debian 16 LTS or CentOS 7.2. Popular SDN switch operating system development company Pica8 also bundles the OVS in a custom Ubuntu version for Pronto, Dell, and many other switches.

Below is an effort to provide easy installation instructions for OVS on CentOS 7.2 and also to integrate OVS with the OpenDaylight. Note this blog is updated to use OVS version 2.5.1 (bug fix release for OVS 2.5.0).

Install the requisite packages.
#yum -y install make gcc openssl-devel autoconf automake rpm-build redhat-rpm-config python-devel openssl-devel kernel-devel kernel-debug-devel libtool wget
Necessary steps for building RPM
#mkdir -p ~/rpmbuild/SOURCES
#wget http://openvswitch.org/releases/openvswitch-2.8.0.tar.gz
#cp openvswitch-2.8.0.tar.gz ~/rpmbuild/SOURCES/
#tar xfz openvswitch-2.8.0.tar.gz
#sed ‘s/openvswitch-kmod, //g’ openvswitch-2.8.0/rhel/openvswitch.spec > openvswitch-2.8.0/rhel/openvswitch_no_kmod.spec
Build the RPM
#rpmbuild -bb –nocheck ~/openvswitch-2.8.0/rhel/openvswitch_no_kmod.spec
Install the RPM
#ls -l ~/rpmbuild/RPMS/x86_64/
#yum localinstall ~/rpmbuild/RPMS/x86_64/openvswitch-2.8.0-1.x86_64.rpm
Start the OVS service and enable it for the next boot
#systemctl start openvswitch.service
#chkconfig openvswitch on
This process will install the OVS on the server and start the process. Firewall should be open to accept the incoming TCP connection at port 6633.

Test the OVS Version
#ovs-vsctl -V

Useful OVS commands
#ovs-vsctl show
#ovs-ofctl show br0

Create a new OVS Bridge, add physical ports, connect OVS with ODL controller
#ovs-vsctl add-br ovsbr0
#ovs-vsctl set bridge ovsbr0 protocols=OpenFlow13
#ovs-vsctl list controller
#ovs-vsctl add-port ovsbr0 eth4
#ovs-vsctl add-port ovsbr0 eth8
#ovs-vsctl set-controller ovsbr0 tcp:192.168.1.57:6633
#ovs-vsctl show

First step we will install LAMP
yum -y install mariadb-server mariadb
systemctl start mariadb.service
systemctl enable mariadb.service
Secure MariaDB installation
mysql_secure_installation
Install Apache server
yum -y install httpd
systemctl start httpd.service
systemctl enable httpd.service
Install php with all modules
yum -y install php
yum -y install php-mysql
yum -y install php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-snmp php-soap curl curl-devel
Restart apache
systemctl restart httpd.service
Now lets install phpMyAdmin
Lets add epel repository
rpm -iUvh http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
Install phpMyAdmin
yum install phpMyAdmin
Make sure we allow access to the software
vi /etc/httpd/conf.d/phpMyAdmin.conf
Change authentication
vi /etc/phpMyAdmin/config.inc.php

[…]
$cfg[‘Servers’][$i][‘auth_type’] = ‘http’; // Authentication method (config, http or cookie based)?
[…]

Restart Apache
systemctl restart httpd.service
Now we setup virtual hosts

mkdir -p /var/www/html/site1.com/public_html
mkdir -p /var/www/html/site2.com/public_html

useradd webadmin
passwd webadmin

chown -R webadmin:webadmin /var/www/html/site1/public_html
chown -R webadmin:webadmin /var/www/html/site2/public_html

chmod -R 755 /var/www/html

vi /etc/httpd/conf/httpd.conf
IncludeOptional sites-enabled/*.conf

mkdir /etc/httpd/sites-enabled
mkdir /etc/httpd/sites-available

cd sites-available
vi site1.com.conf

ServerName www.site1.com
DocumentRoot /var/www/html/site1/public_html
ServerAlias site1.com
ErrorLog /var/www/html/site1/error.log
CustomLog /var/www/html/site1/requests.log combined

vi site2.com.conf

ServerName www.site2.com
DocumentRoot /var/www/html/site2/public_html
ServerAlias site2.com
ErrorLog /var/www/html/site2/error.log
CustomLog /var/www/html/site2/requests.log combined

ln -s /etc/httpd/sites-available/site1.com.conf /etc/httpd/sites-enabled/site1.com.conf
ln -s /etc/httpd/sites-available/site2.com.conf /etc/httpd/sites-enabled/site2.com.conf

Make sure proper firewall accept ions are added

firewall-cmd –permanent –zone=public –add-service=http
firewall-cmd –permanent –zone=public –add-service=https
firewall-cmd –reload

Install OSSEC Host Intrusion Detection Software
yum install mysql-devel postgresql-devel gcc
wget -U ossec https://bintray.com/artifact/download/ossec/ossec-hids/ossec-hids-2.8.3.tar.gz
tar -zxvf ossec-hids-2.8.3.tar.gz
cd ossec-hids-2.8.3 cd ossec-hids-2.8.3
./install.sh
Choose local install, provide email and SMTP server for alerts

Install Fail2Ban
yum install fail2ban fail2ban-systemd
cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Examine configuration file to make sure settings are as you want them
vi /etc/fail2ban/jail.local
Add ssh jail file
vi /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = ssh
#action = firewallcmd-ipset
logpath = %(sshd_log)s
maxretry = 5
bantime = 86400
With firewalld enabled and running
systemctl enable fail2ban
systemctl start fail2ban
Tracking logon attempts
cat /var/log/secure | grep ‘Failed password’
Check banned IP address
iptables -L -n
Check fail2ban status
fail2ban-client status
Remove ban from IP
fail2ban-client set sshd unbanip IPADDRESS

Install nagios to monitor server or vm
cd ~
curl -L -O http://nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz
tar xvf nagios-plugins-*.tar.gz
cd nagios-plugins-*
./configure –with-nagios-user=nagios –with-nagios-group=nagios –with-openssl
make
make install
htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin
systemctl start nagios.service
systemctl restart httpd.service
chkconfig nagios on

If you like to restrict access to Nagios web portion by IP
vi /etc/httpd/conf.d/nagios.conf
Find and comment the following two lines by adding # symbols in front of them:
Order allow,deny
Allow from all
Then uncomment the following lines, by deleting the # symbols, and add the IP addresses or ranges (space delimited) that you want to allow to in the
Allow from line:

# Order deny,allow
# Deny from all
# Allow from 127.0.0.1
Install Clamv virus scanner
yum install clamav-server clamav-data clamav-update clamav-filesystem clamav clamav-scanner-systemd clamav-devel clamav-lib clamav-server-systemd

cp /usr/share/clamav/template/clamd.conf /etc/clamd.d/clamd.conf
sed -i ‘/^Example/d’ /etc/clamd.d/clamd.conf

freshclam

cp /etc/freshclam.conf /etc/freshclam.conf.bak
sed -i ‘/^Example/d’ /etc/freshclam.conf

vi /usr/lib/systemd/system/clam-freshclam.service
# Run the freshclam as daemon
[Unit]
Description = freshclam scanner
After = network.target

[Service]
Type = forking
ExecStart = /usr/bin/freshclam -d -c 4
Restart = on-failure
PrivateTmp = true

[Install]
WantedBy=multi-user.target

systemctl enable clam-freshclam.service
systemctl start clam-freshclam.service
Add ssl website
Install mod_ssl
yum install mod_ssl
Create certioficate CSR – Certificate Signing Request
openssl req -new -newkey rsa:2048 -nodes -keyout rmohan.key -out rmohan.csr
edit /etc/httpd/sites-available and add below.

SSLEngine On
SSLCertificateFile /etc/pki/tls/certs/rmohan.crt
SSLCertificateKeyFile /etc/pki/tls/private/rmohan.key
SSLCACertificateFile /etc/pki/tls/certs/root-certificate.crt #root certificate provided by ca-certificates, omit this line

ServerAdmin info@rmohan.com
ServerName www.rmohan.com
DocumentRoot /var/www/html/rmohan.com/public_html/
ErrorLog /var/www/html/rmohan.com/logs/error.log
CustomLog /var/www/html/rmohan.com/logs/access.log combined

Finish configuration and setup correct permittions
mkdir /var/www/html/rmohan.com/public_html
chown -R webadmin:webadmin /var/www/html/rmohan.com/public_html
ln -s /etc/httpd/sites-available/rmohan.com.conf / /etc/httpd/sites-enabled/rmohan.com.conf

OpenSSH Server Best Security Practices

OpenSSH server is the standard SSH client and server. OpenSSH is suggested for remote login, transfer file by means of SCP or SFTP, and a much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two systems and networks. OpenSSH encrypts all traffic and password to effectively eliminate with assaults. In other words, we can say that “OpenSSH secure that the connection”.

OpenSSH Security Files and SSH Port

/etc/ssh/sshd_config – OpenSSH server configuration file.
/etc/ssh/ssh_config – OpenSSH client configuration file.
~/.ssh/ – Users ssh configuration directory.
~/.ssh/authorized_keys – Lists the public keys (RSA or DSA) that can be used to log into the user’s account
/etc/nologin – If this file exists, sshd refuses to let anyone except root log in.
/etc/hosts.allow and /etc/hosts.deny – Access controls lists that should be enforced by tcp-wrappers are defined here.
SSH default port – TCP 22

1: Only Use SSH Protocol 2

SSH has two protocol versions, the old protocol 1 which is insecure and the new protocol 2. SSH version is obsolete and should be avoided at all cost.

Protocol 2
2: Limit Users and Group SSH Access

You can configure SSH to permit only certain users or group to log in. By default, all users and group can login using their password or public key. In any case, for Secure SSH server, we should say exactly which Users or group can connect SSH Server. I am using this tool provides another layer of security.

Allow user’s and group’s through SSHD configuration file:

AllowUsers root dennis
AllowGroups sshgroup
Also Deny user’s and group’s through SSHD configuration file:

class=”pretty”>
DenyUsers kapil suresh
DenyGroups sshgroup
3: Configure Idle Log Out Timeout Interval

User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Sets a timeout interval in seconds after which if no data has been received from the client.

ClientAliveInterval 300
ClientAliveCountMax 0
4: Disable .rhosts Files

Specifies that .rhosts and .shosts files will not be used in RhostsRSAAuthentication or HostbasedAuthentication. Update the SSHD configuration file.

IgnoreRhosts yes
5: Disable Host-Based Authentication

This option is similar to RhostsRSAAuthentication and applies to protocol version 2 only. The default is “no”.

HostbasedAuthentication no
6: Disable root Login via SSH

There is no need to allow login directly as root. First normal users access the server and then use su or sudo to access with root. To disable root login update below entry in SSHD configuration file.

PermitRootLogin no
7: Enable a Warning Banner

The contents of the specified file are sent to the remote user before authentication is allowed. Also its important to set a warning banner.

Banner /etc/techoism.txt
Sample Content:

####################################################################################################################
# Welcome to Techoism Server #
# All connections are monitored and recorded #
# Disconnect IMMEDIATELY if you are not an authorized user! #
####################################################################################################################
8: Limit SSH Access by IP Address via IPtables

You need to firewall ssh port # 22 by updating IPtables or pf firewall configurations. Usually, OpenSSH server must only accept connections from your LAN or other remote WAN sites only.

First block all the SSH connection.

# iptables -I INPUT -p tcp -m tcp –dport 22 -j REJECT
Now enable specific SSH connection.

# iptables -A INPUT 1 -p udp -s 192.168.15.0/24 –dport 22 -j ACCEPT
# iptables -A INPUT 1 -p udp -s 172.16.5.0/24 –dport 22 -j ACCEPT
9: Change SSH Port

By default SSH listen port 22. We nee to change the SSH port no to secure the connection.

Port 3527
10: Limit IP Binding

If that port is not indicated, sshd listen on the address. By default, it listens to all the address. We can define multiple addresses also.

ListenAddress 10.230.5.6
ListenAddress 10.200.5.6
11: Use Public Key Based Authentication

Rather than using a normal password-based login, a better way is using public key authentication. Keys are viewed as substantially more secure Disable PasswordAuthentication to force users to use the key.

PubkeyAuthentication yes
PasswordAuthentication no
12: Use Keychain Based Authentication

OpenSSH offers RSA and DSA verification to remote systems without providing a password. keychain is a unique bash script designed to make key-based authentication. It offers different security benefits over passphrase keys.

See how to setup and use keychain software.

13: SSHD Chroot Jail

By default, users can access all the server directories like /etc, /bin, /sbin and so on. Now you can protect you ssh using chroot jail. This service is released in the latest version of OpenSSH, so no need to use any third party to block the user’s access.

Click here to configure the Chroot Jail for you user.

14: Disable Empty Passwords

When you want to secure the connection with password authentication, then you need to update the SSHD configuration file to specifies whether the server allows login to accounts with empty password strings. The default is “no”.

PermitEmptyPasswords no
15: Use Log Analyzer

Gives the verbosity level that is used when logging messages from SSHD. The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO.

LogLevel INFO
I hope this article will help you to secure your server.

Enjoy it!

Open vSwitch installation on CentOS 7.2

Open vSwitch installation on CentOS 7.2
Open vSwitch (OVS) is a production quality, multilayer virtual switch software available for various platforms. The server platforms include x86 based latest Linux distributions e.g. Debian 16 LTS or CentOS 7.2. Popular SDN switch operating system development company Pica8 also bundles the OVS in a custom Ubuntu version for Pronto, Dell, and many other switches.

Below is an effort to provide easy installation instructions for OVS on CentOS 7.2 and also to integrate OVS with the OpenDaylight. Note this blog is updated to use OVS version 2.5.1 (bug fix release for OVS 2.5.0).

Install the requisite packages.
#yum -y install make gcc openssl-devel autoconf automake rpm-build redhat-rpm-config python-devel openssl-devel kernel-devel kernel-debug-devel libtool wget
Necessary steps for building RPM
#mkdir -p ~/rpmbuild/SOURCES
#wget http://openvswitch.org/releases/openvswitch-2.8.0.tar.gz
#cp openvswitch-2.8.0.tar.gz ~/rpmbuild/SOURCES/
#tar xfz openvswitch-2.8.0.tar.gz
#sed ‘s/openvswitch-kmod, //g’ openvswitch-2.8.0/rhel/openvswitch.spec > openvswitch-2.8.0/rhel/openvswitch_no_kmod.spec
Build the RPM
#rpmbuild -bb –nocheck ~/openvswitch-2.8.0/rhel/openvswitch_no_kmod.spec
Install the RPM
#ls -l ~/rpmbuild/RPMS/x86_64/
#yum localinstall ~/rpmbuild/RPMS/x86_64/openvswitch-2.8.0-1.x86_64.rpm
Start the OVS service and enable it for the next boot
#systemctl start openvswitch.service
#chkconfig openvswitch on
This process will install the OVS on the server and start the process. Firewall should be open to accept the incoming TCP connection at port 6633.

Check that the command-line tools are ready
ovs-vsctl -V
NOW, if you’re using SELinux in enfocing mode and try to start the service, you’ll find some errors. Please follow the steps to solve it.
yum install policycoreutils-python
mkdir /etc/openvswitch
semanage fcontext -a -t openvswitch_rw_t “/etc/openvswitch(/.*)?”
restorecon -Rv /etc/openvswitch
Start OpenvSwitch
/etc/init.d/openvswitch start

Test the OVS Version
#ovs-vsctl -V

Useful OVS commands
#ovs-vsctl show
#ovs-ofctl show br0

Create a new OVS Bridge, add physical ports, connect OVS with ODL controller
#ovs-vsctl add-br ovsbr0
#ovs-vsctl set bridge ovsbr0 protocols=OpenFlow13
#ovs-vsctl list controller
#ovs-vsctl add-port ovsbr0 eth4
#ovs-vsctl add-port ovsbr0 eth8
#ovs-vsctl set-controller ovsbr0 tcp:192.168.1.57:6633
#ovs-vsctl show

Openstack log files

OpenStack log files contains different structures and distributed across multiple folders which make a real challenge to provide real proactive insights on your deployment. Loom Cloud Intelligence can simply save your time and make sense of your Openstack deployment on going issues.
Most services use the convention of writing their log files to subdirectories of the /var/log directory, as listed in the following list.

Compute nova-*
/var/log/nova

Image Service glance-*
/var/log/glance

Block Storage cinder-*
/var/log/cinder

Identity service keystone-*
/var/log/keystone

Networking neutron-*
/var/log/neutron

Dashboard horizon
/var/log/apache2 or /var/log/httpd

Orchestration service heat
/var/log/heat

Telemetry service ceilometer
/var/log/ceilometer

All nodes misc (swift, dnsmasq)
/var/log/syslog

Compute nodes libvirt
/var/log/libvirt/libvirtd.log

Compute nodes Console (boot upmessages) for VM instances: /var/lib/nova/instances/instance-/console.log

Block Storage nodes cinder-volume
/var/log/cinder/cinder-volume.log

How to confiugre logging in Openstack enviroment?

Separately configure the Compute service (nova), the Identity service (keystone), the Image service (glance), and, if you are using it, the Block Storage service (cinder) to send log messages to syslog. Open these configuration files:

/etc/nova/nova.conf
/etc/keystone/keystone.conf
/etc/glance/glance-api.conf
/etc/glance/glance-registry.conf
/etc/cinder/cinder.conf
In each configuration file, add these lines:

debug = False

use_syslog = True

syslog_log_facility = LOG_LOCAL0

In addition to enabling syslog, these settings also turn off debugging output from the log.

OpenStack Cheat Sheet 2017

OpenStack different services have very powerful command line interfaces, with lots of different options.

Here is quick reference of the most used command-line commands:

General:

You will probably want to know what is the name of your openstack deployment? Aka Queens, Pines, Ocata, Newton but also to Mitaka, Liberty, Kilo & Juno.
Which OpenStack version is installed?

$ openstack –version
Once you have the version, check here for the name.
Same way for other specific services too, for example:

$ nova-manage –version
$ cinder-manage –version
$ glance-manage –version
Identity Service (aka Keystone):

List all users

$ openstack user list
List Identity service catalog

$ openstack catalog
List all services in service catalog

$ openstack service list
Compute (aka Nova)

List instances, notice status of instance

$ openstack server list
List images

$ openstack image list
List flavors

$ openstack flavor list
Boot an instance using flavor and image names

$ openstack server create –image IMAGE –flavor FLAVOR INSTANCE_NAME
$ openstack server create –image cirros-0.4.8-x86_64-uec –flavor m1.large\
NewInstance
Login to a Linux instance

# ip netns

# ip netns exec NETNS_NAME ssh USER@SERVER

# ip netns exec qdhcp-34343ds43-2323-4f9c-5432-0432885dgtf2 \

ssh cirros@10.0.0.2
*Note, in CirrOS the password for user cirros is “cubswin:)”.

Show details of instance

$ openstack server show NAME
$ openstack server show NewInstance
View console log of instance

$ openstack console-log NewInstance
Set metadata on an instance

$ nova meta volumeTwoImage set newmeta=’my new meta data’
Create an instance snapshot

$ openstack image-create volumeImage snapshot1OfVolumeImage
$ openstack image-show snapshot1OfVolumeImage

Stop, Pause, resize, rebuild and offcourse reboot an instance

Pause

$ openstack server pause NAME
$ openstack server pause myinstance
Unpause

$ openstack server unpause NAME
Stop

$ openstack server stop NAME
Start

$ openstack server start NAME
Resize

$ openstack server resize NAME FLAVOR
$ openstack server resize myinstance m2.large
$ openstack server resize –confirm myinstance
Rebuild

$ openstack server rebuild NAME IMAGE
$ openstack server rebuild myinstance cirros-121
Reboot

$ openstack server reboot NAME
$ openstack server reboot myinstance
Image Service (aka Glance)

List images you can access

$ openstack image list
Delete specified image

$ openstack image delete IMAGE
Describe a specific image

$ openstack image show IMAGE
Update image

$ openstack set imageIMAGE
Networking Service (aka Neutron)

Create network

$ openstack network create NAME
Create a subnet

$ openstack subnet create –subnet-pool SUBNET –network NETWORK SUBNET_NAME
$ openstack subnet create –subnet-pool 10.0.0.2/30 –network network1 subnetwork1
List network and subnet

$ neutron net-list
$ neutron subnet-list
Examine details of network and subnet

$ neutron net-show ID_OR_NAME_OF_NETWORK
$ neutron subnet-show ID_OR_NAME_OF_NETWORK
Block Storage Service (aka Cinder)

Create a new volume

$ openstack volume create –size SIZE_IN_GB NAME
$ openstack volume create –size 10 MyVolume
Boot an instance and attach to volume

$ openstack server create –image cirros-qcow2 –flavor m2.large MyVolume
List volumes

$ openstack volume list
Attach volume to instance after instance is active, and volume is available

$ openstack server add volume INSTANCE_ID VOLUME_ID
Manage volumes after login into the instance

List storage devices

# fdisk -l
Make filesystem on volume

# mkfs.ext3 /dev/vdb
Create a mountpoint

# mkdir /myspace
Mount the volume at the mountpoint

# mount /dev/vdb /myspace
Create a file on the volume

# touch /myspace/helloworld.txt
# ls /myspace
Unmount the volume

# umount /myspace
Troubleshooting

(1) In case you tried run one of the above commands and received the following error “Missing value auth-url required for auth plugin password”, simply follow this article and you are good to go.

expect,sshpass,pash

expect,sshpass,pash
rpm -qa expect

yum install expect -y

useradd mohan

echo 123456|passwd –stdin mohan

su – mohan

ssh-keygen -t dsa -P ” -f ~/.ssh/id_dsa >/dev/null 2>&1

yum install lrzsz -y

cat mohan_sshkey.exp
#!/usr/bin/expect
if { $argc !=2 } {
send_user “usage: expect mohan_sshkey.exp file host\n”
exit
}
#define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password “123456”
#spawn scp /etc/hosts root@10.0.0.142:/etc/hosts
#spawn scp -P52113 $file testserver@$host:$dir
spawn ssh-copy-id -i $file “-p 22 oldgirl888@$host”
expect {
“yes/no” {send “yes\r” ;exp_continue}
“password” {send “$password\r”}
}
expect cof
exit -onexit {
send_user “testserver say good bye to you!\n”
}
#script usage
#expect testserver-6.exp file host dir
#example
#expect mohan_sshkey.exp file host dir
#expect mohan_sshkey.exp ~/etc/hosts 10.0.0.41:~

expect mohan_sshkey.exp .ssh/id_dsa.pub 192.168.1.21

#!/bin/sh
. /etc/init.d/functions
for ip in 8 31 41
do
expect mohan_sshkey.exp ~/.ssh/id_dsa.pub 192.168.1.$ip >/dev/null 2>&1
if [ $? -eq 0 ];then
action “$ip” /bin/true
else
action “$ip” /bin/false
fi
done

Page 2 of 15912345...102030...Last »