OpenVPN with user & password based authentication

System details:

OpenVPN Server, IP = 192.168.1.2 (Public IP, the written IP is private used for example purpose)

MySQL Server, IP = 192.168.1.2 (Public IP, the written IP is private used for example purpose)

Shell script (Customize)– 1 user – many connections

 Install MySQL Server for User/Pass Authentication, IP = 192.168.1.2

Install MySQL Server

[root@localhost]# yum install mysql-server

Log in MySQL as root

[root@localhost]#mysql -uroot -p

Create the database ‘openvpn’

mysql> CREATE DATABASE openvpn;

Create a MySQL user with username ‘USERNAME’ and password ‘PASSWORD’

mysql>GRANT ALL ON openvpn.* TO 'USERNAME'@"%" IDENTIFIED BY 'PASSWORD';

Log out root user

mysql>exit

Log in MySQL as new user ‘USERNAME’

[root@localhost]# mysql -uUSERNAME -pPASSWORD

Switch database

mysql>USE openvpn;

Create the user, log table and insert user data into it.

User table creation


CREATE TABLE IF NOT EXISTS `user` (

    `user_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,

    `user_pass` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1234',

    `user_mail` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,

    `user_phone` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,

    `user_online` tinyint(1) NOT NULL DEFAULT '0',

    `user_enable` tinyint(1) NOT NULL DEFAULT '1',

    `user_start_date` date NOT NULL,

    `user_end_date` date NOT NULL,

PRIMARY KEY (`user_id`),

KEY `user_pass` (`user_pass`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Log table creation


CREATE TABLE IF NOT EXISTS `log` (

    `log_id` int(10) unsigned NOT NULL AUTO_INCREMENT,

    `user_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,

    `log_trusted_ip` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,

    `log_trusted_port` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,

    `log_remote_ip` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,

    `log_remote_port` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,

    `log_start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

    `log_end_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

    `log_received` float NOT NULL DEFAULT '0',

    `log_send` float NOT NULL DEFAULT '0',

PRIMARY KEY (`log_id`),

KEY `user_id` (`user_id`)

) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

User data insertion


INSERT INTO `user` (

    `user_id`, `user_pass`, `user_mail`, `user_phone`,

    `user_online`, `user_enable`, `user_start_date`, `user_end_date`

)

VALUES (

    'foobar', 'foo@123', 'foo.bar@foobar.com',

    '+1234567890', 0, 1, '2014-01-01', '0000-00-00'

);

Now let’s have a look at the tables & user data we just created.

Tabel view

mysql>show tables;

+-------------------+

| Tables_in_openvpn |

+-------------------+

| log               |

| user              |

+-------------------+

User data view

mysql>select * from user;

+---------+-----------+---------------------+--------------+-------------+-------------+-----------------+---------------+

| user_id | user_pass | user_mail           | user_phone   | user_online | user_enable | user_start_date | user_end_date |

+---------+-----------+---------------------+--------------+-------------+-------------+-----------------+---------------+

| foobar    | foo@123      | foo.bar@foobar.com | +1234567890 |           0 |           1 | 2014-01-01      | 0000-00-00    |

+---------+-----------+---------------------+--------------+-------------+-------------+-----------------+---------------+

Everything seems to be OK now let’s logout of mysql

mysql>exit

Edit file /etc/mysql/my.cnf using your favourite editor & insert # to line

[root@localhost]# vi /etc/my.cnf

bind-address  = 127.0.0.1

Sample

#bind-address  = 127.0.0.1

OpenVPN Server Side Configuration

Prerequisites

OpenVPN and it’s dependencies are not available in CentOS default repositories. So, it is required to install the“EPEL” repo. in order to install OpenVPN and its dependencies.

Lets start with the installation of EPEL repo first. Downloading & installing the rpm from the below link will enable the EPEL repo on your CentOS box.

## RHEL/CentOS 6 32-Bit ##

[root@localhost]# wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
[root@localhost]# rpm -ivh epel-release-6-8.noarch.rpm

## RHEL/CentOS 6 64-Bit ##

[root@localhost]# wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
[root@localhost]# rpm -ivh epel-release-6-8.noarch.rpm

Its better to update the system using the following command:

yum update

Install OpenVPN Software

Install the OpenVPN software using the following command:

yum install openvpn easy-rsa

The easy-rsa scripts by default are in the /usr/share/easy-rsa/ directory. Make a directory /easy-rsa/keys inside the /etc/openvpn directory and copy those scripts to that directory as shown below:

mkdir -p /etc/openvpn/easy-rsa/keys
cp -rf /usr/share/easy-rsa/2.0/* /etc/openvpn/easy-rsa/

Generate CA Certificate and CA key

Edit file /etc/openvpn/easy-rsa/2.0/vars

[root@localhost]vi /etc/openvpn/easy-rsa/vars

And, change the values that matches with your country, state, city, mail id etc.


# Don't leave any of these fields blank.
export KEY_COUNTRY="IN"
export KEY_PROVINCE="Delhi"
export KEY_CITY="New Delhi"
export KEY_ORG="Test_Lab"
export KEY_EMAIL="foo@foobar.com"
export KEY_OU="server"

Go to the openvpn/easy-rsa directory:

cd /etc/openvpn/easy-rsa/

Enter the following commands one by one to initialize the certificate authority:

cp openssl-1.0.0.cnf openssl.cnfsource
source ./vars
./clean-all

Then, run the following command to generate CA certificate and CA key:

./build-ca

Sample output:

Generating a 2048 bit RSA private key
......................................................+++
............................................................+++
writing new private key to 'ca.key'
----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [DEL]:----> Press Enter
Locality Name (eg, city) [New Delhi]: ----> Press Enter
Organization Name (eg, company) [Test_Lab]: ----> Press Enter
Organizational Unit Name (eg, section) [server]: ----> Press Enter
Common Name (eg, your name or your server's hostname) [server CA]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [foo@foobar.com]: ----> Press Enter

We have now generated the CA certificate and CA key. Then create certificate and key for server using the following command:

./build-key-server server

Sample output:

Generating a 2048 bit RSA private key
....................+++
.............+++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [DEL]: ----> Press Enter
Locality Name (eg, city) [New Delhi]: ----> Press Enter
Organization Name (eg, company) [Test_Lab]: ----> Press Enter
Organizational Unit Name (eg, section) [server]: ----> Press Enter
Common Name (eg, your name or your server's hostname) [server]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [foo@foobar.com]: ----> Press Enter
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ----> Press Enter
An optional company name []: ----> Press Enter
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IN'
stateOrProvinceName   :PRINTABLE:'DEL'
localityName          :PRINTABLE:'New Delhi'
organizationName      :PRINTABLE:'Test_Lab'
organizationalUnitName:PRINTABLE:'server'
commonName            :PRINTABLE:'server'
name                  :PRINTABLE:'EasyRSA'
emailAddress          :IA5STRING:'foo@foobar.com'
Certificate is to be certified until Mar 23 12:21:34 2024 GMT (3650 days)
Sign the certificate? [y/n]:y ----> Type Y and Press Enter
1 out of 1 certificate requests certified, commit? [y/n]y ----> Type Y and Press Enter
Write out database with 1 new entries
Data Base Updated

Create certificate and key for VPN clients using the following command:

./build-key client

If you want to create certificate and key files for each client, you should replace the client parameter with an unique identifier.

Sample output:

Generating a 2048 bit RSA private key
.......+++
..................................................................................................+++
writing new private key to 'client.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [DEL]: ----> Press Enter
Locality Name (eg, city) [New Delhi]: ----> Press Enter
Organization Name (eg, company) [Test_Lab]: ----> Press Enter
Organizational Unit Name (eg, section) [server]:----> Press Enter
Common Name (eg, your name or your server's hostname) [client]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [foo@foobar.com]: ----> Press Enter
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ----> Press Enter
An optional company name []: ----> Press Enter
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IN'
stateOrProvinceName   :PRINTABLE:'DEL'
localityName          :PRINTABLE:'New Delhi'
organizationName      :PRINTABLE:'Test_Lab'
organizationalUnitName:PRINTABLE:'server'
commonName            :PRINTABLE:'client'
name                  :PRINTABLE:'EasyRSA'
emailAddress          :IA5STRING:'foo@foobar.com'
Certificate is to be certified until Mar 23 12:23:44 2024 GMT (3650 days)
Sign the certificate? [y/n]:y ----> Type Y and Press Enter
1 out of 1 certificate requests certified, commit? ----> Type Y and Press Enter
Write out database with 1 new entries
Data Base Updated

Generate Diffie Hellman (dh) Parameter

Enter the following command to generate DH parameter.

./build-dh

Sample output:

Generating DH parameters, 2048 bit long safe prime, generator 2This is going to take a long time

The necessary keys and certificates will be generated in the /etc/openvpn/easy-rsa/keys/ directory. Copy the following certificate and key files to the /etc/openvpn/keys directory.


ca.crt

dh2048.pem

server.crt

server.key

Go to the directory /etc/openvpn/easy-rsa/keys/ and enter the following command to transfer the above files to/etc/openvpn/keys directory.

[root@localhost]# mkdir /etc/openvpn/keys

[root@localhost]#cd /etc/openvpn/easy-rsa/keys/

[root@localhost]#cp dh2048.pem ca.crt server.crt server.key /etc/openvpn/keys

And then, you must copy all client certificates and keys to the remote VPN clients in order to authenticate to the VPN server. In our case, we have generated certificates and keys to only one client, so we have to copy the following files to the VPN client.


ca.crt

client.crt

client.key

Now let’s tuneup the setup to use user authorization parameters.
Customize shell script, IP = 192.168.1.2

Create directory for script ‘/etc/openvpn/script’

[root@localhost]#mkdir /etc/openvpn/script

[root@localhost]#cd /etc/openvpn/script

Create file config.sh ‘/etc/openvpn/script/config.sh’ 

[root@localhost]vi /etc/openvpn/script/config.sh

Insert the below code into the config.sh file


#!/bin/bash

##Dababase Server

HOST='192.168.1.2'

#Default port = 3306

PORT='3306'

#Username

USER='USERNAME'

#Password

PASS='PASSWORD'

#database name

DB='openvpn'

Create file test_connect_db.sh’/etc/openvpn/script/test_connect_db.sh’

[root@localhost]# vi test_connect_db.sh

Insert the below code into the test_connect_db.sh file


#!/bin/bash

. /etc/openvpn/script/config.sh

##Test Authentication

username=$1

password=$2

user_id=$(mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -sN -e "select user_id from user where user_id = '$username' AND user_pass = '$password' AND user_enable=1 AND user_start_date != user_end_date AND TO_DAYS(now()) >= TO_DAYS(user_start_date) AND (TO_DAYS(now()) <= TO_DAYS(user_end_date) OR user_end_date='0000-00-00')")

##Check user

[ "$user_id" != '' ] && [ "$user_id" = "$username" ] && echo "user : $username" && echo 'authentication ok.' && exit 0 || echo 'authentication failed.'; exit 1

Create file login.sh ‘/etc/openvpn/script/login.sh’

[root@localhost]# vi /etc/openvpn/script/login.sh

Insert the below code into the login.sh file


#!/bin/bash

. /etc/openvpn/script/config.sh

##Authentication

user_id=$(mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -sN -e "select user_id from user where user_id = '$username' AND user_pass = '$password' AND user_enable=1 AND user_start_date != user_end_date AND TO_DAYS(now()) >= TO_DAYS(user_start_date) AND (TO_DAYS(now()) <= TO_DAYS(user_end_date) OR user_end_date='0000-00-00')")

##Check user

[ "$user_id" != '' ] && [ "$user_id" = "$username" ] && echo "user : $username" && echo 'authentication ok.' && exit 0 || echo 'authentication failed.'; exit 1

Create file connect.sh ‘/etc/openvpn/script/connect.sh’

[root@localhost]# vi /etc/openvpn/script/connect.sh

Insert the below code into the file connect.sh


#!/bin/bash

. /etc/openvpn/script/config.sh

##insert data connection to table log

mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e "INSERT INTO log (log_id,user_id,log_trusted_ip,log_trusted_port,log_remote_ip,log_remote_port,log_start_time,log_end_time,log_received,log_send) VALUES(NULL,'$common_name','$trusted_ip','$trusted_port','$ifconfig_pool_remote_ip','$remote_port_1',now(),'0000-00-00 00:00:00','$bytes_received','$bytes_sent')"

##set status online to user connected

mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e "UPDATE user SET user_online=1 WHERE ser_id='$common_name'"

Create file disconnect.sh ‘/etc/openvpn/script/disconnect.sh’

[root@localhost]# vi /etc/openvpn/script/disconnect.sh

Insert the below code into the disconnect.sh file


#!/bin/bash

. /etc/openvpn/script/config.sh

##set status offline to user disconnected

mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e "UPDATE user SET user_online=0 WHERE user_id='$common_name'"

##insert data disconnected to table log

mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e "UPDATE log SET log_end_time=now(),log_received='$bytes_received',log_send='$bytes_sent' WHERE log_trusted_ip='$trusted_ip' AND log_trusted_port='$trusted_port' AND user_id='$common_name' AND log_end_time='0000-00-00 00:00:00'"

Compose OpenVPN configuration files, OpenVPN server will scan the .conf files in /etc/openvpn when it starts. For each file, it forks a daemon. In this system, we need both UDP and TCP support. I created two configuration files for two daemons in charge of UDP and TCP respectively.

Create file server-tcp-443.conf ‘/etc/openvpn/server-tcp-443.conf’ for Server Port:443


##protocol port

port 443

proto tcp

dev tun



##ip server client

server 10.4.0.0 255.255.255.0



##key

ca /etc/openvpn/keys/ca.crt

cert /etc/openvpn/keys/server.crt

key /etc/openvpn/keys/server.key

dh /etc/openvpn/keys/dh1024.pem



##option

persist-key

persist-tun

keepalive 5 60

reneg-sec 432000



##option authen.

comp-lzo

user nobody

#group nogroup

client-to-client

username-as-common-name

client-cert-not-required

auth-user-pass-verify /etc/openvpn/script/login.sh via-env



##push to client

max-clients 50

push "persist-key"

push "persist-tun"

push "redirect-gateway def1"

#push "explicit-exit-notify 1"



##DNS-Server

push "dhcp-option DNS 8.8.8.8"

push "dhcp-option DNS 8.8.4.4"



##script connect-disconnect

script-security 3 system

client-connect /etc/openvpn/script/connect.sh

client-disconnect /etc/openvpn/script/disconnect.sh



##log-status

status /etc/openvpn/log/tcp_443.log

log-append /etc/openvpn/log/openvpn.log

verb 3

Create file server-udp-53.conf ‘/etc/openvpn/server-udp-53.conf’ for Server Port:53

[root@localhost]# vi /etc/openvpnserver-udp-53.conf

Insert the below lines to the server-udp-53.conf


##protocol port

port 53

proto udp

dev tun



##ip server client

server 10.5.0.0 255.255.255.0



##key

ca /etc/openvpn/keys/ca.crt

cert /etc/openvpn/keys/server.crt

key /etc/openvpn/keys/server.key

dh /etc/openvpn/keys/dh1024.pem



##option

persist-key

persist-tun

keepalive 5 60

reneg-sec 432000



##option authen.

comp-lzo

user nobody

#group nogroup

client-to-client

username-as-common-name

client-cert-not-required

auth-user-pass-verify /etc/openvpn/script/login.sh via-env



##push to client

max-clients 50

push "persist-key"

push "persist-tun"

push "redirect-gateway def1"

push "explicit-exit-notify 1"



##DNS-Server

push "dhcp-option DNS 8.8.8.8"

push "dhcp-option DNS 8.8.4.4"



##script connect-disconnect

script-security 3 system

client-connect /etc/openvpn/script/connect.sh

client-disconnect /etc/openvpn/script/disconnect.sh



##log-status

status /etc/openvpn/log/udp_53.log

log-append /etc/openvpn/log/openvpn.log

verb 3

Create directory for log ‘/etc/openvpn/log’

[root@localhost]# mkdir /etc/openvpn/log

[root@localhost]# touch /etc/openvpn/log/openvpn.log

[root@localhost]# touch /etc/openvpn/log/tcp_443.log

[root@localhost]# touch /etc/openvpn/log/udp_53.log

Changes the permission of files

chmod -R 755 /etc/openvpn

Test authentication username ‘foobar’ and password ‘foo@123’

[root@localhost]# /etc/openvpn/script/test_connect_db.sh foobar foo@123

# user : test

# authentication ok.

# if authentication failed. check user and password in database

# or detail database server in /etc/openvpn/script/config.sh

Start serviece OpenVPN

[root@localhost]# /etc/init.d/openvpn start

Edit file /etc/sysctl.conf Remove # In line : #net.ipv4.ip_forward=1

[root@localhost]#vi /etc/sysctl.conf

net.ipv4.ip_forward=1

Execute the sysctl -p command for the changes to take effect

[root@localhost]# sysctl -p

Edit file /etc/rc.local Add before exit 0; the below code


echo "1" > /proc/sys/net/ipv4/ip_forward

echo "1" > /proc/sys/net/ipv4/ip_dynaddr

iptables -A INPUT -i tun0 -j ACCEPT

iptables -A FORWARD -i tun0 -j ACCEPT

iptables -A INPUT -i tun1 -j ACCEPT

iptables -A FORWARD -i tun1 -j ACCEPT

iptables -A INPUT -p udp --dport 53 -j ACCEPT

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

iptables -t nat -A POSTROUTING -s 10.4.0.0/24 -o eth0 -j MASQUERADE

iptables -t nat -A POSTROUTING -s 10.5.0.0/24 -o eth0 -j MASQUERADE

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

Run Script Iptables

[root@localhost]# /etc/rc.local

[root@localhost]# iptables-save

Config for Client

Config for port TCP port 443


client

dev tun

proto tcp

remote 192.168.1.2 443

nobind

auth-user-pass

reneg-sec 432000

resolv-retry infinite

ca ca.crt

comp-lzo

verb 1

Config for port UDP port 53


client

dev tun

proto udp

remote 1.1.1.1 53

nobind

auth-user-pass

reneg-sec 432000

resolv-retry infinite

ca ca.crt

comp-lzo

verb 1

That’s it, all done

Test it & share your feedback.  🙂

Secure your SSH with two step authentication using Google Authenticator.

Hey Guy’s

Here my new post about the Google Authenticator, its really a very good & effective tool.

Hope you will find this post useful.

Google Two-Factor Authentication provides next level of security from intruders to SSH server. This article will help you understand the process & how to protect your SSH server with a two-factor authentication using Google Authenticator & PAM module. Now Every time when you try to SSH to your server, you have to generate code using your phone or other devices to login the server.

Step 1: EPEL Repository Installation

First we need to add EPEL yum repository on the system. Follow this link on how to install EPEL repository.

https://shivamshukla.wordpress.com/2014/11/17/how-to-install-epel-repository-on-centos-6/

then proceed ahead with the step 2

Step 2: Google Authenticator Installation

Install Google Authenticator using yum command line tool.

[root@localhost]# yum install google-authenticator

Step 3: Configure Google authenticator

For this tutorial, we will use demo account for testing.

Use below steps to configure google-authenticator for user demouser.

[root@localhost]# su - demouser
[demouser@localhost]$ google-authenticator

now you will get the secret key & emergency codes please write them down & keep them safe. Emergency codes can only be used one time in case if your secret key is lost.

https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/demouser@localhost%3Fsecret%3DW2CUM37JJKN2KF2S

Your new secret key is: W2CUM37JJKN2KF2S

Your verification code is 357458

Your emergency scratch codes are:

56071230

90988902

61142941

30330862

64907016

After the secret codes the authenticator will ask few questions respond to them as yes if you don’t want any specific changes.


Do you want me to update your "~/.google_authenticator" file (y/n) y

Do you want to disallow multiple uses of the same authentication

token? This restricts you to one login about every 30s, but it increases

your chances to notice or even prevent man-in-the-middle attacks (y/n) y

By default, tokens are good for 30 seconds and in order to compensate for

possible time-skew between the client and the server, we allow an extra

token before and after the current time. If you experience problems with poor

time synchronization, you can increase the window from its default

size of 1:30min to about 4min. Do you want to do so (y/n) y

If the computer that you are logging into isn't hardened against brute-force

login attempts, you can enable rate-limiting for the authentication module.

By default, this limits attackers to no more than 3 login attempts every 30s.

Do you want to enable rate-limiting (y/n) y

[demouser@localhost]$

Use Google Authenticator Application in your Android, iPhone or Blackberry phones to generate verification code by entering secret key. You can also use the add on available for firefox browser.

After installing the application on your phone here’s how you can add the details on it.

Select “Enter provided key” option

gsnap1

 

Enter the details required here like demouser & the secret key

gsnap2

 

After adding the details you will get the vitrification codes here.

gsnap3

Step 4: Activate Google authenticator

To enable google authenticator edit /etc/pam.d/sshd using your favorite editor.

[root@localhost]# vi /etc/pam.d/sshd

Add the below line to the start of the file just below the first line

auth required pam_google_authenticator.so

Now edit /etc/ssh/sshd_config  and Change ChallengeResponseAuthentication option value to ‘yes’. On enabling this, openssh could ask a user any number of multi-facited (Like google authenticator) questions. Generally the system asks only for the user’s password.

[root@localhost]# vi /etc/ssh/sshd_config

Change the value from NO to YES

ChallengeResponseAuthentication yes

Restart the SSH service

[root@localhost]# service sshd restart

Now SSH your server & you will be asked for verification code first then the password.

Note: you will have to generate the secret code for each user separately & add them separately on application as well.

have fun let & me know your suggestions.

🙂

 

 

How to solve the EPEL error “Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again”

Hi Guys,

I have been working on the EPEL repository these day’s & at times I got around with the following error.

“Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again”

[root@localhost]# yum list

Loaded plugins: fastestmirror

Determining fastest mirrors

Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again

[root@localhost]

Here’s how you can solve this error if you come across this error.

edit the file epel.repo which is located in the /etc/yum.repos.d/ using your favorite editor.

& change the https link to http as show below.

[root@localhost]# vi /ete/yum.repos.d/epel.repo

now change the https to http

mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

to

mirrorlist=http://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

do this for all the links present in  the file.

then check the yum again

[root@localhost]# yum list
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.nbrc.ac.in
* epel: mirrors.123host.vn
* extras: mirror.nbrc.ac.in
* rpmforge: archive.cs.uu.nl

.

.

That’s it the issue is solved

hope you find this post helpful please don’t forget to share you feedback or comments about my post.

 

How to install EPEL repository on CentOS 6

Hey guys,

Hope you are having fun these day’s  today we are going to try on the EPEL repository installation on CentOS 6.

For 32/64 Bit Operating system.

use the below link & install it as show below.

http://dl.fedoraproject.org/pub/epel/6Server/i386/epel-release-6-8.noarch.rpm


[root@localhost]# rpm -ivh http://dl.fedoraproject.org/pub/epel/6Server/i386/epel-release-6-8.noarch.rpm

Retrieving http://dl.fedoraproject.org/pub/epel/6Server/i386/epel-release-6-8.noarch.rpm

Preparing...                ########################################### [100%]

1:epel-release           ########################################### [100%]

[root@localhost]#

Now lets verify weather our repository has been installed or not


[root@localhost]# rpm –qa |grep epel

epel-release-6-8.noarch

[root@localhost]

yeah that’s all the installation is complete.

Enjoy 🙂

Functions in a BASH script.

Hey friends here’s an other blog regarding BASH in which my aim is to help you understand basics about functions in BASH

The thing which I like about functions in BASH is that you can create/define a function at any point in your script & call it as per your requirement in the script.

Basic structure of a function in bash is as show below.

function hello{

your code or messages here

}

.

.

.

hello

Calling the function by its name where ever needed

Let’s have a look at a simple example using a script in which we will print a greeting message using function.

Create a file using your favorite editor, paste the below lines into it & exit saving changes. assign executable permissions to the file.

#!/bin/bash

function hello {

echo "Hello there this is my first bash function…"

}

hello

echo "Bye for now…."

As soon as you execute this script the following output will appear

Hello there this is my first bash function…

Bye for now….

You can use multiple functions in a single script & use them as per your requirement.

Let’s use this same script & make two different functions for each message that means one for hello the other for bye.

#!/bin/bash

function hello {

echo "Hello there this is my first bash function…"

}

function bye {

echo "Bye for now…."

}

hello

bye

 

The output remains same as above.

Hello there this is my first bash function…

Bye for now….

 

Hope you find this post helpful let me know if you have any queries.. 🙂

Shebang & Basics of Bash

Hi guys here’s my new post about Shebang & some basics about BASH & creation of first bash script.

What is Shebang?

This symbol #! (Hash with Exclamation mark) is known as shebang,

What Shebang does?

It tells the shell what program to interpret the script with, when executed.

Few examples:

#!/bin/bash                   — Execute the file using bash, the Bourne again shell, or a compatible shell

#!/bin/sh                       — Execute the file using sh, the Bourne shell, or a compatible shell

#!/bin/csh                     — Execute the file using csh, the C shell, or a compatible shell

#!/usr/bin/perl –T         — Execute using Perl with the option for taint checks

#!/usr/bin/php              — Execute the file using the PHP command line interpreter

#!/usr/bin/python -O    — Execute using Python with optimizations to code

#!/usr/bin/ruby             — Execute using Ruby

 

Some commands to learn more about the shell you have on your system.

To check the shell type & path

#echo $SHELL

/bin/bash

OR

#which bash

/bin/bash

To check if the shell is interactive or non-interactive

#echo $-

himBH

when the $- variable contains “i” in its output it means the shell is interactive.

 

Let’s try out some fun filled bash script examples.

  1. Create any file say myscript using your favorite editor like vi/vim write down the script as show below & set the executable permission to the file.

 

#!/bin/bash
echo -e "Hello World.....:)\nThis is my first bash script.."

OR

#!/bin/bash

echo "Hello World..... :)"

echo "This is my first bash script.."

Both the above script will print the message in two different lines.

The difference between the two is that in the first script both messages are used within the same echo command with additional options like “-e & \n”

-e         is used to enable interpretation of backslash escapes.

\n         is used to change the output to new line.

 

  1. In this second example we will greet the user with a welcome message whenever he access the terminal.

 

Edit the ~/.bash_profile using your favorite editor

#vi ~/.bash_profile

add the below lines to the end of the file


hname=`hostname`

usern=`whoami`

echo "Hello $usern welcome to $hname"

Now let’s understand what’s happing in the above script

 

The ~/.bash_profile is executed when BASH is invoked as a login shell, certain environment variables are set here or can be set here for that particular user.

Adding the above lines will greet the user with those messages whenever he logins the terminal.

Example:

Username: admin

Hostname: testhost

 

The output after adding those lines will be

Hello admin welcome to testhost

MRTG + RRD Installation Script for CentOS.

Hey guys here’s a script to help you install MRTG+RRD on a CentOS box

The script has been tested on  CentOS 6.4 (Final) Desktop, you can use this script to install on a Minimal Desktop or Minimal system as well.

If you choose to install MRTG+RRD on a Minimal Desktop or Minimal version you may face issue with fonts during Graph creation. The fonts issue may get resolved by itself or if not then you might have to install font packages manually that is not included into the script.

Note:

1) SELniux will be disabled if you run this script.

2) Port 80 (HTTP) will be allowed or IPTables would be disabled as per your choice. If you are running HTTP service on some custom port make sure to allow that manually if you choose not to disable IPTables.

#!/bin/bash

#########################################
##Author: Shivam Shukla ##
##Build Date: 26-10-2014 ##
##Modification Date: 03-11-2014 ##
##Version: 1.0.0 ##
##Tool: MRTG+RRD Installer for CentOS ##
#########################################

##### User Variable #####
ipadd=`ifconfig |grep inet | cut -b 21-32 |head -n1`

#### User Functions####
function fn_SELinux()
{
getenforce |grep Enforcing >/dev/null 2>&1 && se_l=1 || se_l=0
if [ $se_l -eq 1 ]
then 
echo "SELinux is Enforcing..."
echo "Disabling SELinux...."
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
echo "SELinux is Disabled...:)"
else 
echo "SELinux is Disabled :)"
fi
}

function fn_IPTable()
{
/etc/init.d/iptables status |grep not && ipt=1 || ipt=0
if [ $ipt -eq 1 ]
then 
echo "IPtables is already disabled...."
else 
echo ""
echo "IPtables service is running on the system..."
echo ""
echo "If you want I can stop the IPtable service for you or if you don't want to stop the IPtable service i will allow the httpd service in IPtables."
echo""
echo "Do you want me to stop the IPtable service [y/n]..."
read response 
fi 
echo "$response" > respo; head -1 respo > res
cat res | grep y >/dev/null 2>&1 && sure=1 || sure=0
if [ $sure -eq 1 ]
then 
echo "Disabling IPTables..... "
/etc/init.d/iptables stop
chkconfig iptables off
echo "IPTables service is disabled now...:)"
rm -f res respo 
else 
echo "Checking if http service is allowed in IPtable..."
iptables -L |grep http >/dev/null 2>&1 && ena=1 || ena=0 
if [ $ena -eq 1 ]
then
echo "http service is already allowed in IPtable :)"
else
echo "Adding httpd service to iptables..."
iptables -I INPUT 5 -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
/etc/init.d/iptables save
echo "httpd service has been allowed in IPtables... :)"
rm -f res respo
fi
fi
}

####### Information Collection #######
echo "Please enter the network IP you want to add example 192.168.1.0/24"
read netwo
echo "please enter the state/province name where system is located"
read state
echo "Please enter the country name where system is located"
read country
echo "Please enter the system administrators name"
read contact
echo "Please enter the system administrators email"
read contactmail

####### Preparing the server for MRTG installation ######
echo "Checking prerequisites...."
fn_SELinux;
fn_IPTable;
echo "Checking for wget package..."
wget |grep Usage >/dev/null 2>&1 && wgt=1 || wgt=0
if [ $wgt -eq 1 ]
then
echo "wget is already installed"
else
echo "Installing wget"
yum install -y wget
fi
echo "Installing other required packages..."
###### Necessary Package Installation ######

yum install -y httpd gcc gd gd-devel perl libpng libxml2-devel cairo-devel glib2-devel pango-devel perl-devel perl-CGI net-snmp net-snmp-utils

###### SNMP Configuration #######

mv /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf.orig
echo "com2sec local localhost public
com2sec mynetwork $netwo public
group MyRWGroup v1 local
group MyRWGroup v2c local
group MyRWGroup usm local
group MyROGroup v1 mynetwork
group MyROGroup v2c mynetwork
group MyROGroup usm mynetwork
view all included .1 80
access MyROGroup \"\" any noauth exact all none none
access MyRWGroup \"\" any noauth exact all all none
syslocation $state, $country
syscontact $contact <$contactmail>

" > /etc/snmp/snmpd.conf
/etc/init.d/snmpd restart
chkconfig snmpd on
##### MRTG Installation #######
cd /tmp
wget http://oss.oetiker.ch/mrtg/pub/mrtg.tar.gz
tar zfx mrtg.tar.gz >/dev/null 2>&1
tar -ztf mrtg.tar.gz |head -n1 |awk -F "/THANKS" '{print $1}' > mrtgvers
mrtver="$(cat /tmp/mrtgvers)"
cd $mrtver
./configure --prefix=/usr/local/mrtg2
make
make install
cd /tmp
wget http://oss.oetiker.ch/rrdtool/pub/rrdtool.tar.gz
tar zfx rrdtool.tar.gz >/dev/null 2>&1
tar -ztf rrdtool.tar.gz |head -n1 |awk -F "/THANKS" '{print $1}' > rrdvers
rrdver="$(cat /tmp/rrdvers)"
cd $rrdver
./configure --prefix=/usr/local/rrdtool
make
make install
mkdir /var/www/mrtg
mkdir /home/mrtg
/usr/local/mrtg2/bin/cfgmaker --global "WorkDir: /var/www/mrtg" --global "Options[_]: growright, bits" --global "RunAsDaemon: Yes" --global "LogFormat: rrdtool" --global "PathAdd: /usr/local/rrdtool/bin" --global "LibAdd: /usr/local/rrdtool/lib/perl/5.10.1" -ifref=ip --output /home/mrtg/mrtg.cfg public@localhost
env LANG=C /usr/local/mrtg2/bin/mrtg /home/mrtg/mrtg.cfg
echo "*/5 * * * * root env LANG=C /usr/local/mrtg2/bin/mrtg /home/mrtg/mrtg.cfg --logging /var/log/mrtg.log " > /etc/cron.d/mrtg
chkconfig crond on
/usr/local/mrtg2/bin/indexmaker --output=/var/www/mrtg/index.html /home/mrtg/mrtg.cfg
echo "
# This configuration file maps the mrtg output (generated daily)
# into the URL space. By default these results are only accessible
# from the local host.
# 
Alias /mrtg /var/www/mrtg
<Location /mrtg>
Order deny,allow
#Deny from all
Allow from 127.0.0.1
Allow from ::1
# Allow from .example.com
Allow from all
</Location>
" > /etc/httpd/conf.d/mrtg.conf
chkconfig httpd on
service httpd restart
cd /tmp
wget https://shivamshukla.wordpress.com/wp-content/uploads/2014/10/14all-cgi1.key >/dev/null 2>&1
mv /tmp/14all-cgi1.key /var/www/cgi-bin/14all.cgi
chmod 777 /var/www/cgi-bin/14all.cgi
echo "MRTG Installation Completed.... :)"
echo "Click the link to open the MRTG page http://$ipadd/mrtg"


Download Link for the above script:

https://shivamshukla.wordpress.com/wp-content/uploads/2014/11/mrtg.key