nginx multiple SSL server block example :

root@nplink:/etc/nginx/sites-available# nginx -V
nginx version: nginx/1.1.19
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx.
.
.
To generate an RSA key, use the genrsa option. The command below generates a 2048 bit RSA key and saves it to a file called key.pem
(No password protected)
openssl genrsa -out privatekey.pem 2048 
 
If you require that your private key file is protected with a passphrase, use the command below.
openssl genrsa -des3 -out privatekey.pem 2048 
 
here private key i generated is named 'privatekey.pem'
Now removing password.. 

# openssl rsa -in privatekey.pem -out nprivate.key
 
Creating CSR certificate sigining request:
# openssl req -new -key nprivate.key -out CSRself.csr 
----------------------------------------------------------
Signing and creating certificate with csr
 
# openssl x509 -req -days 365 -in CSRself.csr -signkey nprivate.key -out selfsignedSSLCRT.crt
 
root@nplink:/etc/nginx/ssl/helloSSL# pwd 
/etc/nginx/ssl/helloSSL 
root@nplink:/etc/nginx/ssl/helloSSL# ls 
CSRself.csr  nprivate.key   selfsignedSSLCRT.crt
 
There are two virtual hosts 1)example.com 2)hello.com
hello.com implementing ssl
 
root@nplink:/etc/nginx/sites-available# ls 
example.com  hello.com 
root@nplink:/etc/nginx/sites-available# cat hello.com 
# Generated by Chef for nplink (nginx version: 1.1.19)

# Local modifications will be overwritten.
#
#getting ridn of www
server {
 listen   192.168.140.30:80 default;
server_name hello.com *.hello.com;
##redirect http to https ##
rewrite        ^ https://$server_name$request_uri? permanent;
}


 server {

  ssl_certificate /etc/nginx/ssl/helloSSL/selfsignedSSLCRT.crt;
  ssl_certificate_key /etc/nginx/ssl/helloSSL/nprivate.key;
  access_log /var/log/nginx/default-access.log;
  error_log  /var/log/nginx/default-error.log;
  root /var/www/hello.com/public_html;
  index index.html index.htm;
        
        ##start ssl config

 listen 192.168.140.30:443 ssl;
 server_name hello.com *.hello.com;

########## redirect to https##########
   
if ($host = 'www.hello.com' ) {
         rewrite  ^/(.*)$  https://hello.com/$1  permanent;
      }
}
=========================================================
root@nplink:/etc/nginx/sites-available# cat example.com
# Generated by Chef for nplink (nginx version: 1.1.19)
#
# Local modifications will be overwritten.
# 
server {
  
listen   192.168.140.30:80;
 server_name example.com *.example.com;
 access_log /var/log/nginx/default-access.log;
  
error_log  /var/log/nginx/default-error.log;


   
 root /var/www/example.com/public_html;
    
index index.html index.htm;
 } 
 
------------------------------------------------------------
 


create soft link of example.com and hello.com in sites-enabled with full path

# ln -s /etc/nginx/sites-available/hello.com /etc/nginx/sites-enabled/hello.com
# ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com

---------------------------------------------------------------------------------
place your file in /var/www/

##service nginx reload or restart and check

openssl ptr

View the contents of a CSR

To view a CSR you can use our online CSR Decoder. However, if you prefer to decode your CSR locally use the command below.
openssl req -in req.pem -noout -text

Verify the signature on a CSR

To verify the signature on a CSR you can use our online CSR Decoder, or you can use the command below.
openssl req -in req.pem -noout -verify

Create a self-signed certificate

To create a self-signed certificate, sign the CSR with its associated private key
openssl x509 -req -days 365 -in req.pem -signkey key.pem -out cert.pem
To create a self-signed certificate, with one command use the command below. This generates a 2048 bit key and associated self-signed certificate with a one year validity period.
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

View the contents of a certificate

To view a certificate you can use our online Certificate Decoder. However, if you prefer to decode your certificate locally use the command below.
openssl x509 -in cert.pem -noout -text

Create a test SSL server

The OpenSSL s_server command implements a generic SSL/TLS server. It should be used for test purposes only. The example below listens for connections on port 8080 and returns an HTML formatted status page that includes lots of information about ciphers.
openssl s_server -key key.pem -cert cert.pem -accept 8080 -www

Convert a certificate from PEM to DER format

openssl x509 -in cert.pem -inform PEM -out cert.der -outform DER 

Convert a certificate from DER to PEM format

openssl x509 -in cert.der -inform DER -out cert.pem -outform PEM 

Convert a CSR from PEM to DER format

openssl req -in csr.pem -out csr.der -outform DER

Convert a CSR from DER to PEM format

openssl req -in csr.der -inform DER -out csr.pem -outform PEM

Get the SHA-1 fingerprint of a certificate or CSR

You can use our CSR and Cert Decoder to get the SHA1 fingerprint of a certificate or CSR. The decoder converts the CSR/certificate to DER format before calculating the fingerprint.
To get the SHA1 fingerprint of a certificate using OpenSSL, use the command shown below.
openssl dgst -sha1 certificate.der
To get the SHA1 fingerprint of a CSR using OpenSSL, use the command shown below.
openssl dgst -sha1 csr.der

Get the MD5 fingerprint of a certificate or CSR

You can use our CSR and Cert Decoder to get the MD5 fingerprint of a certificate or CSR. The decoder converts the CSR/certificate to DER format before calculating the fingerprint.
To get the MD5 fingerprint of a certificate using OpenSSL, use the command shown below.
openssl dgst -md5 certificate.der
To get the MD5 fingerprint of a CSR using OpenSSL, use the command shown below.
openssl dgst -md5 csr.der

Grab a website's SSL certificate

openssl s_client -connect www.somesite.com:443 > cert.pem
Now edit the cert.pem file and delete everything except the PEM certificate.
The command below makes life even easier as it will automatically delete everything except the PEM certificate.
echo -n | openssl s_client -connect mysite.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > pem.cert
If the webserver has several certificates on one IP address, then you will need to tell OpenSSL which certificate to request using Server Name Indication (SNI). This can be done by adding the -servername argument, which tells OpenSSL to negotiate SNI. The command below shows the previous command modified to use SNI.
echo -n | openssl s_client -connect mysite.com:443 -servername mysite.com | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > pem.cert

Find out what version of OpenSSL you're running

Use the version command
openssl version



Self signed ssl certificate for NGINX

  1. Usually, an SSL certificate issued by a third party. It provides privacy and security between two computers (client and server) on a public network by encrypting traffic. CA (Certificate Authorities) may issue you a SSL certificate that verify the organizational identity (company name), location, and server details.
  2. A self-signed certificate encrypt traffic between client (browser) and server. However, it can not verify the organizational identity. You are not depend upon third party to verify your location and server details.

    Our sample setup

  • Domain name: theos.in
  • Directory name: /etc/nginx/ssl/theos.in
  • SSL certificate file for theos.in: /etc/nginx/ssl/theos.in/self-ssl.crt
  • ssl certificate key for theos.in: /etc/nginx/ssl/theos.in/self-ssl.key
  • Nginx configuration file for theos.in: /etc/nginx/virtual/theos.in.conf

Step #1: Make sure SSL aware nginx installed

Find nginx version:

root@nplink:/etc/nginx# nginx -V
 
nginx version: nginx/1.1.19
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/va

 . . .

Step #2: Create a directory

Type the following mkdir command to create a directory to store your ssl certificates:
# mkdir -p /etc/nginx/ssl/theos.in
Use the following cd command to change the directory:
# cd /etc/nginx/ssl/theos.in

Step #3: Create an SSL private key

To generate an SSL private key, enter:
# openssl genrsa -des3 -out self-ssl.key 1024
OR better try 2048 bit key:
# openssl genrsa -des3 -out self-ssl.key 2048
Sample outputs:
Generating RSA private key, 1024 bit long modulus
...++++++
...............++++++
e is 65537 (0x10001)
Enter pass phrase for self-ssl.key: Type-Your-PassPhrase-Here
Verifying - Enter pass phrase for self-ssl.key: Retype-Your-PassPhrase-Here
Warning: Make sure you remember passphrase. This passphrase is required to access your SSL key while generating csr or starting/stopping ssl.

Step #4: Create a certificate signing request (CSR)

To generate a CSR, enter:
# openssl req -new -key self-ssl.key -out self-ssl.csr
Sample outputs:
Enter pass phrase for self-ssl.key: Type-Your-PassPhrase-Here
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:IN
State or Province Name (full name) []:Delhi
Locality Name (eg, city) [Default City]:New Delhi
Organization Name (eg, company) [Default Company Ltd]:nixCraft LTD
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:theos.in
Email Address []:webmaster@nixcraft.com 
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Step #5: Remove passphrase for nginx (optional)

You can remove passphrase from self-ssl.key for nginx server, enter:
# cp -v self-ssl.{key,original}
# openssl rsa -in self-ssl.original -out self-ssl.key
# rm -v self-ssl.original

Sample outputs:
Enter pass phrase for self-ssl.original: Type-Your-PassPhrase-Here
writing RSA key

Step #6: Create certificate

Finally, generate SSL certificate i.e. sign your SSL certificate with your own .csr file for one year:
# openssl x509 -req -days 365 -in self-ssl.csr -signkey self-ssl.key -out self-ssl.crt

Sample outputs:

Signature ok
subject=/C=IN/ST=Delhi/L=New Delhi/O=nixCraft LTD/OU=IT/CN=theos.in/emailAddress=webmaster@nixcraft.com
Getting Private key


Step #7: Configure the Certificate for nginx

Edit /etc/nginx/virtual/theos.in.conf, enter:
# vi /etc/nginx/virtual/theos.in.conf
The general syntax is as follows for nginx SSL configuration:
server {
    listen               443;
    ssl                  on;
    ssl_certificate      /path/to/self-ssl.crt;
    ssl_certificate_key  /path/to/self-ssl.key;
    server_name theos.in;
    location / {
       ....
       ...
       ....
    }
}
Here is my sample config for theos.in:
server {
    ###########################[Note]##############################
    ## Note: Replace IP and server name as per your actual setup ##
    ###############################################################
    ## IP:Port and server name
        listen 75.126.153.211:443;
        server_name theos.in;
    ## SSL settings
        ssl on;
        ssl_certificate /etc/nginx/ssl/theos.in/self-ssl.crt;
        ssl_certificate_key /etc/nginx/ssl/theos.in/self-ssl.key;
    ## SSL caching/optimization
        ssl_protocols        SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers RC4:HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        keepalive_timeout    60;
        ssl_session_cache    shared:SSL:10m;
        ssl_session_timeout  10m;
    ## SSL log files
        access_log /var/log/nginx/theos.in/ssl_theos.in_access.log;
        error_log /var/log/nginx/theos.in/ssl_theos.in_error.log;
    ## Rest of server config goes here
        location / {
                proxy_set_header        Accept-Encoding   "";
                proxy_set_header        Host              $http_host;
                proxy_set_header        X-Forwarded-By    $server_addr:$server_port;
                proxy_set_header        X-Forwarded-For   $remote_addr;
                proxy_set_header        X-Forwarded-Proto $scheme;
                proxy_set_header        X-Real-IP               $remote_addr;
                proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
                ## Hey, ADD YOUR location / specific CONFIG HERE ##
                ## STOP: YOUR location / specific CONFIG HERE ##
        }
}

Step #8: Restart/reload nginx

Type the following command
# /usr/sbin/nginx -t
Sample outputs:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
To gracefully restart/reload nginx server, type the following command:
# /etc/init.d/nginx reload
OR
# /usr/sbin/nginx -s reload
OR
# service nginx reload

Step #9: Open TCP HTTPS port # 443

Type the following command to open port # 443 for everyone:
# /sbin/iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
Save new firewall settings:
# service iptables save
See how to setup firewall for a web server for more information.

Step 10: Test it

Fire a browser and type the following url:
https://theos.in/
 

Step 11: Verify SSL certificats

You can verify SSL Certificate using the following command:
# openssl verify pem-file
# openssl verify self-ssl.crt

 

openvpn

OpenVPN is a robust and highly flexible tunneling application that uses all of the encryption, authentication, and certification features of the OpenSSL library to securely tunnel IP networks over a single TCP/UDP port. OpenVPN is developed by James Yonan of OpenVPN Technologies.
In this brief guide, let us setup OpenVPN server on CentOS 6.5, and connect from a remote client. For the purpose of this tutorial, I use two systems running with CentOS 6.5, one acts as VPN server and other one acts as VPN client.

Part One – VPN Server Side Configuration

Here, I use CentOS 6.5 as VPN server, and it’s actual IP address is 192.168.1.2/24.

Prerequisites

OpenVPN and it’s dependencies are not available in the CentOS default repositories. So, we should install the “EPEL” repository in order to install OpenVPN and its dependencies.
To enable EPEL repository On CentOS, refer the following link.
Also, update the system using the following command:
yum update

Install OpenVPN Software

Install the OpenVPN software using the following command:
yum install openvpn easy-rsa
The easy-rsa scripts are located by default in the /usr/share/easy-rsa/ directory. Make a directory /easy-rsa/keys inside the/etc/openvpn directory and copy the scripts to that directory as shown below:
mkdir -p /etc/openvpn/easy-rsa/keys
cp -rf /usr/share/easy-rsa/2.0/* /etc/openvpn/easy-rsa/

Generate CA Certificate and CA key

Edit file /etc/openvpn/easy-rsa/2.0/vars,
vi /etc/openvpn/easy-rsa/vars
And, change the values that matches with your country, state, city, mail id etc.
[...]
# Don't leave any of these fields blank.
export KEY_COUNTRY="IN"
export KEY_PROVINCE="TN"
export KEY_CITY="Erode"
export KEY_ORG="Unixmen"
export KEY_EMAIL="sk@unixmen.com"
export KEY_OU="server"
[...]
Go to the openvpn/easy-rsa directory:
cd /etc/openvpn/easy-rsa/
Enter the following commands one by one to initialize the certificate authority:
cp openssl-1.0.0.cnf openssl.cnf
source ./vars
./clean-all
Then, run the following command to generate CA certificate and CA key:
./build-ca
Sample output:
Generating a 2048 bit RSA private key
......................................................+++
............................................................+++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [TN]: ----> Press Enter
Locality Name (eg, city) [Erode]: ----> Press Enter
Organization Name (eg, company) [Unixmen]: ----> Press Enter
Organizational Unit Name (eg, section) [server]: ----> Press Enter
Common Name (eg, your name or your server's hostname) [Unixmen CA]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [sk@unixmen.com]: ----> Press Enter
We have now generated the CA certificate and CA key. Then create certificate and key for server using the following command:
./build-key-server server
Sample output:
Generating a 2048 bit RSA private key
....................+++
.............+++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [TN]: ----> Press Enter
Locality Name (eg, city) [Erode]: ----> Press Enter
Organization Name (eg, company) [Unixmen]: ----> Press Enter
Organizational Unit Name (eg, section) [server]: ----> Press Enter
Common Name (eg, your name or your server's hostname) [server]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [sk@unixmen.com]: ----> Press Enter

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ----> Press Enter      
An optional company name []: ----> Press Enter
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IN'
stateOrProvinceName   :PRINTABLE:'TN'
localityName          :PRINTABLE:'Erode'
organizationName      :PRINTABLE:'Unixmen'
organizationalUnitName:PRINTABLE:'server'
commonName            :PRINTABLE:'server'
name                  :PRINTABLE:'EasyRSA'
emailAddress          :IA5STRING:'sk@unixmen.com'
Certificate is to be certified until Mar 23 12:21:34 2024 GMT (3650 days)
Sign the certificate? [y/n]:y ----> Type Y and Press Enter

1 out of 1 certificate requests certified, commit? [y/n]y ----> Type Y and Press Enter
Write out database with 1 new entries
Data Base Updated
Create certificate and key for VPN clients using the following command:
./build-key client
If you want to create certificate and key files for each client, you should replace the client parameter with an unique identifier.
Sample output:
Generating a 2048 bit RSA private key
.......+++
..................................................................................................+++
writing new private key to 'client.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IN]: ----> Press Enter
State or Province Name (full name) [TN]: ----> Press Enter
Locality Name (eg, city) [Erode]: ----> Press Enter
Organization Name (eg, company) [Unixmen]: ----> Press Enter
Organizational Unit Name (eg, section) [server]: ----> Press Enter
Common Name (eg, your name or your server's hostname) [client]: ----> Press Enter
Name [EasyRSA]: ----> Press Enter
Email Address [sk@unixmen.com]: ----> Press Enter

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ----> Press Enter
An optional company name []: ----> Press Enter
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IN'
stateOrProvinceName   :PRINTABLE:'TN'
localityName          :PRINTABLE:'Erode'
organizationName      :PRINTABLE:'Unixmen'
organizationalUnitName:PRINTABLE:'server'
commonName            :PRINTABLE:'client'
name                  :PRINTABLE:'EasyRSA'
emailAddress          :IA5STRING:'sk@unixmen.com'
Certificate is to be certified until Mar 23 12:23:44 2024 GMT (3650 days)
Sign the certificate? [y/n]:y ----> Type Y and Press Enter

1 out of 1 certificate requests certified, commit? [y/n]y ----> Type Y and Press Enter
Write out database with 1 new entries
Data Base Updated

Generate Diffie Hellman Parameter

Enter the following command to generate DH parameter.
./build-dh
Sample output:
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
The necessary keys and certificates will be generated in the /etc/openvpn/easy-rsa/keys/ directory. Copy the following certificate and key files to the /etc/openvpn/ directory.
  • ca.crt
  • dh2048.pem
  • server.crt
  • server.key
Go to the directory /etc/openvpn/easy-rsa/keys/ and enter the following command to transfer the above files to /etc/openvpn/directory.
cd /etc/openvpn/easy-rsa/keys/
cp dh2048.pem ca.crt server.crt server.key /etc/openvpn/
And then, you must copy all client certificates and keys to the remote VPN clients in order to authenticate to the VPN server. In our case, we have generated certificates and keys to only one client, so we have to copy the following files to the VPN client.
  • ca.crt
  • client.crt
  • client.key
As I mentioned before, I have another system running with CentOS 6.5 that acts as my VPN client. Make sure you have installed openvpn package on your client systems. Then, copy the above files to your VPN client system, using the following command:
scp ca.crt client.crt client.key root@192.168.1.101:/etc/openvpn
Copy the keys with caution. If anyone have chances to get the keys, they can easily intrude and get full access to your virtual private network.

Remove Client access to VPN server

If you want to remove a user’s access to the VPN server, enter the following command:
. /etc/openvpn/easy-rsa/2.0/vars
. /etc/openvpn/easy-rsa/2.0/revoke-full client
The above commands remove the user who have the certificate to access the VPN server.

Configuring VPN Server

Now, we have to configure our VPN server. Copy the file server.conf file to /etc/openvpn/ directory.
cp /usr/share/doc/openvpn-2.3.2/sample/sample-config-files/server.conf /etc/openvpn/
Edit file server.conf,
vi /etc/openvpn/server.conf
Find and uncomment the following lines to route client systems traffic through OpenVPN server.
[...]

# Substitute 2048 for 1024 if you are using
# 2048 bit keys.
dh dh2048.pem

[...]

push "redirect-gateway def1 bypass-dhcp"

[...]
Also, Uncomment and change the DNS servers to reflect your own DNS values. Here I am using Google public DNS servers.
[...]

push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"

[...]
Uncomment the following lines:
[...]

user nobody
group nobody

[...]
Save and close the file.
Then we need to copy and edit the client.conf file. We need this file to be transferred to the VPN clients. First copy the file to any location (ex. /home directory).
cp /usr/share/doc/openvpn-2.3.2/sample/sample-config-files/client.conf /home/
Edit file client.conf,
vi /home/client.conf
Set the VPN server host name/IP address:
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote 192.168.1.2 1194
Here 192.168.1.2 is my VPN server IP address.
Next, Copy the client.conf file to your client system.
scp /home/client.conf root@192.168.1.101:/etc/openvpn

IP forwarding and routing Configuration

Edit sysctl.conf file,
vi /etc/sysctl.conf
Find the following line and set value “1” to enable IP forwarding.
# Controls IP packet forwarding
net.ipv4.ip_forward = 1
Run the following command to apply the sysctl changes.
sysctl -p
Adjust iptables to forward traffic through VPN properly.
Enter the following commands one by one:
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
Save the iptables changes using command:
service iptables save
service iptables restart
Finally, start openvpn service and make it to start automatically on every reboot using the following commands:
service openvpn start
chkconfig openvpn on
At this time, you should have a working OpenVPN server. Next, let us move to client side configuration.
Verify if VPN interface(tun0) is created using ifconfig command:
ifconfig
Sample output:
eth0      Link encap:Ethernet  HWaddr 08:00:27:46:36:62  
          inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe46:3662/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:604 errors:0 dropped:0 overruns:0 frame:0
          TX packets:100 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:44166 (43.1 KiB)  TX bytes:14434 (14.0 KiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

Part Two – VPN Client side configuration

Here, I use CentOS 6.5 as my VPN client system. And, it’s actual IP address is 192.168.1.101/24.

Install OpenVPN

Enter the following command from the Terminal to install openvpn package.
yum install openvpn
After installing openvpn, start the service and make it to run automatically on every reboot.
service openvpn start
chkconfig openvpn on
Now, check if tun0(VPN interface) is created.
ifconfig
Sample output:
eth0      Link encap:Ethernet  HWaddr 08:00:27:BE:25:49  
          inet addr:192.168.1.101  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:febe:2549/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:537 errors:0 dropped:0 overruns:0 frame:0
          TX packets:387 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:52177 (50.9 KiB)  TX bytes:50170 (48.9 KiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:10.8.0.6  P-t-P:10.8.0.5  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
As you see in the above output, the VPN server has automatically assigned IP address 10.8.0.6 to my VPN client.
Check if you can ping your VPN server from client system.
ping 10.8.0.1
10.8.0.1 is my VPN server tun0 address.
Sample output:
PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
64 bytes from 10.8.0.1: icmp_seq=1 ttl=64 time=9.61 ms
64 bytes from 10.8.0.1: icmp_seq=2 ttl=64 time=7.17 ms
64 bytes from 10.8.0.1: icmp_seq=3 ttl=64 time=4.87 ms
That’s it. Now the VPN server and client are ready. Connect to your VPN server securely.

chattr & lsattr immutable undeleteable

  • a – append only: Writing to a file will only allow the file to be opened in append mode for writing. That is you cannot redirect output to overwrite the file, only append to it. Most normal file edit operations, like opening the file with a text editor, will most likely fail as the program will attempt to overwrite the file with the changes and “permission denied” will be displayed. This attribute can only be set by an account with superuser privileges.
  • A – Do not update Atime – access time. When the file is accessed do not update the access time (atime) attribute. This attribute can be a little tricky because if you want to see it in action you need to be aware of a few things. The behavior of atime is determine by how the file system is mounted. With noatime set the access time of the file is not updated when the file is accessed. With atime set use the kernel defaults for how atime is set. Now it could be set in strict mode where atime is always updated when the file is accesses or with relatime which only update the access time should it be older than the modification time when the file is accessed. So if you are monitoring the atime with stat on a file and you are accessing the file and not seeing this time stamp change, chances are the file system you are on is mounted with noatime or relatime set. You would actually have to modify the file and then access it (e.g; cat the file) before the atime would change.
  • c – compressed attribute: Compress sets the file to be compressed when written to on the disk. Data written to the file is compressed by the kernel before the file is written and when read, the file is uncompressed by the kernel for the read. Note that setting this attribute can incur overhead as the file will need to be compressed and uncompressed when written to or accessed. Note that this attribute is not honored by ext2 and ext3 file systems.
  • C – no copy-on-write: The standard behavior on most Linux file systems is that when a file is opened by multiple tasks at one time, instead of creating multiple copies of the information for each task, a pointer to the shared resource is used. Should a task write to the file, then a private copy is broken off for that task instead of manipulating the shared resource. This behavior can be turned off by setting the C attribute so that a separate, private copy is never created.
  • d -no dump: This marks the file as not being a candidate for backups when the dump command is used.
  • D – Sychronous Directory Updates: When a change is made to the file changes are written synchronously to the disk. What this means is that any changes to a file are immediately written to disk and available. This is particularly useful in a networked situation where multiple systems may be accessing a share. When a file is created in that share the directory is immediately updated so that it is visible to all systems accessing the share.
  • e – extents: This attribute indicates that the file is using extents for mapping the blocks on disk. Extents replaced traditional block mapping schemes (found in ext2 and ext3) and define a contiguous range of physical blocks for storage of the data. This attribute is set by the file system and cannot be altered by chattr.
  • E – This is an experimental attribute that may be set by compression programs to indicate that a compressed file has a compression error. This attribute cannot be set or changed with chattr.
  • h – This is not an attribute you can set. Its presence indicates that the file is storing its blocks in units of the file system block size as opposed to the units of sectors. This is shown when a file is, or was at one time, larger than 2TB.
  • i – Immutable: This renders the file impervious to change. The file cannot be written to, appended to, or deleted. It cannot be renamed and it cannot have a link created to it. This attribute can only be set by a superuser account.
  • I - Directory is being indexed: This attribute is not something you can set with chattr. What this indicates is that the directory is being indexed using hashed trees.
  • j – Data journaling: If the file system is mounted with the data=ordered or data=writeback options enabled then this attribute will force the data to be written to the ext3 journal before being written to the file. If the share is mounted with data=journal, than this attribute has no effect as that is the way data=journal behaves.
  • s – Secure deletion: When the file is deleted the blocks the file used are zeroed out. This attribute is not honored by ext2 and ext3 file systems.
  • S – Sychronous Updates: With synchronous update attribute set any changes to the file are immediately written to the disk. Otherwise, changes to the file are cached and then updated at a later time.
  • t- no tail merging: Tail merging, or block sub-allocation  is when a single block is used to hold the tail end of a files data. File systems are formatted into blocks for storage. The default in most Linux systems if 4KB blocks. Most files do not evenly divide into the block values resulting in the last, or tail, block of the file containing empty space. Block sub-allocation is a behavior of some file systems to aggregate the tails of multiple blocks into a single block thus freeing up the blocks those file ends would have consumed. This no tail merging attribute turns this feature off on the file.
  • T – Top of directory hierarchy: This attribute works with Orlov’s block allocator algorithm. The idea is that storing files in related directories closer together will result in faster disk access. An apt example is home directories. By grouping files with their home directories on a disk theoretically most access should be sped up. Otherwise, if directories and unrelated files are grouped together then disk access to related files will take longer. This flag will attempt to force sub-directories to be unrelated and should be spread apart.
  • u – Undeletable: This attribute sets the file to be recoverable should it be deleted, the contents of the file are actually saved. This option is not available to ext2 and ext3 file systems. This is a hold over from extfs.
A file or directories attributes can be viewed with the lsattr command. This command by itself acts like a directory listing showing all the files in the current working directory and their attributes. Specifying a single file will show only the attributes of that file. The output will look something like this:
lsattr test.txt
Produces:
————-e– test.txt
To fill in the dashes, should these values be set:
suS-iadAcj-t-e– test.txt
The lsattr command has a few flags you can pass:
  • -R – recursively list attributes of directories and their contents
  • -a – list all files in the directory including hidden files
  • -d – suppress listing contents of directories and just list directories like other files
  • -V – display version of lsattr
  • -v – display the file’s version/generation number
The version generation number is typically handled by the file system. This number is handy in networked file systems like NFS where the version number can be checked to see if a file has been changed or deleted by another user in situations where multiple users are accessing the file.
File system attributes can be manipulated by the chattr command. The command works similarly to chmod in that it requires that the change in attributes and a file or list of files be passed to it. Changing attributes can be done with:
  • + – set attribute
  • - – remove attribute
  • = – force these attributes
Thus to add the append attribute to test.txt:
chattr +a test.txt
Remember, this attribute can only be added by a superuser account like root.
To remove the append attribute:
chattr -a test.txt
Using the = to set attributes will force only those attributes to be applied. If there are already attributes that are applied to the file those will be removed if not specified by in the chattr command. The caveat here is that only those attributes that can be set with the chattr will be altered. Trying to set or remove the h attribute will fail as this can only be set by the file system not with chattr.
There are a few flags that chattr accepts. The -R flag recursively sets the attributes for all files and sub-directories below the specified or current directory.
The -V flag tells chattr to be verbose on what it is doing and will also print the program version.
The -f switch will suppress error message.
The -v switch will allow you to set the version number of a file. It requires the version number to be passed. Unless you know what you are doing, do not use this flag.

Find ports used by program

You are sometimes trying to install or configure a program and bind it to a port and it throws an error. That means some other program is using that particular port. Let’s see how you can check what program is using your system’s ports.
First if you know the number of the port you are interested in you can:
For example let’s check port number 631:
$ sudo lsof –i:631 –n –P
That should give you something like that:
COMMAND   PID USER   FD   TYPE  DEVICE  SIZE/OFF  NODE NAME
cupsd         776 root   10u  IPv6   9353       0t0  TCP [::1]:631 (LISTEN)
cupsd         776 root   11u  IPv4   9354       0t0  TCP 127.0.0.1:631 (LISTEN)
cups-brow      953 root    8u  IPv4   9930      0t0  UDP *:631
In the above, the “-n” parameter prevents automatic conversion of host IP address to host name, and “-P” parameter prohibits conversion of port number to port name. In our example, cupsd and cups-brow processes are using TCP and UDP port number 631, respectively.
If you want a list of all open TCP ports and the programs/processes associated you can type:
$ sudo lsof -i -n -P | grep TCP
On the table resulting from it, on the left column it has the processes and on the right the ports.
- See more at: http://www.unixmen.com/check-program-using-port-via-terminal/#sthash.RJSMJDQE.dpuf