Category: Linux Tools

Home / Category: Linux Tools

Creating SSL Certificate for HAProxy

 
In my last tutorial I’ve discussed how to implement HAProxy with an ACL. 
 
In that case study, we have terminated all the HTTPS traffic on HAProxy itself and then forward decrypted traffic to our internal server iiswebsrv01 and  iiswebsrv02.
 
To implement above solution successfully we may required to attain a SSL certificates, In this tutorial we will disscuss how to create a free SSL certificate to use with HAProxy.

We will use a open CA call  “Let’s Encrypt” in this tutorial.

What is Let’s Encrypt?
               – Let’s Encrypt is a free, automated, and open certificate authority (CA)
 
To Manage the SSL certificate I will use certbot, 
certbot is a client service which can use to fetch and deploy SSL certificate.
 
To install certbot (CentOS 7),

1. Install EPEL repos

          #wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
          #rpm -ivh epel-release-latest-7.noarch.rpm


2. Install Certbot


          #yum install certbot


Now Create your certificates by using certbot, In here I’m using certbot standalone plug-in to create my certificates
Note: this standalone plug-in along with certbot will work as temporary web server which connects to letsencrypt CA and validate your certificates. So it may requires to temporary use your web port (80)..


To check whether your web port is in use 
          #netstat -ntlp | grep ‘:80.*LISTEN’


if there is no output, you’re good to use the certbot with standalone plug-in 
          #certbot certonly –standalone –preferred-challenges http –http-01-port 80 -d london.mycompany.com -d  chicago.mycompany.com


At this point you may stop the haproxy server temporary.
            #systemctl stop haproxy


Now it will  prompt to insert your email and accept the license agreement, and will perform the http challenge.
After successful completion, you will prompt with a message as follow 

IMPORTANT NOTES:

 

 – Congratulations! Your certificate and chain have been saved at

 

   /etc/letsencrypt/live/xxxxx.com/fullchain.pem. Your cert

 

   will expire on xxxx-xx-xx. To obtain a new or tweaked version of

 

   this certificate in the future, simply run certbot again. To

 

 

   non-interactively renew *all* of your certificates, run “certbot
   renew” ~

 

After Successful completion it should create four files in  /etc/letsencrypt/live/<domain name>,

  1. cert.pem: Domain’s certificate
  2. chain.pem: Chain certificate of  Let’s Encrypt 
  3. fullchain.pem: Combined cert.pem and chain.pem file
  4. privkey.pem: Certificate’s private key


Now in order to use these on HAProxy you have to combine private key and full chain.
I will create a new directory on HAProxy directory and keep those file
          #mkdir -p /etc/haproxy/certs
          #domain=’iiswebsrv.com’ sudo -E bash -c ‘cat /etc/letsencrypt/live/$domain/fullchain.pem /etc/letsencrypt/live/$domain/privkey.pem > /etc/haproxy/certs/$domain.pem’

Auto Renewal

These certificates will expire after 90 days and certbot will automatically renew the certificates. 
In order to manage these keys specially for HAProxy, you may create a shell script to combine and move them to HAProxy’s certs directory, 
And you may create a cron job to execute these script accordingly.
 
Sample shell script 

 

#!/bin/bash
DOM=<your domain>.com

cd /etc/letsencrypt/live/$DOM
cat fullchain.pem privkey.pem > /etc/haproxy/certs/$DOM.pem
systemctl reload haproxy

 

You may grant execute permission to the shell script 
           #chmod u+x /path/to/your/schellcript.sh
 
Now configure the cron
          #crontab -e
 
add following lines (to execute the shell script on 1AM everyday)
         00 1 * * * /path/to/your/schellcript.sh
Now file appending and copping to HAProxy’s cert directory is done. At this point you may do some changes to you renewal config file which has already created with initial certificate creation.  
 
You can find this config file in “/etc/letsencrypt/renewal”, and you may change the “http01_port” parameter with you desired port  and save.
 

         #certbot renew –dry-run

Then on Certbot will listen on my port 83249 for the renewal challenge.

-Enjoy-

HAProxy

February 10, 2018 | Linux Tools, Proxies and Load balancing | 1 Comment

HAProxy implementation Case Study

This tutorial covers HAProxy Deployment on Firewall and
SELinux enabled Centos7 systems.
First of all lets get an overall idea about my situation.
I’ve bought a domain call mycompany.com so all of my  hosted sites should be followed by this main domain.
As an example, if someone look for london.mycompany.com he should
reach to London server, if someone look for chicago.mycompany.com he should
reach to Chicago server
So, I’ve created a Cloudflare account and point
mycompany.com to our public IP address and created two                 CNAME entries from Cloudflare by adding London and Chicago.
From the Cloudflare all the request to mycompany.com will
forward to our public address and HAProxy may read those requests
and Process them and forward them accordingly between two IIS servers.
Note that all HTTPs connection should terminated at HAProxy.  Please see my post HTTPS for HAProxy


In this chapter we will look in to Load balancing and ACL
based traffic routing between IIS web servers

As the first step I will add hosts entries for my hosts file
 vi /etc/hosts
 10.0.3.121 iiswebsrv01
 10.0.3.131 iiswebsrv02
You may ping and verify the connectivity between HAProxy
server and your web servers.
Download and Enable the EPEL Repositories and install the
HAProxy
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum -y install HAProxy
  
After Successful installation of HAProxy, you can start configuration
on HAProxy.
Prior to edit the configuration file its recommended to keep
a backup of existing HAProxy configuration file
cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg_bak
Now Let’s look at our HAProxy configurations
HAProxy configuration file contains four types sections
  1. Global Section which contains global configurations
  2. Default Section for default configurations
  3. Frontend sections which expose to Public to accepts the requests
  4. Backend sections which  define who to be should serve the requests which are forwarding from front end section.
 global
        log 127.0.0.1   local2                      #1
        maxconn 1024                                #2
        user haproxy                                #3
        group haproxy                               #4
        daemon                                      #5
        stats socket /var/run/haproxy.sock mode 600 level admin    #6        
 tune.ssl.default-dh-param 2048                             #7
 
1. In global section it is configured where to store our HAProxy logs, in here our HAProxy logs will be stored by using local rsyslog server
2. Maximum Connection count which is supposed accommodate
using my HAProxy Server
3. Define HAProxy user which is already created with the
installation
4. Define HAProxy group
5. State that HAProxy should run as a daemon process
6. In HAProxy you can monitor the performance by using status page or socket, this for socket usage.
7. Define the Maximum size of the temporary DHE Key for TLS
Now we are done with our global configurations…
It’s time to start our configurations on HAProxy Default
Configuration
In default section we configure the default parameter for
all frontend and backend sections
defaults
        log     global                        #1
        option  tcplog                        #2
        option  dontlognull                   #3
        retries 3                             #4
        option  redispatch                    #5
        maxconn 1024                          #6
        timeout connect 50000ms               #7
        timeout client 500000ms               #8
        timeout server 500000ms               #9
1. Define the log mode to use which we have already dud in Global configuration
2. option tcplog will logging will keep the logs on tcp (Layer 4) level.
         Note that you may also use httplog if you’re willing to log on http level
3. dontlognull will filter the  log entries, this will keep your logs clean (By default even a simple port probe will produce a log, due to that HAProxy in order to avoid these type of log entries you may use this option)
4. This will set the number of retries after a fail attempts to the server
5. If a server designated by a cookie and it is down, clients may stick to this because they cannot flush the cookie, so this client will not be able be to the access the particular service anymore. So, this will allow the HAProxy to break their persistence and redistribute them to a working server.
6. Define the maximum connection count
7. Set the maximum time to a client to wait for the response
8. Set maximum inactive time on the client side
9. Set maximum inactive time on the server side
Now our basic Configuration is done let’s start to
configuring the parameters for frontends and backends.
In frontend sections it will accept the traffic from public
entities and process them, and it will forward the traffic to relevant backend.
In following front end section, I will demonstrate how to read  HTTP headers and process them with basic ACLs and forward them to relevant
backend sections.
frontend http_handler
         bind *:80                                                                #1
         bind *:443 ssl crt /etc/haproxy/certs/hrms.itcstaging.com-0001.pem       #2
         mode http                                                                #3
         option httplog                                                           #4
         log global                                                               #5
         
                acl acl_london  hdr_beg(host) -i london                           #6
                acl acl_chicago hdr_beg(host) -i chicago                          #7
                use_backend be_london if acl_london                               #8
                use_backend be_chicago if acl_chicago                             #9
                default_backend be_welcome                                        #10
This frontend will accept all http and https request and
process them with a ACL.  
 
1,2 In order to accept the traffic from port 80 (http) and
443 (https), shall we bind both 80,443 ports to a front end. Note that for https traffic it is required to have a SSL certificate.
 
Here in this tutorial I’ve created a SSL certificate using let’s
encrypt (https://letsencrypt.org) (Please see my post HTTPs for HAProxy)
3 since our primary objective is to read those HTTP/HTTPs headers
and forward the traffic accordingly we may use ‘mode http’, if you use the TCP
mode instead you load balancing will be based on layer 4, if so we won’t be
able to read the HTTP header in our ACL
4 Here I have enable HTTP logging of HTTP/HTTPs Request
5 Add logs to the global syslog service
In HAProxy an ACL can define the “acl” keyword,
ACLs can be defined in either backend or fronted. (In our scenario ACL have to
be defined in the frontend section)
                acl
<Name of the ACL> <criterion> [flags][option] values
6,7 I’ve initiated two acls for my two sites one
london(acl_london) and one for chicago(acl_chicago), now as per the requirement
it’s required to read http headers and forward the traffic based on the
content of the http headers.
In here I’ve used hdr_beg criterion which will test the http
header with defined keyword. alternately you may use hdr(host)
 which will test against the exact
match of the header content.
Here with hdr_beg(host) I’ve use -i option ignore the case.
So, if there is any http request which contain london key
word will activate the ACL “acl_london” and if there is any http
request whoch contain chicago it will activate “acl_chicago”
Now we have defined the conditions for the ACLs, now we
should instruct HAProxy to what should happen if that particular ACL entry is
true
8,9 use_backend can be used to switch backends depends on
the ACL output
               
                use_backend
<desired backend> {if | unless} [Condition]
               
In our scenario if acl_london is true it should use the
london backend (be_london), if acl_chicago is true it should use the chicago
backend (be_chicago)
10. Now in practical scenarios, some HTTP requests may hit
our frontends but failed on the ACLs, which means our ACLs happens to unidentified
the which backend to use, on those kinds of scenarios we may use
default_backend option which is not compulsory here
Now traffic come to our frontends and test against the ACLs,
it’s time to define our backends to accommodate HTTP request and forward
them to desired destination
backend be_london
                balance leastcon                                                  #1
                redirect scheme https if !{ ssl_fc }                              #2          
                option forceclose                                                 #3
                option forwardfor                                                 #4
                stick match src                                                   #5
                stick-table type ip size 200k expire 30m                          #6
                mode http                                                         #7
                reqadd X-Forwarded-Proto: http                                   #8
                cookie SERVERID insert indirect nocache                           #9
                option httpchk GET /check.aspx?testsrv=londonsrv01:8080           #10
                http-check expect string 200 OK                                  #11
                server london_01 iiswebsrv01:94 cookie L01 check                  #12
                server london_02 iiswebsrv02:94 cookie L02 check                  #12

1 balance key word state the balancing which balancing algorithm
to use when HAProxy selecting the destination servers
               
                balance
<algorithms> [argument]
               
HAProxy proxy provides various balancing algorithms to balance
the load between the servers
  • leastconcon : Selects the server with the least number of connections–This is recommended for longer sessions. Servers in the same backend are also rotated in a round-robin fashion.
  • roundrobin : Round Robin selects servers in turns. This is the default algorithm.
  • source : This selects which server to use based on a hash of the source IP i.e. user’s IP address. This is one method to ensure that a user will connect to the same server.
2 Now for the security purposes I prefer only to use HTTPS. so in the backends, here we forcefully filter the traffic only to use HTTPs.
Note that In TCP mode, HAProxy doesn’t actually even
terminate SSL, it just passes the packets on to the backend.
For additional information, ssl_fc: Returns true when
the front connection was made via an SSL/TLS transport layer and is locally
deciphered.
4 This will enable X-Forwarding the HTTP connections.
                What is
X-Forwarding, HAProxy act as a revers proxy which we already know. when it comes to your server side, the server will only see the ip address of HAProxy
server as the client address which sometimes it may cause some issues. By using
X-Forwarding, HAProxy will append the original IP address of the client when
requests are sending to the server.
3 By default HAProxy operates in keep alive mode with the connection
and keep connection idle from both the Client and Server.
 Simply ” option
forceclose” will check if “Connection: close” header is already set
in each direction and will add the Connection close if not including headers
and will kill the connection. (Also, any “Connection” header
different from “close” will also be removed) 
5 stick match statement define a rule to extract the
stickiness criterion from an incoming request or connection.
6 This is to configure the sticky table. These stick
tables will keep learned data on the memory from the connection. Note that restarting the service will remove those sticky entries (To overcome this issue
you may implement HAProxy peering with secondary HAProxy server).  
               
7 mode http is optional since  we have already define it
on default Section .
8 In here we are adding a header to all HTTP request’s which
are passing through this backend (Header transformations only apply to traffic
which passes through HAProxy)
9 Adding Cookie values to  HTTP requests. This value will
be checked in incoming requests, and the first operational server possessing
the same value will be selected. In return, in cookie insertion or rewrite
modes, this value will be assigned to the cookie sent to the client.
10 Before forward the traffic to the destination servers it
is wise to check the availability of those servers using httpchk. It will point to “from where” HAProxy should get this information.
                Additionally,
I’ve created a separate sites on both of my chicago and london servers which
will give us an output saying “200 OK”, based on the readiness of this
content HAProxy will figure it out that particular destination server is ready
serve. (I’ve put this sample html script later on this tutorial)
               
11 Now HAProxy test previous readings from the httpchk
and test it
It’s time to us to define our backend servers. Back end
servers can define using “server”.
                server
<name> <server address>[:[port]] [param*]
               
12 Here in our configuration I’ve defined a name for
particular cookies from london_01 server.
The check
parameter will do the test based on our previous html script
And you may add the other Back End servers as well.

Now we are done with the configuration..

Once you complete the HAProxy configuration you may check the configurations by     

haproxy -f /etc/haproxy/haproxy.cfg -c
To restart the HAProxy

systemctl restart haproxy
You may fall in to some SELinux related issue, which some destination ports are not
allowed by SELinux in Such a scenario you may use following command,
semanage port --add --type http_port_t --proto tcp <port>
               
You may require to open firewall ports, to do that use

firewall-cmd --permanent --add-port=tcp
firewall-cmd --reload

Complete Configuration Sample

global
        log 127.0.0.1   local2
        maxconn 1024
        user haproxy
        group haproxy
        daemon
        stats socket /var/run/haproxy.sock mode 600 level admin         
  tune.ssl.default-dh-param 2048     

defaults
        log     global
        option  tcplog
        option  dontlognull
        retries 3
        option  redispatch
        maxconn 1024
        timeout connect 50000ms
        timeout client 500000ms
        timeout server 500000ms

###########################
#Front Ends Configurations#
###########################
frontend http_handler
 bind *:80
 bind *:443 ssl crt /etc/haproxy/certs/hrms.itcstaging.com-0001.pem
 mode http
 option httplog
        log global

 acl acl_london  hdr_beg(host) -i london        
 acl acl_chicago hdr_beg(host) -i chicago
 

 use_backend be_london if acl_london         
 use_backend be_chicago if acl_chicago         
 default_backend be_welcome     

###########################
#Back  Ends Configurations#
###########################
backend be_london
 balance leastcon           
 redirect scheme https if !{ ssl_fc }                                   
        option forceclose          
 option forwardfor          
        stick match src           
        stick-table type ip size 200k expire 30m    
        mode http            
        reqadd X-Forwarded-Proto: http       
        cookie SERVERID insert indirect nocache     
        option httpchk GET /check.aspx?testsrv=iiswebsrv01:8080 
        http-check expect string 200 OK      
        server london_01 iiswebsrv01:94 cookie L01 check  
 server london_02 iiswebsrv02:94 cookie L02 check  

backend be_chicago
 balance leastcon           
 redirect scheme https if !{ ssl_fc }                                   
        option forceclose          
 option forwardfor          
        stick match src           
        stick-table type ip size 200k expire 30m    
        mode http            
        reqadd X-Forwarded-Proto: http       
        cookie SERVERID insert indirect nocache     
        option httpchk GET /check.aspx?testsrv=iiswebsrv01:8080 
        http-check expect string 200 OK      
        server london_01 iiswebsrv01:94 cookie L01 check  
 server london_02 iiswebsrv02:94 cookie L02 check  

Sample HTTP check html Script

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
         <head>
             <title>
             Mediatools Check
             </title>
         </head>
         <body id="bodyID">
                200 OK
         </body>
</html>

Asterisk on Docker

August 25, 2017 | Linux Containers, Linux Tools, VoIP | No Comments

This Document covers asterisk basic installation on docker. Since till now there is no official asterisk image on Docker hub we will use Debian core to install the asterisk.

Prerequisites Linux host to install docker, Internet connectivity and docker account to download docker images.

1. Installing Docker (Ensure your Internet connectivity)

  • Centos 7

          #wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
#rpm -ivh epel-release-latest-7.noarch.rpm
#yum install docker

  •  Install Docker on RHEL and CentOS 6
         # yum install epel-release
# yum install docker-io

2. Start Docker

  • Centos 7

         # systemctl start docker
# systemctl status docker
# systemctl enable docker

  •  On RHEL/CentOS 6

         # service docker start
# service docker status
# chkconfig docker on


Our Asterisk PBX will reside on Debain, So first we must set our Debian container to install asterisk. (Please ensure that you docker is up running without any issue, If you wish to verify you docker engine please use hello world application “# docker run hello-world” )
If everything went well as we expected, you will see something like this.

 3. Pull Debian Image to Docker

         # docker pull debian


This might take some time.

4. Now Lets run our New Debian container using pulled image

First we shall get the Debian image ID by using

            # docker images
You will get someting like this (This will show your all docker images),

Now we shall Start our container using Our Debian image (My Debian image ID appears to be a20fd0d59cf1 )

       # docker run -it –name=<Container Name> –network=host <Image ID>

I’ve used -i and -t option to Keep STDIN open even when container is detached :i and to allocate  pseudo-TTY :t. Plus I’ve used –network option to connect my container with my host network.

After creating your Debian container you will be inside the Container.

5. Install Asterisk

Update your Debain distribution

       # apt-get update
Install asterisk

        # apt-get -y install asterisk
This will take some time to install the packages.

Now After completion of the installation, we might configure the asterisk.

6. Asterisk Configuration

Configure the asterisk RTP Port Limitation.

       #vim /etc/asterisk/rtp.conf

(Use #apt-get install vim-nox To Install VIM)

Change rtpstart and rtpend parameters.

Save and Exit
This will help us wo bind the ports when we running our Asterisk container.
Now We shall start the asterisk.
 

       # /etc/init.d/asterisk start
Use # rasterisk to check if you can  access the Asterisk CLI.

Type exit and Hit Enter to exit Asterisk CLI

Now we shall commit our changes to keep our container configuration.

7. Committing the Container configuration

use Ctrl + p + q to detach from the container
Now issue docker ps  command to see running containers.

        # docker commit -m “<Commit Message>” -a “<author’s name>” <ContainerID or Name to commit> <Repository>:<tag>

Now you can check your committed Docker images by using # docker images

8. Run our Committed Image

        docker run -itd –name=PBX-Asterisk –network=host -p 5060:5060/tcp -p 5060:5060/udp -p 10010:10010/udp -p 10011:10011/udp -p 10012:10012/udp -p 10013:10013/udp -p 10014:10014/udp -p 10015:10015/udp -p 10016:10016/udp -p 10017:10017/udp -p 10018:10018/udp -p 10019:10019/udp -p 10020:10020/udp <Commited Docker ImageID to run>


 I’ve used the –name option to assign a name to my container, and use -p to map the container port with host port. 

9. Configure the sip peers

Lets jump in to our asterisk container
You can use

        # docker exec -it <Your Container ID> bash

or

         # docker attach <Your Container ID>

 Let’s configure our sip peers in # vim /etc/asterisk/sip.conf

       [100]
       secrete=abc123
       context=home
       type=friend
       allow=ulaw,alaw
       host=dynamic

10. Dialplan configuration

11. Complete Asterisk configuration

Now we shall start the asterisk if we already haven’t,

        # service asterisk start


Jump to Asterisk CLI

         # rasterisk
Reload the sip and dialplans

          localhost*CLI> sip reload
localhost*CLI> dialplan reload

You can connect youe sip phones now…..

Note that, If you have iptables service aka firewalls up on your host machine you may need to do some changes accordance.

FreePBX-Installation

March 26, 2017 | Linux Administration, Linux Tools, VoIP | No Comments

FreePBX-Installation

 

1. Pre-installation

In order to setup call center server first we have to confirm that our system is full filled the minimum requirements. This asterisk deployment is based on RedHat distribution aka CentOS.  To full-fill the above requirement we are going to setup asterisk 11 on CentOS 6.5 (x64).

1.2 CentOS 6.5×64 installation 

It is recommended to install CentOS 6.5×64 minimum version and manually install all the other package as our requirement. 
 
At the beginning it recommended to configure the logical disk drives aka Raid. 
 
Note that some of the server-rigs will not compatible to centos 6.5×64, most of the time it’s because the particular server’s Raid drivers might not be found in centos 6.5×64 disk. In such scenario please follow the below instruction.
First we have to download the Raid driver from relevant vendor. (If it’s HP you will find somewhat like this hpvsa-X.X.X-X.rhel6u.5x86_64.dd).
 
Note that if the driver has compressed with gzip(.gz) it is recommended to extract by using “tar” in a Linux platform.
Use your Fat32 formatted usb stick and copy those extracted driver (.dd) files.
Now boot your server with centos 6.5×64 and plug your USB stick during the boot time.  At the installation menu, select the installation method and hit “ESC” key to receive the “boot:” prompt. In the boot prompt enter following command 
 

                linux dd blacklist=ahci

 
and then let your system to boot (Don’t reboot the system).
 
And during the installation you will be prompted a window to select the Raid driver and select the relevant driver. On successful driver installation you will be able to see your Logical (Raid driver).
 
And install the centos 6.5×64 without customize any package.
 
Note that it is recommended to customize your Logical disk in order to accommodate root user to enough space.  

2 Asterisks Installation

2.2 Disable SELinux

First You have to disable SELinux
 

             # sed -i ‘s/(^SELINUX=).*/SELINUX=disabled/’ /etc/sysconfig/selinux

Afterwards to affect the system changes restart the PC.
 

           # init 6

 
Now check selinux stats by using
 

          # sestatus

 
 
 
Or you can confirm it on “/etc/sysconfig/selinux” file
 
 

2.3 Network Configuration 

          # vim /etc/sysconfig/network-scripts/ifcfg-<netowrk card>`

   Note that network card name can be found using

         # ifconfig

 
This an example network scripts for network card called “eth0” assign with the IP address “192.168.1.250”.
Make sure that your changes only limited to following parameters,

ONBOOT 
BOOTPROTO 
IPADDR 
NETMASK 
GATEWAY 
DNS1 
DNS2

 
You are always welcome to use `[root@localhost ~]# setup` in order to perform following configurations.

2.4 Update the System

Then you have to update your system.
 
Make sure that internet connectivity of the server is alive.
 
Now using yum application manger lets update the server,
 

            # yum -y update

These Updating processes will take a while.

         # yum groupinstall core
         # yum groupinstall base

 

2.5 Install essential dependencies 

In order to deploy the system, we have to install some additional packages aka dependencies.  
 

           # yum install gcc gcc-c++ lynx bison mysql-devel mysql-server php php-mysql php-pear php-mbstring tftp-server httpd make ncurses-devel libtermcap-devel sendmail sendmail-cf caching-nameserver sox newt-devel libxml2-devel libtiff-devel audiofile-devel gtk2-devel subversion kernel-devel git subversion kernel-devel php-process crontabs cronie cronie-anacron wget vim php-xml uuid-devel libtool sqlite-devel unixODBC mysql-connector-odbc

2.6 Disabling Default IP tables 

Then you have to disable default IP tables and you may enable them again after the installation.
 

 

            chkconfig –level 0123456 iptables off`

 

2.7 Configurations on MySQL and Apache

It is required MySQL and Apache servers to perform Both asterisk and FreePBX operations and it’s recommended if MySQL and Apache services start at the server boot time.
 
          chkconfig –level 345 mysqld on

 

          chkconfig –level 345 Apache on

 

 
Let’s bring up the Both Apache and MySQL server
 
          service mysqld start

 

          service httpd start

 

2.8 PearDB Installation

PearDB is a database abstraction library which allows to connect to different kinds of databases such as    PostgreSQL, MySQL using a consistent API.
 
             # pear channel-update pear.php.net
   # pear channel-update pear.php.net
You may found some warnings saying “WARNING: “pear/DB” is deprecated in favor of “pear/MDB2″”, You can just ignore them.
 
It is preferred to reboot the system before continue further.
 

         # init 6

2.9 Setup the Asterisk user

Then it is required add user to the system  with relevant permission to perform asterisk activities.
 
          # adduser asterisk -M -c “Asterisk User”
 

2.10 Download Asterisk Source Files

 
Use following links to download asterisk sources files. 
 
Note that it is preferred  to download the following files to “/usr/src/”.

       # cd /usr/src
       # wgethttp://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz
       # wget http://downloads.asterisk.org/pub/telephony/libpri/libpri-current.tar.gz
       # wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-11-current.tar.gz
       # git clone https://github.com/akheron/jansson.git
       # wget http://www.pjsip.org/release/2.2.1/pjproject-2.2.1.tar.bz2

2.11 LibPRI and DAHDI

        # cd /usr/src
        # tar xvfz dahdi-linux-complete-current.tar.gz
        # tar xvfz libpri-current.tar.gz
        # rm -f dahdi-linux-complete-current.tar.gz libpri-current.tar.gz
        # cd dahdi-linux-complete-…… Folder……
        # make all
        # make install
        # make config
        # cd /usr/src/libpri-……Folder……
        # make
        # make install

 
These modules are recommended to install even those modules required only if you are using physical devices.
 

2.12 Pjproject Setup

 
pjproject is a collection of utilities, libraries for building and testing SIP based applications.
 

         # cd /usr/src`
         # tar -xjvf pjproject-2.2.1.tar.bz2`
         # cd pjproject-2.2.1`
         # CFLAGS=’-DPJ_HAS_IPV6=1′ ./configure –prefix=/usr –enable-shared –disable-sound –disable-resample –disable-video –disable-opencore-amr –libdir=/usr/lib64`
         # make dep`
         # make`
         # make install`

 

2.13 Jansson Setup 

Jansson is a C library for encoding, decoding and manipulating JSON (JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming) data. 
 

         # cd /usr/src/jansson
         # autoreconf -i
         #./configure –libdir=/usr/lib64
         # make
         # make install

2.14 Asterisk Setup

        # cd /usr/src
        # tar xvfz asterisk-13-current.tar.gz
        # rm -f asterisk-13-current.tar.gz
        # cd asterisk-…..Folder….
        # contrib/scripts/install_prereq install
        #./configure –libdir=/usr/lib64
        # contrib/scripts/get_mp3_source.sh
        #make menuselect

 
Now you must be prompted with “Asterisk Module and Build Option Selection”.
 
 
 
Add mp3 format support if you’re required too compatible mp3 formats on your asterisk server and then press “Save & Exit”.
Finally let’s complete the asterisk installation process.
 

        # make
        # make install
        # make config
        # ldconfig

 
You may need to install Asterisk-Extra-Sound
 

           # mkdir -p /var/lib/asterisk/sounds
           # cd /var/lib/asterisk/sounds
           # wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-wav-current.tar.gz
          # tar xfz asterisk-extra-sounds-en-wav-current.tar.gz
          # rm -f asterisk-extra-sounds-en-wav-current.tar.gz
          # wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-g722-current.tar.gz
         # tar xfz asterisk-extra-sounds-en-g722-current.tar.gz
         # rm -f asterisk-extra-sounds-en-g722-current.tar.gz

3 FreePBX Installation

 
Note that asterisk is our actual PBX aka core switch, while FreePDB can defined as a web-based GUI and configuration file writer which will write asterisk dial planes and configuration for you.
 

3.1 Download FreePBX Source Files

        # cd /usr/src

        # wget http://mirror.freepbx.org/modules/packages/freepbx/freepbx-12.0-latest.tgz
        #tar vxfz freepbx-12-latest.tgz

 

3.2 Setup Relevant permission on Asterisk

It is required to setup couple of ownership permissions as follows.

 

         #chown asterisk. /var/run/asterisk
         #chown -R asterisk. /etc/asterisk
         #chown -R asterisk. /var/{lib,log,spool}/asterisk
         #chown -R asterisk. /usr/lib/asterisk
         #chown -R asterisk. /usr/lib64/asterisk
         #mkdir /var/www/html
         #chown -R asterisk. /var/www/

3.3 Configuration on Apache Server

FreePBX use Apache web server to provide web-based GUI, Following modifications are essential on Apache server.

 

            #sed -i ‘s/(^upload_max_filesize = ).*/120M/’ /etc/php.ini
            #cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf_orig
           #1 asterisk/’ /etc/httpd/conf/httpd.conf
           #service httpd restart

3.4 Configuration on MySQL Server

 
Asterisk uses MySQL database engine to perform its database activities, These Following modifications are essential on MySQL database.
 

          #cd /usr/src/freepbx
          #export ASTERISK_DB_PW=amp109
          #mysqladmin -u root create asterisk
          #mysqladmin -u root create asteriskcdrdb

 
Now It’s required Grant relevant permissions on asterisk database.

 

         #mysql -u root -e “GRANT ALL PRIVILEGES ON asterisk.* TO asteriskuser@localhost IDENTIFIED BY ‘${ASTERISK_DB_PW}’;”
        #mysql -u root -e “GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO asteriskuser@localhost IDENTIFIED BY ‘${ASTERISK_DB_PW}’;”
        #mysql -u root -e “flush privileges;”

3.5 Finalize the FreePBX installation

        #cd /usr/src/freepbx
         #./start_asterisk start
         #./install_amp –installdb –username=asteriskuser –password=${ASTERISK_DB_PW}
         #amportal chown
         #amportal a ma installall
         #amportal a reload
         #amportal a ma refreshsignatures
         #amportal chown

Let’s Start the FreePBX
 

          #ln -s /var/lib/asterisk/moh /var/lib/asterisk/mohmp3
          #amportal restart

Note that amportal is the Linux command which is use to controls FreePBX by using Linux command prompt.
 
 
 
 
 
 
 
 
 
 
 

Reference

Nagy, A. (2014). Version 12.0 Installation – FreePBX OpenSource Project – Documentation. [online] Wiki.freepbx.org. Available at: https://wiki.freepbx.org/display/FOP/Version+12.0+Installation [Accessed 7 Mar. 2016].

Jordan, M. (2019). Asterisk 11 Documentation – Asterisk Project – Asterisk Project Wiki. [online] Wiki.asterisk.org. Available at: https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+Documentation [Accessed 3 Mar. 2014].

Install and configure SQUID Proxy Server

Introduction

A proxy server is a server which acts as an intermediary for clients seeking resources from other servers such as Web servers, File servers… etc. Whenever a client requests resources, the proxy server will evaluate the request as a way to simplify and control its complexity. Today, most proxies are web proxies, facilitating access to content on the World Wide Web and providing anonymity.

Use of Proxy servers

  • Firewall and network data filtering support
  • Data caching
  • Accessing services anonymously

Overview

For the demonstration purpose, Cent OS 6.5 and Fedora 17 are installed in VMWare Workstation (9.0.1 build-894247).

Fedora 17 – Configured as a client machine.

Cent OS 6.5 – Configured as a router and Proxy server was installed and configured there.

Overview Diagram

Network Diagram – Description

After installation of OS s in VMWare. Following IP addresses were assigned to network interfaces accordingly.

Fedora Client

Eth0 – 192.168.2.2 (LAN 111)

Cent OS – Server

Eth1 – 192.168.2.1 (LAN 111)

Eth0 – 192.168.1.12 (This will be changed as IP addresses assigned through DHCP)

Proxy server port – 3128

Configurations

Cent OS 6.5 – Interfaces Details (After configuration of network addresses)

Fedora 17 – Interfaces Details (After configuration of network addresses)

Configuring Cent-OS 6.5 as a Router.

When Fedora client requesting web traffic through Cent OS machine, it should be able to redirect web traffic towards the Access point (192.168.1.1). So the following steps were done to fulfil the requirement.

1) To send packets through IP forwarding following command was used.

2) Enabling NAT on the server

3) Set up Fedora client to access AP through Cent OS, had to do some modifications to the IP-tables. For it following commands were used.

Now it is all configured to access the internet via Cent OS for Fedora client.

Installing/Configuring Squid

In Cent OS machine squid proxy server was installed using following command.

Changing the squid.conf file to work as a transparent proxy.

For newer versions of squid proxy server to enable transparent proxy, in squid.conf file word “intercept” should be given as follows

Allowing HTTP traffic through squid proxy server. Uncomment these lines as following

To allow Fedora client’s network (192.168.2.0/24) for accessing squid proxy server. (Highlighted the line which was added by myself)

After saving squid.conf file started the squid service using the following command.

It’s all configured properly but Fedora client still doesn’t access the internet through the proxy server. It is needed to access port 3128 which is for the proxy server by Fedora client. For the requirement following modification was done to the IP table.

NAT table changed as following after the modifications.

To verify that fedora client is using squid proxy server following command was used.

If logfile is filled like above, It means that Fedora client access internet via Proxy server.

IF not Fedora client doesn’t access the internet via a Proxy server. (If the log file is empty)

Caching

For enable caching squid.conf file was modified as follows.

That’s it 🙂

 

RSYNC

June 22, 2016 | Linux Administration, Linux Tools | No Comments

RSYNC

is one of the most popular File Copying/Synchronizing service among Linux people. Its synchronizing while copping and consume Less network resources for its operations.
 
CAUTION!!!! Miss use may cause original data overwrite or
deletion.
As an example, here in iPhonik (iPhonik was formed as a company in the business of developing an
Unified Communication Solution product and related services.
) we use rsync
to take realtime backups and duplicate them on the redundant servers. Call recording which stores
in the real-time server will be synchronized/ copied to the redundant server (We
are using NFS as the file sharing mechanism share-directory-between-two-server-nfs ).

 How to USE

Most of the time your Linux distributions comes with the
installed rsync service but if you don’t have installed rsync on your Linux
distribution,

Debian distributions

apt-get install rsync

RedHat distributions

yum install rsync

Now if you
wish to use rsync with the remote host

rsync -avz -e ssh remotepeers@remotedomain:/remotepeers/dirA/dirB/ /local-this-user/dirE/dirF

If you wish to use
rsync through server

First you have to setup
rsync as a daemon process, to do that find the /etc/xinetd.con file
and add following lines below the very last line of the file,

rsync stream tcp nowait root
/usr/bin/rsync rsync –daemon
Let’s create the rsync configuration file as “/etc/rsyncd.conf” And add following configuration,
max connections = 1 log file = /var/log/rsync.log timeout = 300 [usersfiles] comment = Rsync user’s cache path = /usr/local/usersfiles read only = no list = yes uid = nobody gid = nogroup #auth users = user list = yes hosts allow = 127.0.0.0/8 192.168.1.0/24 secrets file = /etc/rsyncd.sec
Save and Exit
By commenting very last two line
will allow anonymous access.
Afterward let’s create the /etc/rsyncd.sec
file and add user name and
passwords for the allowed users (if you didn’t allow anonymous access).
To start the syncronisation,
rsync -avz
rsync://your_ip-addresses_or_domain/public

Click here for rsync manual (Man page).

Service-Start-Linux

April 23, 2016 | Linux Administration, Linux Tools | No Comments

Service-Start-Linux

Click Here to Download zip

Author ::krishees@gmail.com      
Features,     
Check the status of the given services (as a command line argument)  
and if that particular service is in down status./checksrv.sh <service> 
program can turn up the particular service.    
======================================================================= 
pattern->        
./checksrv.sh <service-1> <service-2>.....<service-n>   
ex-> for httpd and mysqld     
./checksrv.sh httpd mysqld     
======================================================================= 
Usage->   
Using crontab (crontab -e)      
* * * * *  ./checksrv.sh <service>     
Check the status of the service every 60 seconds and if the particular 
service not up then the ./checksrv.sh will bring up the particular  
services          
------------------------------------------------------------------------
Using inittab (/etc/inittab)      
Check the status of a service after particular run-level reset. After  
particular run-level change and if particular service is not up then    
 ./checksrv.sh will bring up  the particular services    
 
 
#./checksrv.sh
#!/bin/bash
echo "   ======================================================================= +   Author ::krishees@gmail.com +   Features, +   Check the status of the given services (as a command line argument) +   and if that particular service is in down status./checksrv.sh <service> +   program can turn up the particular service. +   ======================================================================= +   pattern-> +   ./checksrv.sh <service-1> <service-2>.....<service-n> +   ex-> for httpd and mysqld +   ./checksrv.sh httpd mysqld +   ======================================================================= +   Usage-> +   Using crontab (crontab -e) +   * * * * * ./checksrv.sh <service> +   Check the status of the service every 60 seconds and if the particular +   service not up then the ./checksrv.sh will bring up the particular +   services +   ------------------------------------------------------------------------+   Using inittab (/etc/inittab) +   Check the status of a service after particular run-level reset. After +   particular run-level change and if particular service is not up then +   ./checksrv.sh will bring up the particular services +   ======================================================================= +   "   if [ "$#" = 0 ]   then   echo "Usage $0 <service>"   exit 1   fi       for i;do   service=$i   is_running=`ps aux | grep -v grep| grep -v "$0" | grep $service| wc -l | awk '{print $1}'`   if [ $is_running != "0" ] ;   then   echo "Nothing to do!!! $service Service is already up and running...."   else   echo   initd=`ls /etc/init.d/ | grep $service | wc -l | awk '{ print $i }'`   if [ $initd = "1" ];   then   startup=`ls /etc/init.d/ | grep $service`   echo "   =======================================================================   $i   ======================================================================="   echo "Waiting for service $i..."   /etc/init.d/${startup} start   else   echo "$i No such a service!!!"   fi   fi   done

Share-A-Directory-between-two-server-NFS

Please grant the relevant permission on the shell scripts
./client_Export.sh
  Takes three argument as follows

    1. server ip address to be exported

    2. client directory which should be exported to the particular server

    3. options aka permission for the expoted folder

                    rw: This option allows the client server to both read and write within the shared directory

                    sync: Sync confirms requests to the shared directory only once the changes have been committed.

                    no_subtree_check: This option prevents the subtree checking. When a shared directory is the subdirectory of a larger filesystem, nfs performs scans of every directory above it, in order to verify its permissions and details. Disabling the subtree check may increase the reliability of NFS, but reduce security.

                    no_root_squash: This phrase allows root to connect to the designated directory
    Eg:-:
      [root@localhost ~]# ./clint_Export.sh 192.168.1.78 /home/cli rw,sync,no_root_squash,no_subtree_check 
./server_Mount.sh
  Takes three argument as follows

    1. client (Provider of the Shared file) ip address 

    2. client directory which has exported to the server

    3. server directory which client's directory to be mounted

      Eg:-
       [root@localhost ~]# ./server_Mount.sh 192.168.1.78 /home/cli /home/cliatserver

client_Export.sh

#!/bin/sh
 echo Author krishan thisera @iPhonik.com
 
 
 
if [ "$#" != 3 ]
 
then
 
echo
 
echo "Usage $0 <Where to export:ServerIP> <What should export:Exporting Dirctory> <Set permission>"
 
echo "Please reffer : https://github.com/krishanthisera/Share-A-Directory-between-two-server-NFS"
 
echo
 
exit 1
 
fi
 
 
 
ipaddr=$1
 
dir=$2
 
opt=$3
 
echo "Checking nfs-utils"
 
if ! rpm -qa | grep -qw nfs-utils; then
 
echo "Installing nfs-utils"
 
yum install nfs-utils
 
else
 
echo "nfs-utils Installed. Nothing to DO"
 
fi
 
 
 
echo "Checking nfs-utils-lib"
 
if ! rpm -qa | grep -qw nfs-utils-lib; then
 
echo "Installing nfs-utils"
 
yum install nfs-utils-lib
 
else
 
echo "nfs-utils-lib Installed. Nothing to DO"
 
fi
 
 
 
chkconfig --levels 235 nfs on
 
/etc/init.d/nfs start
 
 
 
if [ -d "$dir" ]; then
 
echo "$dir Found"
 
else
 
echo "Creating a new directory.."
 
mkdir "$dir"
 
chown 65534:65534 "$dir"
 
chmod 777 "$dir"
 
echo "Directory created.."
 
fi
 
echo "Updating Export Script..."
 
echo "$dir" " " " " "$ipaddr""("$opt")" >> /etc/exports
 
exportfs -a
 
echo "Export Script Updated..." 

#!/bin/sh
 
if [ "$#" != 3 ]
 
then
 
echo
 
echo "Usage $0 <What is the source(Mount From):Clientip> <What is to mount:What is the client directory to be mount> <Where to Mount>"
 
echo "Please reffer : https://github.com/krishanthisera/Share-A-Directory-between-two-server-NFS"
 
echo
 
exit 1
 
fi
 
 
 
 
 
echo Author krishan thisera @iPhonik.com
 
ipaddr=$1
 
clidir=$2
 
srvdir=$3
 
echo "Checking nfs-utils"
 
if ! rpm -qa | grep -qw nfs-utils; then
 
echo "Installing nfs-utils"
 
yum install nfs-utils
 
else
 
echo "nfs-utils Installed. Nothing to DO"
 
fi
 
 
 
echo "Checking nfs-utils-lib"
 
if ! rpm -qa | grep -qw nfs-utils-lib; then
 
echo "Installing nfs-utils"
 
yum install nfs-utils-lib
 
else
 
echo "nfs-utils-lib Installed. Nothing to DO"
 
fi
 
 
 
chkconfig --levels 235 nfs on
 
/etc/init.d/nfs start
 
 
 
if [ -d "$srvdir" ]; then
 
echo "$srvdir Found"
 
else
 
echo "Creating a new directory.."
 
mkdir -p "$srvdir"
 
chown 65534:65534 "$srvdir"
 
chmod 777 "$srvdir"
 
echo "Directory created.."
 
fi
 
 
 
echo "Mounting $clidir in $srvdir"
 
mount "$ipaddr"":""$clidir" """$srvdir"
 
echo "Mounted $clidir to $srvdir"
 
df -h

How-to-Encrypt-a-shell-script
If you’re really concerning about the privacy of your shell scripts(Source),
I have use Ubuntu 14.04 server with the root Privilage. The source of the program ‘SCH’ which I’m using here is from
    http://www.datsi.fi.upm.es/
At first lets download some packeges which required to run our shell encryption program
You will need to download gcc compilers
    root@ubuntu:/usr/src# apt-get install gcc
You will need to install ‘make’ utility if it required (Depend on your system)
    root@ubuntu:/usr/src# apt-get install make
After that lets download our encryption program/ source [from http://www.datsi.fi.upm.es/]
Or you can download the ‘SCH’ source file which I’ve attached to this repository from from http://www.datsi.fi.upm.es/
    root@ubuntu:/usr/src# wget http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.7.tgz
Lets extract the ‘.tgz’ file
    root@ubuntu:/usr/src# tar xvf shc-3.8.7.tgz
    shc-3.8.7/CHANGES
    shc-3.8.7/Copying
    shc-3.8.7/Makefile
    shc-3.8.7/match
    shc-3.8.7/pru.sh
    shc-3.8.7/shc-3.8.7.c
    shc-3.8.7/shc.1
    shc-3.8.7/shc.README
    shc-3.8.7/shc.c
    shc-3.8.7/shc.html
    shc-3.8.7/test.bash
    shc-3.8.7/test.csh
    shc-3.8.7/test.ksh
Let jump in to the ‘shc’ source folder
    root@ubuntu:/usr/src# cd shc-3.8.7
In here I’m going to encrypt a shell script in the
    /home/encrypt
Let’s look inside the Shell script
    vim /home/encrypt/checksrv.sh
alt tag
Now lets Encrypt our Shell file Note that you always welcome to change password file in the shc-3.8.7 as you desire.
    root@ubuntu:/usr/src/shc-3.8.7# ./shc -f /home/encrypt/checksrv.sh
There will be two additional files
    root@ubuntu:/usr/src/shc-3.8.7# ls  /home/encrypt/
    checksrv.sh  checksrv.sh.x  checksrv.sh.x.c
‘checksrv.sh’ is our original (Unencrypted) shell source ‘checksrv.sh.x’ is the Encrypted Shell source ‘checksrv.sh.x.c’ c files was created in order to perform encryption
Lets check on our encrypted source file
    root@ubuntu:/usr/src/shc-3.8.7# vim  /home/encrypt/checksrv.sh.x
alt tag
Now you can see some binary stuffs instead of the plain shell text.
Now you can share the ‘.sh.x’ so your source will be hidden