Tuesday, April 28, 2015

SSH Tunnel – Port Forwarding With SSH

SSH has a huge number of features, SSH Tunnel being just one of them. SSH Tunnel is a secure connection between two machines and is often refered to as “SSH Tunneling” or also “Port Forwarding”.

Using the “ssh” command we can bind a desired port on a local machine to a desired port on a remote machine. This creates an encrypted SSH Tunnel between these machines and enables direct communication via localhost socket address. We can use SSH Tunnel to secure an insecure connection or to bypass different firewall restrictions.



Before we create our first SSH Tunnel check that you can run “ssh” command on your system. If you are running CentOS 6 minimal then you probably need to install openssh-clients package (Ubuntu users need to install openssh-client package).

SSH Tunnel

There are three types of Port Forwarding and thus three ways of using an SSH Tunnel:

  • Local Port Forwarding (enables access from local socket address via intermediate SSH server to a destination socket address)
  • Remote Port Forwarding (enables access from remote location via intermediate SSH server socket address to a localsocket address)
  • Dynamic Port Forwarding (SOCKS Proxy Server – NOT COVERED IN DETAIL IN THIS HOW TO!)

I use “SSH Tunneling” (Local Port Forwarding) on a daily basis since an environment from a customer I am working for, is designed in a way I can only access Workstation linux server on SSH port 22. All of the other infrastructure machines are only accessible from this Workstation, so using “SSH Tunneling” is the best way to go, to directly access different services.
SSH Tunnel – Port Forwarding with SSH

SSH Tunnel – Local Port Forwarding

Local Port Forwarding lets you connect from a local machine to a remote machine even if you do not have direct access to this remote machine from your local environment. In order for this to work, you need to have SSH access to an intermediate machine, which of course has access to the remote machine you want to connect to. The intermediate machine can reside in your local network and be subject to a different firewall policy or be outside of your local network.

Example #1:

We have SSH access on port 22 to a Workstation machine (user: wsuser, hostname: workstation). Behind the Workstation machine is an Application server (hostname: appserver) running Apache Tomcat on port 8080.We can not directly access Apache Tomcat administrator webpage on port 8080 from our Local machine, but Tomcat webpage port 8080 is accessible from Workstation machine thus we can create an SSH Tunnel and forward local port 8080 from our Local machine via Workstation to the Application server.

We can do this by running the following command on my Local machine:

ssh -f wsuser@workstation -L 8080:appserver:8080 -N


After authenticating to Workstation SSH server the connection is established and Apache Tomcat administration webpage is accessible when we open a web browser on our Local machine and point it to http://localhost:8080

Example #2:

Let’s say the situation is the same as in Example #1 but with one difference – there is also a firewall between Workstation (user: wsuser, hostname: workstation) and Application server (user: appuser, hostname: appserver) which only allows SSH access on port 22 from Workstation to Application server. This means Workstation can not directly access Apache Tomcat on port 8080.

There is still a way we can access Apache Tomcat administration webpage from our Local machine, but we need to make 2 hops via SSH.

1.
SSH to Workstation machine:
ssh wsuser@workstation

2.
When connected to Workstation machine, forward port 8080 via SSH to the Application server:
ssh -f appuser@appserver -L 8080:localhost:8080 -N

3.
Next we need to forward port 8080 via SSH from our Local machine to Workstation:
ssh -f wsuser@workstation -L 8080:localhost:8080 -N

Voila, Apache Tomcat administration webpage is accessible if i open up a web browser on my Local machine and point it to http://localhost:8080


SSH Tunnel – Remote Port Forwarding

Remote Port Forwarding works the other way around like the Local Port Forwarding. With Local Port Forwarding we enable access from our local machine via intermediate machine with SSH Server to a remote machine and with Remote Port Forwarding we enable access from a remote machine via intermediate machine with SSH server to our local machine. Of course for this to work we need to have SSH access to the intermediate machine. Remote Port Forwarding comes useful when we do not have Router administration rights so we can not configure port forwarding on a Router level. SSH Tunnel Remote Port forwarding does the same trick.

Before we can start Remote Port Forwarding we must reconfigure SSH server on an intermediate machine to accept it. We must edit “/etc/ssh/sshd_config” and uncomment and change to “yes” the following option:
GatewayPorts yes

of course followed by a SSH service restart!

Example #1:

We are running Apache Tomcat on our Local machine on port 8080. We want our friend, not from our local network, to access ourApache Tomcat administration webpage on port 8080 and help us configure something or deploy a new application. Thank god we have a Webserver (user: myuser, hostname: webserver) hosting some webpage accessible from the internet and also accessible via SSH from our local network. We will configure a Remote Port Forwarding and enable our friend to access the Apache Tomcat administration webpage we are running on our Local machine via Webserver.

We can do this by running the following command:
ssh -f myuser@webserver -R 8080:localhost:8080 -N

Voila, we can now tell our friend to access Webserver on port 8080 and Apache Tomcat administration webpage running on our Local machine will open up to him.
As we can see the only difference when using Remote Port Forward is the syntax change from “-L” to “-R” option.

SSH Tunnel – Dynamic Port Forwarding

Dynamic Port Forwarding will turn your machine into a SOCKS Proxy. SOCKS Proxy can proxy all requests through the network or the internet, but programs usually must be configured to use the SOCKS proxy. SOCKS proxy can be started with the following command:

ssh -C -D 1080 localmachine

where 
the -C options enables compression, -D option specifies dynamic port 
forwarding and 1080 is the standard SOCKS Proxy port. The next step 
would be to reconfigure your web browser to use 127.0.0.1 on port 1080 as a SOCKS Proxy.

Using Dynamic Port Forwarding and configuring your browser to use local SOCKS Proxy will encrypt all traffic visited from your web browser and make your connections secure.

SSH Tunnel – GeekPeek Tips

  • If you are running SSH server on a non-default port, you need to specify your port when running “ssh” command with the “-p” option
ssh -f wsuser@workstation -p 22222 -L 8080:appserver:8080 -N
  • Double check the ports that are already used on the intermediate machine before doing Local or Remote Port Forwarding. You can use netstat command and grep the port you want to forward
netstat -anp |grep 8080
  • Do not forget to reconfigure SSH server before trying Remote Port Forwarding and restarting SSH server
GatewayPorts yes
  • The “-f” option requests SSH to go to backgrouns and “-N” option tells it not to execute a remote command. If you do not want the SSH to go into background just remove the “-f” and “-N” option
  • Make sure your IPTables configuration is compatible with Port Forwarding you configured!

Thursday, April 23, 2015

How to Configure Linux Cluster with 2 Nodes on RedHat and CentOS

In an active-standby Linux cluster configuration, all the critical services including IP, filesystem will failover from one node to another node in the cluster.
This tutorials explains in detail on how to create and configure two node redhat cluster using command line utilities.
The following are the high-level steps involved in configuring Linux cluster on Redhat or CentOS:

  • Install and start RICCI cluster service
  • Create cluster on active node
  • Add a node to cluster
  • Add fencing to cluster
  • Configure failover domain
  • Add resources to cluster
  • Sync cluster configuration across nodes
  • Start the cluster
  • Verify failover by shutting down an active node
Red Hat Cluster

1. Required Cluster Packages

First make sure the following cluster packages are installed. If you don’t have these packages install them using yum command.

[root@rh1 ~]# rpm -qa | egrep -i "ricci|luci|cluster|ccs|cman"
modcluster-0.16.2-28.el6.x86_64
luci-0.26.0-48.el6.x86_64
ccs-0.16.2-69.el6.x86_64
ricci-0.16.2-69.el6.x86_64
cman-3.0.12.1-59.el6.x86_64
clusterlib-3.0.12.1-59.el6.x86_64

2. Start RICCI service and Assign Password

Next, start ricci service on both the nodes.
[root@rh1 ~]# service ricci start
Starting oddjobd:                                          [  OK  ]
generating SSL certificates...  done
Generating NSS database...  done
Starting ricci:                                            [  OK  ]

You also need to assign a password for the RICCI on both the nodes.

[root@rh1 ~]# passwd ricci
Changing password for user ricci.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Also, If you are running iptables firewall, keep in mind that you need to have appropriate firewall rules on both the nodes to be able to talk to each other.

3. Create Cluster on Active Node

From the active node, please run the below command to create a new cluster.
The following command will create the cluster configuration file /etc/cluster/cluster.conf. If the file already exists, it will replace the existing cluster.conf with the newly created cluster.conf.

[root@rh1 ~]# ccs -h rh1.mydomain.net --createcluster mycluster
rh1.mydomain.net password:

[root@rh1 ~]# ls -l /etc/cluster/cluster.conf
-rw-r-----. 1 root root 188 Sep 26 17:40 /etc/cluster/cluster.conf
Also keep in mind that we are running these commands only from one node on the cluster and we are not yet ready to propagate the changes to the other node on the cluster.

4. Initial Plain cluster.conf File

After creating the cluster, the cluster.conf file will look like the following:
[root@rh1 ~]# cat /etc/cluster/cluster.conf
<?xml version="1.0"?>
<cluster config_version="1" name="mycluster">
  <fence_daemon/>
  <clusternodes/>
  <cman/>
  <fencedevices/>
  <rm>
    <failoverdomains/>
    <resources/>
  </rm>
</cluster>

5. Add a Node to the Cluster

Once the cluster is created, we need to add the participating nodes to the cluster using the ccs command as shown below.
First, add the first node rh1 to the cluster as shown below.

[root@rh1 ~]# ccs -h rh1.mydomain.net --addnode rh1.mydomain.net
Node rh1.mydomain.net added.

Next, add the second node rh2 to the cluster as shown below.

[root@rh1 ~]# ccs -h rh1.mydomain.net --addnode rh2.mydomain.net
Node rh2.mydomain.net added.

Once the nodes are created, you can use the following command to view all the available nodes in the cluster. This will also display the node id for the corresponding node.

[root@rh1 ~]# ccs -h rh1 --lsnodes
rh1.mydomain.net: nodeid=1
rh2.mydomain.net: nodeid=2

6. cluster.conf File After Adding Nodes

This above will also add the nodes to the cluster.conf file as shown below.

[root@rh1 ~]# cat /etc/cluster/cluster.conf
<?xml version="1.0"?>
<cluster config_version="3" name="mycluster">
  <fence_daemon/>
  <clusternodes>
    <clusternode name="rh1.mydomain.net" nodeid="1"/>
    <clusternode name="rh2.mydomain.net" nodeid="2"/>
  </clusternodes>
  <cman/>
  <fencedevices/>
  <rm>
    <failoverdomains/>
    <resources/>
  </rm>
</cluster>

7. Add Fencing to Cluster

Fencing is the disconnection of a node from shared storage. Fencing cuts off I/O from shared storage, thus ensuring data integrity.

A fence device is a hardware device that can be used to cut a node off from shared storage.
This can be accomplished in a variety of ways: powering off the node via a remote power switch, disabling a Fiber Channel switch port, or revoking a host’s SCSI 3 reservations.

A fence agent is a software program that connects to a fence device in order to ask the fence device to cut off access to a node’s shared storage (via powering off the node or removing access to the shared storage by other means).
Execute the following command to enable fencing.

[root@rh1 ~]# ccs -h rh1 --setfencedaemon post_fail_delay=0
[root@rh1 ~]# ccs -h rh1 --setfencedaemon post_join_delay=25

Next, add a fence device. There are different types of fencing devices available. If you are using virtual machine to build a cluster, use fence_virt device as shown below.

[root@rh1 ~]# ccs -h rh1 --addfencedev myfence agent=fence_virt

Next, add fencing method. After creating the fencing device, you need to created the fencing method
and add the hosts to the fencing method.

[root@rh1 ~]# ccs -h rh1 --addmethod mthd1 rh1.mydomain.net
Method mthd1 added to rh1.mydomain.net.

[root@rh1 ~]# ccs -h rh1 --addmethod mthd1 rh2.mydomain.net
Method mthd1 added to rh2.mydomain.net.

Finally, associate fence device to the method created above as shown below:
[root@rh1 ~]# ccs -h rh1 --addfenceinst myfence rh1.mydomain.net mthd1
[root@rh1 ~]# ccs -h rh1 --addfenceinst myfence rh2.mydomain.net mthd1

8. cluster.conf File after Fencing

Your cluster.conf will look like below after the fencing devices, methods are added.

[root@rh1 ~]# cat /etc/cluster/cluster.conf
<?xml version="1.0"?>
<cluster config_version="10" name="mycluster">
  <fence_daemon post_join_delay="25"/>
  <clusternodes>
    <clusternode name="rh1.mydomain.net" nodeid="1">
      <fence>
        <method name="mthd1">
          <device name="myfence"/>
        </method>
      </fence>
    </clusternode>
    <clusternode name="rh2.mydomain.net" nodeid="2">
      <fence>
        <method name="mthd1">
          <device name="myfence"/>
        </method>
      </fence>
    </clusternode>
  </clusternodes>
  <cman/>
  <fencedevices>
    <fencedevice agent="fence_virt" name="myfence"/>
  </fencedevices>
  <rm>
    <failoverdomains/>
    <resources/>
  </rm>
</cluster>

9. Types of Failover Domain

A failover domain is an ordered subset of cluster members to which a resource group or service may be bound.
The following are the different types of failover domains:
  • Restricted failover-domain: Resource groups or service bound to the domain may only run on cluster members which are also members of the failover domain. If no members of failover domain are availables, the resource group or service is placed in stopped state.
  • Unrestricted failover-domain: Resource groups bound to this domain may run on all cluster members, but will run on a member of the domain whenever one is available. This means that if a resource group is running outside of the domain and member of the domain transitions online, the resource group or
  • service will migrate to that cluster member.
  • Ordered domain: Nodes in the ordered domain are assigned a priority level from 1-100. Priority 1 being highest and 100 being the lowest. A node with the highest priority will run the resource group. The resource if it was running on node 2, will migrate to node 1 when it becomes online.
  • Unordered domain: Members of the domain have no order of preference. Any member may run in the resource group. Resource group will always migrate to members of their failover domain whenever possible.

10. Add a Filover Domain

To add a failover domain, execute the following command. In this example, I created domain named as “webserverdomain”,

[root@rh1 ~]# ccs -h rh1 --addfailoverdomain webserverdomain ordered

Once the failover domain is created, add both the nodes to the failover domain as shown below:

[root@rh1 ~]# ccs -h rh1 --addfailoverdomainnode webserverdomain rh1.mydomain.net priority=1

[root@rh1 ~]# ccs -h rh1 --addfailoverdomainnode webserverdomain rh2.mydomain.net priority=2

You can view all the nodes in the failover domain using the following command.
[root@rh1 ~]# ccs -h rh1 --lsfailoverdomain
webserverdomain: restricted=0, ordered=1, nofailback=0
  rh1.mydomain.net: 1
  rh2.mydomain.net: 2

11. Add Resources to Cluster

Now it is time to add a resources. This indicates the services that also should failover along with ip and filesystem when a node fails. For example, the Apache webserver can be part of the failover in the Redhat Linux Cluster.

When you are ready to add resources, there are 2 ways you can do this.

You can add as global resources or add a resource directly to resource group or service.
The advantage of adding it as global resource is that if you want to add the resource to more than one service group you can just reference the global resource on your service or resource group.
In this example, we added the filesystem on a shared storage as global resource and referenced it on the service.

[root@rh1 ~]# ccs –h rh1 --addresource fs name=web_fs device=/dev/cluster_vg/vol01 mountpoint=/var/www fstype=ext4

To add a service to the cluster, create a service and add the resource to the service.

[root@rh1 ~]# ccs -h rh1 --addservice webservice1 domain=webserverdomain recovery=relocate autostart=1

Now add the following lines in the cluster.conf for adding the resource references to the service. In this example, we also added failover IP to our service.

  <fs ref="web_fs"/>
  <ip address="192.168.1.12" monitor_link="yes" sleeptime="10"/>

In the 2nd part of this tutorial (tomorrow), we’ll explain how to sync the configurations across multiple nodes in a cluster, and how to verify the failover scenario in a cluster setup.

Configuring Password Policy on CentOS 6

About Password Policy

Password policy is a set of rules that must to be satisfied when setting a password. Password policy is an important factor in computer security, specially since user passwords are too often the main reason for computer system security breaches. This is why most companies and organizations incorporate password policy into the company official regulations. All users and their passwords must comply to official company password policy.
Password policy usually defines:
  • Password Aging
  • Password Length
  • Password Complexity
  • Number of Login Failures
  • Re-Used Password Deny
Configuring Password Policy on CentOS 6

Step 1 – Configuring /etc/login.defs

Password aging controls and password length are defined in /etc/login.defs file. Password aging refers to the maximum number of days password may be used, minimum number of days allowed between password changes and more as seen below and password length refers to the number of characters that need to be used in password.

To configure password aging controls and password length edit /etc/login.defs file and PASS values according to your company policy. The password aging controls and password length do not affect existing users –  they only affect newly created users! PASS_MAX_DAYS – Maximum number of days a password may be used. PASS_MIN_DAYS – Minimum number of days allowed between password changes. PASS_MIN_LEN – Minimum acceptable password length. PASS_WARN_AGE – Number of days warning given before a password expires.

Example configuration file /etc/login.defs:

#
# Please note that the parameters in this configuration file control the
# behavior of the tools from the shadow-utils component. None of these
# tools uses the PAM mechanism, and the utilities that use PAM (such as the
# passwd command) should therefore be configured elsewhere. Refer to
# /etc/pam.d/system-auth for more information.
#
# *REQUIRED*
# Directory where mailboxes reside, _or_ name of file, relative to the
# home directory. If you _do_ define both, MAIL_DIR takes precedence.
# QMAIL_DIR is for Qmail
#
#QMAIL_DIR Maildir
MAIL_DIR /var/spool/mail
#MAIL_FILE .mail
# Password aging controls:
#
# PASS_MAX_DAYS Maximum number of days a password may be used.
# PASS_MIN_DAYS Minimum number of days allowed between password changes.
# PASS_MIN_LEN Minimum acceptable password length.
# PASS_WARN_AGE Number of days warning given before a password expires.
#
PASS_MAX_DAYS 90
PASS_MIN_DAYS 2
PASS_MIN_LEN 9
PASS_WARN_AGE 14
...

Step 2 – Configuring /etc/pam.d/system-auth

By editing /etc/pam.d/system-auth configuration file we can configure the password complexity and deny a number of re-used passwords. Password complexity refers to the complexity of the characters used in password and denying re-used passwords refers to denying the desired number of passwords the user used in the past. By setting password complexity, we can force a user to use the desired number of numbers, capital characters, lower case characters and symbols in his password. If he does not use the characters we specified the password will not be accepted by the system.

Force Capital Characters In Passwords – ucredit=-X – where X is the number of capital characters required in password

Force Lower Case Characters In Passwords – lcredit=-X – where X is the number of lower case characters required in password

Force Numbers In Passwords – dcredit=-X – where X is the number numbers required in password

Force The Use Of Symbols In Passwords – ocredit=-X – where X is the number of symbols required in password

password requisite pam_cracklib.so try_first_pass retry=3 type= ucredit=-2 lcredit=-2 dcredit=-2 ocredit=-2

Deny Re-Used Passwords – 
remember=X – where X is the number of past passwords to deny

password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok remember=5

Example configuration file /etc/pam.d/system-auth:

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth required pam_env.so
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid >= 500 quiet
auth required pam_deny.so
account required pam_unix.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 500 quiet
account required pam_permit.so
password requisite pam_cracklib.so try_first_pass retry=3 type= dcredit=-2 ucredit=-2 lcredit=-2 ocredit=-2
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok remember=5
password required pam_deny.so
session optional pam_keyinit.so revoke
session required pam_limits.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so

Step 3 – Set The Number Of Login Failures

To set the number of login failures we must edit /etc/pam.d/password-auth file. Number of login failures refers to the number of failed logins user can try before his account is locked out. When the account is locked out system administrator must unlock this account. To configure the number of login failures two new lines need to be added to /etc/pam.d/password-auth file. The parameter “deny=X” (where X is the number of login failures) configures the number of login failures permitted before the account is locked.

auth           required      pam_tally2.so deny=3
account     required      pam_tally2.so

Example configuration file /etc/pam.d/system-auth:

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth required pam_env.so
auth required pam_tally2.so deny=3
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid >= 500 quiet
auth required pam_deny.so
account required pam_unix.so
account required pam_tally2.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 500 quiet
account required pam_permit.so
password requisite pam_cracklib.so try_first_pass retry=3 type=
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password required pam_deny.so
session optional pam_keyinit.so revoke
session required pam_limits.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so

Monday, April 20, 2015

Configure Apache http as Forward & Reverse Proxy

There are two possible configurations for Apache Proxy Server and we will present installation and configuration of both types this how to.

Apache Proxy Server
  1. Forward Apache Proxy is a proxy configuration that is commonly used in companies and it enables users to access the internet. Users or clients must configure their browsers or operating system to use a proxy server (Forward Apache Proxy) to be able to access the internet. This means that requests from all clients go through this apache Forward Apache Proxy which then communicates with the destination servers, websites, … on the internet and responds back to the clients.
  2. Reverse Apache Proxy is a proxy configuration that works the other way around from the Forward Apache Proxy. The Reverse Apache Proxy configuration is used to enable users or clients from the internet, to access websites or applications on the company internal network, based on the reverse apache proxy rules that are configured. Reverse Apache Proxy provides internet clients access to servers behind a firewall.

FORWARD APACHE PROXY

1. Install Required Packages

Firts we must install Apache (httpd) and mod_ssl package on our server. Please note that in CentOS 7 Apache 2.4.X is available (in CentOS 5 and 6 Apache 2.2.X).
[root@geekpeek ~]# yum install httpd mod_ssl

2. Basic Forward Apache Proxy Configuration

We need to add a forward proxy configuration file to “/etc/httpd/conf.d” location. We named if “forward-proxy.conf” and added the following content to it:

ProxyRequests On
ProxyVia On
ProxyTimeout 60

<Proxy *>
    Require local
    Require ip 192.168.1.0/255.255.255.0
</Proxy>

The “ProxyRequests” parameter and “ProxyVia” is needed to enable proxy on Apache. “ProxyTimeout” is optional, it just enables request to fail gracefully if the server does not respond in a reasobnale time. The “Require” parameters inside the “Proxy” directive are the client allowed settings.

You can add a specific IP address (as in my case) or whole subnet (with mask like 192.168.1.0/255.255.255.0). The “Require local” allows localhost requests. You could also use “Require host hostname” directive. There are many more parameters available – this is just basic configuration – read more about additional parameters HERE.

3. Block WebSites

We can block the desired websites using “ProxyBlock” parameter. “ProxyBlock” parameter specifies a list of words, hosts or domains separated by spaces (a wildcard * would block all sites!) as follows:

ProxyRequests On
ProxyVia On
ProxyTimeout 60

ProxyBlock facebook.com plus.google.com twitter.com

<Proxy *>
   Require local
   Require ip 192.168.1.0/255.255.255.0
</Proxy>

4. Configure Forwarding to Second Proxy

If you work in a big company (or in other situations) there is a possibility your proxy is not the “last in line” out to the open world. In this case you need to configure a second proxy. This is a proxy your proxy will forward requests to, to get to the internet. We can do this with “ProxyRemote” parameter. “ProxyRemote” parameters takes two two arguments, a scheme, partial URL or ‘*’ and a proxy server. Using wildcard ‘*’ will forward all requests to the second proxy.

ProxyRequests On
ProxyVia On
ProxyTimeout 60

ProxyBlock facebook.com plus.google.com twitter.com
ProxyRemote * http://second.proxy.com:8080

<Proxy *>
   Require local
   Require ip 192.168.1.0/255.255.255.0
</Proxy>

5. Configure NoProxy

If you configured a second proxy it is probably a good idea to use a “NoProxy” parameter. “NoProxy” parameter specifies a list of subnets, IP addresses, hosts and/or domains, separated by spaces which are always served directly without forwarding to the “ProxyRemote” address.

ProxyRequests On
ProxyVia On
ProxyTimeout 60

ProxyBlock facebook.com plus.google.com twitter.com
ProxyRemote * http://second.proxy.com:8080
NoProxy .geekpeek.net

<Proxy *>
   Require local
   Require ip 192.168.1.0/255.255.255.0
</Proxy>

REVERSE APACHE PROXY

1. Install Required Packages

At this stage we must install Apache (httpd) and mod_ssl package on our server. Please note that in CentOS 7 Apache 2.4.X is available (in CentOS 5 and 6 Apache 2.2.X).
[root@geekpeek ~]# yum install httpd mod_ssl

2. Basic Reverse Apache Proxy Configuration

We need to add a reverse proxy configuration file to “/etc/httpd/conf.d” location. We named if “reverse-proxy.conf” and added the following lines to it:

ProxyRequests Off

ProxyPass /test1 http://192.168.1.10:8080/test1
ProxyPassReverse /test1 http://192.168.1.10:8080/test1

ProxyRequests” parameter does not need to be turned on when configuring reverse proxy so turning it off. Next two lines are passing all requests, hitting the reverse proxy server IP/hostname with /test1 URL to the machine with IP address 192.168.1.10, port 8080 and /test1 URL and the other way around. For the communication to work both ways we need to add both lines “ProxyPass” and “ProxyPassReverse“.

3. Add Additional ProxyPasses

It is easy to add additional proxy passes simply by adding new two lines with “ProxyPass” and “ProxyPassReverse” parameters:
ProxyRequests Off

ProxyPass /test1 http://192.168.10.59:8080/test1
ProxyPassReverse /test1 http://192.168.10.59:8080/test1

ProxyPass /test2 http://192.168.10.59:8080/test2
ProxyPassReverse /test2 http://192.168.10.59:8080/test2

Please note that proxy pass can point to a different server, different hostname or IP address.

4. Configure Timeouts

It is wise to configure some sort of time limit on how long to wait if there is no response from backend. We can do this by appending a “connectiontimeout” and “timeout” value at the end of “ProxyPass” line. The “connectiontimeout” is the time it takes to create the connection to the backend and “timeout” is the time proxy waits for response from backend.

ProxyRequests Off
ProxyPass /test1 http://192.168.10.59:8080/test1 connectiontimeout=5 timeout=30
ProxyPassReverse /test1 http://192.168.10.59:8080/test1

ProxyPass /test2 http://192.168.10.59:8080/test2 connectiontimeout=5 timeout=30
ProxyPassReverse /test2 http://192.168.10.59:8080/test2

5. Rewrite HTML Links

Using reverse proxy and accessing internal networks and applications via it, cause specific HTML links (internal links with absolute paths) to fail – not work, since they are redirecting to internal addresses. This is why we need to call for help another Apache module called “mod_proxy_html” which enables rewriting of HTML links and making them work.

mod_proxy_html” does not come by default with httpd installation in CentOS 7so we need to install it first and then copy the configuration file to the right location. The example HTML links configuration file is quite sufficient for ordinary situations and is located at “/usr/share/doc/httpd-X.X.X/” where X.X.X is your apache version number.
What we have to do is:

[root@geekpeek ~]# yum install mod_proxy_html
..and then
[root@geekpeek ~]# cp /usr/share/doc/httpd-2.4.6/proxy-html.conf /etc/httpd/conf.d/
..to finish up we have to restart or reload apache and voila HTML links are working

Souce : http://geekpeek.net

How to Setup Apache as Reverse Proxy for Tomcat Server


Setup Apache as Reverse Proxy for Tomcat Server


Setup Scenario

Tomcat is running on port 8080 and I have configured two sample applications running with following urls.
  • http://localhost:8080/sample
  • http://localhost:8080/calendar
Now I have installed Apache server on same host running on port 80. I will use Apache server to get users requests and transfer these requests to corresponding applications running on back-end Tomcat server on port 8080. I need to configure Apache to transfer requests to tomcat like below:
  • http://example.com >> http://localhost:8080/demo1/
  • http://example.net >> http://localhost:8080/demo2/
  • http://domain.com/demo1/ >> http://localhost:8080/demo1/
  • http://domain.com/demo2/ >> http://localhost:8080/demo2/
Apache as Reverse Proxy
Let’s start configuration

1. Enable Mod Proxy Apache Module

By default this module is enabled in Apache for users who installed using rpm packages. If you don’t have enabled edit your Apache configuration /etc/httpd/conf/httpd.conf or for Apache 2.4 /etc/httpd/conf.modules.d/00-proxy.conf file and uncomment following lines or put in file.
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

2. Configure Apache Virtual Hosts

Now will start working with virtual host. We are creating three virtual hosts as below. You create only which is required with needed modifications. Edit Apache main configuration file and start with the configuration.

Setup VirtualHost-1:

To forward all requests sent to example.com to backend tomcat server corresponding application like:
  • http://example.com >> http://localhost:8080/demo1/
Configure virtual host like this.
<VirtualHost *:80>
 ServerName example.com

 ProxyRequests On
 ProxyPass / http://localhost:8080/demo1/
 ProxyPassReverse / http://localhost:8080/demo1/

 <Location "/sample">
   Order allow,deny
   Allow from all
 </Location>
 
</VirtualHost>

Setup VirtualHost-2:

To forward all requests sent to example.net to backend tomcat server corresponding application like:
  • http://example.net >> http://localhost:8080/demo2/
Configure virtual host like this.
<VirtualHost *:80>
 ServerName example.net

 ProxyRequests On
 ProxyPass / http://localhost:8080/demo2/
 ProxyPassReverse / http://localhost:8080/demo2/

 <Location "/">
   Order allow,deny
   Allow from all
 </Location>
 
</VirtualHost>

Setup VirtualHost-3:

To forward all requests sent to sub directory /demo1/ or /demo2 on http://domain.com to back-end tomcat corresponding applications like:
  • http://domain.com/demo1/ >> http://localhost:8080/demo1/
  • http://domain.com/demo2/ >> http://localhost:8080/demo2/
Configure virtual host like this.
<VirtualHost *:80>
 ServerName domain.com

 ProxyRequests On
 ProxyPass /demo1 http://localhost:8080/demo1/
 ProxyPassReverse /demo1 http://localhost:8080/demo1/
 
 ProxyPass /demo2 http://localhost:8080/demo2/
 ProxyPassReverse /demo2 http://localhost:8080/demo2/

 <Location "/demo1">
   Order allow,deny
   Allow from all
 </Location>
 <Location "/demo2">
   Order allow,deny
   Allow from all
 </Location>
 
</VirtualHost>

3. Restart Apache and Test

After making all necessary changes restart Apache service using following command and access your sites in web browser. Make sure you are getting proper pages from tomcat.
# service httpd restart

Source : http://tecadmin.net

Create NIC Channel Bonding in RedHat/CentOS/Fedora

Channel Bonding enables two or more network interfaces to act as one, simultaneously increasing the bandwidth and providing redundancy. This is a great way of achieving redundancy to a server. If one physical NIC is down or unplugged, it will automatically move resource to other NIC card. Channel bonding will work with the help of bonding driver in kernel. This post guides you through how to create NIC / Channel Bonding in RedHat, CentOS and Fedora Linux.

Install And Configure FTP Server On CentOS

vsftpd (Very Secure File Transport Protocol Daemon) is a secure, fast FTP server for Unix/Linux systems. In this how-to article, let us see how to setup a basic FTP server on CentOS 7. However, this procedure might work well on RHEL CentOS, Scientific Linux 7 version too.
My testbox server hostname and IP Address are server.unixmen.local and 192.168.1.101/24 respectively. Change these values to match your scenario.

Install vsftpd

All commands should be run with ‘root’ user. Run the following command in terminal to install vsftpd package:
yum install vsftpd ftp -y

Configure vsftpd

Edit vsftpd configuration file /etc/vsftpd/vsftpd.conf,
vi /etc/vsftpd/vsftpd.conf
Find the following lines and make the changes as shown below:
 [...]
## Disable anonymous login ##
anonymous_enable=NO

## Uncomment ##
ascii_upload_enable=YES
ascii_download_enable=YES

## Uncomment - Enter your Welcome message - This is optional ##
ftpd_banner=Welcome to UNIXMEN FTP service.

## Add at the end of this  file ##
use_localtime=YES
Enable and start the vsftpd service:
systemctl enable vsftpd
systemctl start vsftpd

Firewall And SELinux Configuration

Allow the ftp service and port 21 via firewall.
firewall-cmd --permanent --add-port=21/tcp
firewall-cmd --permanent --add-service=ftp

Restart firewall:
firewall-cmd --reload

Then, update the SELinux boolean values for FTP service:
setsebool -P ftp_home_dir on

Create FTP users

By default, root user is not allowed to login to ftp server for security purpose. So, let us create a normal testing user called “sk” with password “centos”.
useradd sk
passwd sk

Connecting to FTP server

Now, try to connect to FTP server itself with user “sk”:
ftp 192.168.1.101
Enter the ftp user name and password.
Sample Output:
Connected to 192.168.1.101 (192.168.1.101).
220 Welcome to UNIXMEN FTP service.
Name (192.168.1.101:root): sk
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

Congratulations!! you will be able to login to FTP server without any problems.

Client side configuration

Let us try to log in to the FTP server from my Ubuntu client system.
ftp 192.168.1.101
Sample Output:
Connected to 192.168.1.101.
220 Welcome to UNIXMEN FTP service.
Name (192.168.1.101:sk): sk
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>
Voila!! Our FTP server is working.

Access FTP Server Via FileZilla

Working from command-line mode might be little bit difficult to newbies. So let us install a graphical FTP client called Filezilla to get things done quite easier:

Note: As you may know already, in RHEL 7 and its derivatives the previous firewall system(iptables) has been replaced with firewalld. I find it bit difficult to configure Filezilla along with Firewalld. So I disabled it, and switched back to old firewall system called iptables. I will update this tutorial as soon as possible once I found the working solution. If you don’t want to use filezilla, skip the following steps.

First, enter the following commands one by one to disable current firewall system firewalld, and enable old firewall iptables. The following commands should be run on your FTP server, not in ftp clients.
yum install iptables-services
systemctl mask firewalld
systemctl enable iptables
systemctl enable ip6tables
systemctl stop firewalld
systemctl start iptables
systemctl start ip6tables

Allow the default ftp port “21″ through your firewall or router. In the server side, do the following.
Edit file /etc/sysconfig/iptables,

vi /etc/sysconfig/iptables
Add the following lines.
[...]
-A INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT
[...]

Save and exit the file. Restart iptables now:
systemctl restart iptables
systemctl restart ip6tables

Now, go back to your client systems, and install filezilla package.
On Debian based client systems:
sudo apt-get install filezilla

For RHEL based systems, you can install filezilla using following command:
yum install filezilla

Open Filezilla client from your client system “Dash” or “Menu”. Enter the FTP server hostname or IP Address, username, password and port number. Click “Quickconnect” to login.

FileZilla_002

Probably, you will get the following error.
Error:    The data connection could not be established: EHOSTUNREACH - No route to host
Error:    Connection timed out
Error:    Failed to retrieve directory listing
To get rid of this error, do the following steps. In most cases, Resolution 2 should work.

Resolution 1:
1. From your Filezilla client, go to Edit -> Settings -> FTP ->Active Mode.
In the Active Mode tab, make sure the option “Ask your operating system for the external ip address” is selected.

Settings_004

Then goto Edit -> Settings -> FTP ->Passive Mode. Select “Fall back to active mode” and click Ok.

Settings_005

Now the error will be gone in some cases (May be in Windows OS clients).

Resolution 2:

If the problem still persists, goto your FTP server, edit file “/etc/sysconfig/iptables-config”.
vi /etc/sysconfig/iptables-config
Find the line IPTABLES_MODULES=” “ and change this to IPTABLES_MODULES=”ip_conntrack_ftp”:
# Load additional iptables modules (nat helpers)
#   Default: -none-
# Space separated list of nat helpers (e.g. 'ip_nat_ftp ip_nat_irc'), which
# are loaded after the firewall rules are applied. Options for the helpers are
# stored in /etc/modprobe.conf.
IPTABLES_MODULES="ip_conntrack_ftp"
[...]

Save the iptables rules and restart firewall:
systemctl restart iptables
Now, try again from Filezilla.

sk@192.168.1.101 - FileZilla_006
It should work now.

Access FTP server from Browser

You can access the FTP server from your client browser also. Navigate to ftp://FTP-Server-IP-Address/. Enter the ftp username and password.

New Tab - Mozilla Firefox_007

Now you can see the contents in your FTP server.

Index of ftp:--192.168.1.101- - Mozilla Firefox_008

Log in as a particular user

If you want to login using a particular user, then navigate to ftp://username@FTP-Server-IP-Address/. It will ask the password of user, enter the password and you’re done.

For example, navigate to ftp://sk@192.168.1.101. Enter the password of the user sk.

New Tab - Mozilla Firefox_009

Index of ftp:--sk@192.168.1.101- - Mozilla Firefox_010

That’s it.The FTP server ready now. Start using FTP!

Sunday, April 19, 2015

SSH Passwordless Login Using SSH Keygen in 5 Easy Steps

SSH (Secure SHELL) is an open source and most trusted network protocol that is used to login into remote servers for execution of commands and programs. It is also used to transfer files from one computer to another computer over the network using secure copy (SCP) Protocol.

In this article we will show you how to setup password-less login on RHEL/CentOS 7.x/6.x/5.x and Fedora using ssh keys to connect to remote Linux servers without entering password. Using Password-less login with SSH keys will increase the trust between two Linux servers for easy file synchronization or transfer.

Setup SSH Passwordless Login
Setup Environment
SSH Client : 192.168.0.1 ( CentOS 7 )
SSH Remote Host : 192.168.0.2 ( CentOS 7 )

If you are dealing with number of Linux remote servers, then SSH Password-less login is one of the best way to automate tasks such as automatic backups with scripts, synchronization files using scp and remote command execution.

In this example we will setup SSH password-less automatic login from server 192.168.0.2 as user testserver to 192.168.0.1 with user testclient.

Step 1: Create Authentication SSH-Kegen Keys on – (192.168.0.2)
First login into server 192.168.0.2 with user testserver and generate a pair of public keys using following command.
[testserver@testserver.com ~]$ ssh-keygen -t rsa

Generating public/private rsa key pair.
Enter file in which to save the key (/home/testserver/.ssh/id_rsa): [Press enter key]
Created directory '/home/testserver/.ssh'.
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Press enter key]
Your identification has been saved in /home/testserver/.ssh/id_rsa.
Your public key has been saved in /home/testserver/.ssh/id_rsa.pub.
The key fingerprint is:
5f:ad:40:00:8a:d1:9b:99:b3:b0:f8:08:99:c3:ed:d3 testserver@testserver.com
The key's randomart image is:
+--[ RSA 2048]----+
|        ..oooE.++|
|         o. o.o  |
|          ..   . |
|         o  . . o|
|        S .  . + |
|       . .    . o|
|      . o o    ..|
|       + +       |
|        +.       |
+-----------------+

Step 2: Create .ssh Directory on – 192.168.0.1

Use SSH from server 192.168.0.2 to connect server 192.168.0.1 using testclient as user and create .ssh directory under it, using following command.

[testserver@testserver.com ~]$ ssh testclient@192.168.0.1 mkdir -p .ssh

The authenticity of host '192.168.0.1 (192.168.0.1)' can't be established.
RSA key fingerprint is 45:0e:28:11:d6:81:62:16:04:3f:db:38:02:la:22:4e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.0.11' (ECDSA) to the list of known hosts.
testclient@192.168.0.1's password: [Enter Your Password Here]

Step 3: Upload Generated Public Keys to – 192.168.0.1
Use SSH from server 192.168.0.2 and upload new generated public key (id_rsa.pub) on server 192.168.0.1 under testclient‘s .ssh directory as a file name authorized_keys.

[testserver@testserver.com ~]$ cat .ssh/id_rsa.pub | ssh testclient@192.168.0.1 'cat >> .ssh/authorized_keys'

testclient@192.168.0.1's password: [Enter Your Password Here]

Step 4: Set Permissions on – 192.168.0.1
Due to different SSH versions on servers, we need to set permissions on .ssh directory and authorized_keys file.

[testserver@testserver.com ~]$ ssh testclient@192.168.0.1 "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"

testclient@192.168.0.1's password: [Enter Your Password Here]

Step 5: Login from 192.168.0.2 to 192.168.0.1 Server without Password
From now onwards you can log into 192.168.0.1 as testclient user from server 192.168.0.2 as testserver user without password.

[testserver@testserver.com ~]$ ssh testclient@192.168.0.1