CWP Control Web Pannel on Centos 7

CentOS Web Panel – a Free Web Hosting control panel designed for quick and easy management of (Dedicated & VPS) servers minus the chore and effort to use ssh console for every time you want to do something, offers a huge number of options and features for server management in its control panel package.

CentOS 7: Installer for CentOS 7

cd /usr/local/src
wget http://centos-webpanel.com/cwp-el7-latest
sh cwp-el7-latest

If download link doesn’t work then you can use the following:

CentOS 7: http://dl1.centos-webpanel.com/files/cwp-el7-latest

Reboot Server
Reboot your server so that all updates can take affect and CWP gets started.

reboot

CentOS Web Panel Configuration

Log in to your CWP server using the link provided by the installer on your server
CentOS WebPanel Admin GUI at http://SERVER-IP:2030/
Username: root
Password: your root password

– Setup nameservers
– Setup shared ip (must be your public IP address)
– Setup at least one hosting package (or edit default package)
– Setup root email
& now you are ready to host domains…

For additional configuration instruction, please check our wiki/documentation site.
http://wiki.centos-webpanel.com/

Kerio Connect 502 Bad Gateway Timeout using Webmail

Good day, having a timeout issue in your Kerio Connect webmail server running on Microsoft IIS webserver? It’s not Kerio Connect mail server the problem! The problem is something to do with your Microsoft IIS Webserver,,….

Here is the complete error message:

IIS 502 – Web server received an invalid response while acting as a gateway or proxy server.

There is a problem with the page you are looking for, and it cannot be displayed.

When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

Here is a solution to fix this problem when a user is using the webmail part of Kerio Connect, the user get a 502 Gateway Timeout error after 2 min of inactivity!

First you need to open your IIS server configuration in Windows 2012

Locate this …

Now we need to locate the system.webServer > proxy > proxy

Now open the configuration and apply a new timeout value

You have to set the value to 30:00min+ so when a user is connected to Kerio Connect mail server using the webmail Interface..,,, the user will not be disconnected after 2 min of inactivity!

Hint! Always revert back until it work’s!

Don’t forget to click the apply button to add this proxy timeout function active on your IIS webserver.

Enjoy!

Tuned – Automatic Performance

Tuned is a powerful daemon for dynamically auto-tuning Linux server performance based on information it gathers from monitoring use of system components, to squeeze maximum performance out of a server.

It does this by tuning system settings dynamically on the fly depending on system activity, using tuning profiles. Tuning profiles include sysctl configs, disk-elevators configs, transparent hugepages, power management options and your custom scripts.

By default tuned will not dynamically adjust system settings, but you can modify how the tuned daemon operates and allow it to dynamically alter settings based on system usage. You can use the tuned-adm command-line tool to manage the daemon once it is running.

On CentOS/RHEL 7 and Fedora, tuned comes pre-installed and activated by default, but on older version of CentOS/RHEL 6.x, you need to install it.

# yum install tuned

After the installation, you will find following important tuned configuration files.

  • /etc/tuned – tuned configuration directory.
  • /etc/tuned/tuned-main.conf– tuned mail configuration file.
  • /usr/lib/tuned/ – stores a sub-directory for all tuning profiles.

Now you can start or manage the tuned service using following commands.

--------------- On RHEL/CentOS 7 --------------- 
# systemctl start tuned	        
# systemctl enable tuned	
# systemctl status tuned	
# systemctl stop tuned		
--------------- On RHEL/CentOS 6 ---------------
# service tuned start
# chkconfig tuned on
# service tuned status
# service tuned stop

Now you can control tuned using the tunde-adm tool. There are a number of predefined tuning profiles already included for some common use cases. You can check the current active profile with following command.

tuned-adm active

You can get a list of available tuning profiles using following command.

# tuned-adm list

To switch to any of the available profiles for example throughput-performance – a tuning which results into excellent performance across a variety of common server workloads.

# tuned-adm  profile throughput-performance
# tuned-adm active

To use the recommended profile for your system, run the following command.

# tuned-adm recommend

And you can disable all tuning as shown.

# tuned-adm off

That’s all for now! Tuned is a daemon that monitors usage of system components and dynamically auto-tunes a Linux server for maximum performance.

Installing Memcached on CentOS

Introduction

Memory object caching systems like Memcached can optimize backend database performance by temporarily storing information in memory, retaining frequently or recently requested records. In this way, they reduce the number of direct requests to your databases.

Because systems like Memcached can contribute to denial of service attacks if improperly configured, it is important to secure your Memcached servers. In this guide, we will cover how to protect your Memcached server by binding your installation to a local or private network interface and creating an authorized user for your Memcached instance.

Installing Memcached from Official Repositories

If you don’t already have Memcached installed on your server, you can install it from the official CentOS repositories. First, make sure that your local package index is updated:

sudo yum update

Next, install the official package as follows:

sudo yum install memcached

We can also install libmemcached, a library that provides several tools to work with your Memcached server:

sudo yum install libmemcached

Memcached should now be installed as a service on your server, along with tools that will allow you to test its connectivity. We can now move on to securing its configuration settings.

Securing Memcached Configuration Settings

To ensure that our Memcached instance is listening on the local interface 127.0.0.1, we will modify the OPTIONS variable in the configuration file located at /etc/sysconfig/memcached. We will also disable the UDP listener. Both of these actions will protect our server from denial of service attacks.

You can open /etc/sysconfig/memcached with nano:

sudo nano /etc/sysconfig/memcached

Locate the OPTIONS variable, which will initially look like this:

/etc/sysconfig/memcached
. . .
OPTIONS=""

Binding to our local network interface will restrict traffic to clients on the same machine. We will do this by adding -l 127.0.0.1 to our OPTIONS variable. This may be too restrictive for certain environments, but it can make a good starting point as a security measure.

Because UDP protocol is much more effective for denial of service attacks than TCP, we can also disable the UDP listener. To do this, we will add the -U 0 parameter to our OPTIONS variable. The file in full should look like this:

/etc/sysconfig/memcached

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1 -U 0" 

Save and close the file when you are done.

Restart your Memcached service to apply your changes:

sudo systemctl restart memcached

Verify that Memcached is currently bound to the local interface and listening only for TCP connections by typing:

sudo netstat -plunt

You should see the following output:

Output

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
. . .
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      2383/memcached
. . .

This confirms that memcached is bound to the 127.0.0.1 address using only TCP.

Adding Authorized Users

To add authenticated users to your Memcached service, it is possible to use Simple Authentication and Security Layer (SASL), a framework that de-couples authentication procedures from application protocols. We will enable SASL within our Memcached configuration file and then move on to adding a user with authentication credentials.

Configuring SASL Support

We can first test the connectivity of our Memcached instance with the memstat command. This will help us establish that SASL and user authentication are enabled after we make changes to our configuration files.

To check that Memcached is up and running, type the following:

memstat --servers="127.0.0.1"

You should see output like the following:

Output

Server: 127.0.0.1 (11211)
     pid: 3831
     uptime: 9
     time: 1520028517
     version: 1.4.25
     . . .

Now we can move on to enabling SASL. First, we can add the -S parameter to our OPTIONS variable in /etc/sysconfig/memcached, which will enable SASL. Open the file again:

sudo nano /etc/sysconfig/memcached

We will add both the -S and -vv parameters to our OPTIONS variable. The -vv option will provide verbose output to /var/log/memcached, which will help us as we debug. Add these options to the OPTIONS variable as follows:

/etc/sysconfig/memcached
. . .
OPTIONS="-l 127.0.0.1 -U 0 -S -vv" 

Save and close the file.

Restart the Memcached service:

sudo systemctl restart memcached

Next, we can take a look at the logs to be sure that SASL support has been enabled:

sudo journalctl -u memcached

You should see the following line, indicating that SASL support has been initialized:

Output

. . .
Mar 05 18:16:11 memcached-server memcached[3846]: Initialized SASL.
. . .

We can check the connectivity again, but because SASL has been initialized, this command should fail without authentication:

memstat --servers="127.0.0.1"

This command should not produce output. We can type the following to check its status:

echo $?

$? will always return the exit code of the last command that exited. Typically, anything besides 0 indicates process failure. In this case, we should see an exit status of 1, which tells us that the memstat command failed.

Adding an Authenticated User

Now we can download two packages that will allow us to work with the Cyrus SASL Library and its authentication mechanisms, including plugins that support PLAIN authentication schemes. These packages, cyrus-sasl-devel and cyrus-sasl-plain, will allow us to create and authenticate our user. Install the packages by typing:

sudo yum install cyrus-sasl-devel cyrus-sasl-plain

Next, we will create the directory and file that Memcached will check for its SASL configuration settings:

sudo mkdir -p /etc/sasl2
sudo nano /etc/sasl2/memcached.conf 

Add the following to the SASL configuration file:

/etc/sasl2/memcached.conf
mech_list: plain
log_level: 5
sasldb_path: /etc/sasl2/memcached-sasldb2

In addition to specifying our logging level, we will set mech_list to plain, which tells Memcached that it should use its own password file and verify a plaintext password. We will also specify the path to the user database file that we will create next. Save and close the file when you are finished.

Now we will create a SASL database with our user credentials. We will use the saslpasswd2 command to make a new entry for our user in our database using the -c option. Our user will be sammy here, but you can replace this name with your own user. Using the -f option, we will specify the path to our database, which will be the path we set in /etc/sasl2/memcached.conf:

sudo saslpasswd2 -a memcached -c -f /etc/sasl2/memcached-sasldb2 sammy

Finally, we want to give the memcached user ownership over the SASL database:

sudo chown memcached:memcached /etc/sasl2/memcached-sasldb2

Restart the Memcached service:

sudo systemctl restart memcached

Running memstat again will confirm whether or not our authentication process worked. This time we will run it with our authentication credentials:

memstat --servers="127.0.0.1" --username=sammy --password=your_password

You should see output like the following:

Output

Server: 127.0.0.1 (11211)
     pid: 3831
     uptime: 9
     time: 1520028517
     version: 1.4.25
     . . .

Our Memcached service is now successfully running with SASL support and user authentication.

Allowing Access Over the Private Network

We have covered how to configure Memcached to listen on the local interface, which can prevent denial of service attacks by protecting the Memcached interface from exposure to outside parties. There may be instances where you will need to allow access from other servers, however. In this case, you can adjust your configuration settings to bind Memcached to the private network interface.

Limiting IP Access With Firewalls

Before you adjust your configuration settings, it is a good idea to set up firewall rules to limit the machines that can connect to your Memcached server. If you followed the prerequisites and installed FirewallD on your server and do not plan on connecting to Memcached from another host, then you do not need to adjust your firewall rules. Your standalone Memcached instance should be listening on 127.0.0.1, thanks to the OPTIONS variable we defined earlier, and there should therefore be no concerns about incoming traffic. If you plan to allow access to your Memcached server from other hosts, however, then you will need to make changes to your firewall settings using the firewall-cmd command.

Begin by adding a dedicated Memcached zone to your firewalld policy:

sudo firewall-cmd --permanent --new-zone=memcached

Then, specify which port you would like to keep open. Memcached uses port 11211 by default:

sudo firewall-cmd --permanent --zone=memcached --add-port=11211/tcp

Next, specify the private IP addresses that should be allowed to access Memcached. For this, you will need to know your client server’s private IP address:

sudo firewall-cmd --permanent --zone=memcached --add-source=client_server_private_IP

Reload the firewall to ensure that the new rules take effect:

sudo firewall-cmd --reload

Packets from your client’s IP address should now be processed according to the rules in the dedicated Memcached zone. All other connections will be processed by the default public zone.

With these changes in place, we can move on to making the necessary configuration changes to our Memcached service, binding it to our server’s private networking interface.

Binding Memcached to the Private Network Interface

The first step in binding to our server’s private networking interface will be modifying the OPTIONS variable we set earlier.

We can open /etc/sysconfig/memcached again by typing:

sudo nano /etc/sysconfig/memcached

Inside, locate the OPTIONS variable. We can now modify -l 127.0.0.1 to reflect our Memcached server’s private IP:

/etc/sysconfig/memcached
. . .
OPTIONS="-l memcached_servers_private_IP -U 0 -S -vv"

Save and close the file when you are finished.

Restart the Memcached service again:

sudo systemctl restart memcached

Check your new settings with netstat to confirm the change:

sudo netstat -plunt
Output
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
. . .
tcp        0      0 memcached_servers_private_IP:11211         0.0.0.0:*               LISTEN      2383/memcached

Test connectivity from your external client to ensure that you can still reach the service. It is a good idea to also check access from a non-authorized client to ensure that your firewall rules are effective.

Guide to secure SSH on Centos 7

1. Overview

 

SSH is the default secured remote management protocol for almost all of Linux distributions. SSH provides a confidentiality and integrity by data encryption and passwords are no longer sent in plain text over the network. Nevertheless, a default configuration of SSH can put the server in a security risk.

That is why it is important to follow a few simple steps to harden an SSH server that can dramatically reduce the risk.

2. Prerequisites

 

In this document, it is assumed that:

You have already install RHEL/CentOS 7 Linux server up and running.

3. Disable Root Logins

 

For security concern, it is not recommended to use root user to login via SSH over a network. The best approach is to use normal user to login to the server and use command sudo to perform the task that required root privilege. For more detail about Sudo, please check Linux Privilege Delegation With Sudoers. To disable root login via SSH, update file /etc/ssh/sshd_config and restart SSH service as the following.

#vim /etc/ssh/sshd_config
PermitRootLogin no
#systemctl restart sshd

4. Limit User Logins

 

By default, all valid users on the system are able access the server. For security reason, we should limit to only certain users who really need to have SSH access to the server. Add the parameter AllowUsers followed by a space separated list of usernames to file /etc/ssh/sshd_config. In the following example, there are only two users, “john” and “sysadmin” who can remote SSH to the server.

$sudo vim /etc/ssh/sshd_config
AllowUsers  john sysadmin
$sudo systemctl restart sshd

5. Disable Protocol 1

 

Using protocol 1 of SSH is less secure. We should be disabled it and always use protocol 2 only instead. Edit file /etc/ssh/sshd_config and restart SSH service as the following.

$sudo vim /etc/ssh/sshd_config
Protocol 2
$sudo systemctl restart sshd

6. Change Default Port

 

Port 22 is the default SSH listens port for incoming connections. The hacker can constantly scanning the server for port 22, and an effective method is to changing the default SSH port, for example to port 22224 as the following,  to eliminate this attacks.

$sudo vim /etc/ssh/sshd_config
Port 22224

Now we need to check SELinux what ports sshd is allowed to listen on by executing the following command.

$sudo semanage port -l | grep ssh
ssh_port_t                     tcp      22224

To allow sshd to listen on the new port 2223 we have to add a rule to SELinux and restart SSH service as the following

$sudo semanage port -a -t ssh_port_t -p tcp 22224
$sudo systemctl restart sshd

7. Limit Access With Firewall

 

For security enhancement, we should filter the connections with firewall by adding a firewall rule in IPTables to limit access on the changed port 2223 to only an authorized IP addresses. Edit file /etc/sysconfig/iptables and restart IPTable service as the following.

$sudo vim /etc/sysconfig/iptables
-A INPUT -p tcp -m state –state NEW -m tcp -s 192.168.10.0/24 –dport 22224 -j ACCEPT
$sudo systemctl restart iptables

8. Limit Idle Timeout Interval

 

If a timeout period for SSH connections on a server is not setting up, it is a security risk. In many cases, people stay away from their computers without locking the screens and SSH is still connected to the server. Thus, it could be compromise. Edit file /etc/ssh/sshd_config as the following. The timeout interval is in seconds.  So let set it to 300 seconds to have 5 minutes idle timeout.

$sudo vim /etc/ssh/sshd_config
ClientAliveInterval 300
ClientAliveCountMax 0
$sudo systemctl restart sshd

9. Limit Maximum Fail Authentication

 

Limiting a maximum fail authentication with SSH is a good method to stop the password brute-forcing attacks. If a user input the password incorrectly for N-1 times of the limited N time, the SSH remote session will be disconnected and will have to reconnect again. In below configuration, when user incorrectly input the password for times, the remote session  will be disconnected.

$sudo vim /etc/ssh/sshd_config
MaxAuthTries 5
$sudo systemctl restart sshd

10. Limit Listen Address

 

The default configuration of SSH will listens on all available interfaces which it should be limited. If there are multiple interfaces on the server configured with different IP addresses, it is always best to limit the user to login to the server using management IP address only.

$sudo vim /etc/ssh/sshd_config
ListenAddress 192.168.10.10
$sudo systemctl restart sshd

11. Disable Rhosts Files Support

 

File .rhosts is used to control which computers trust other computers for SSH remote access to with a certain user account. If a computer trust another computer, then it will allow a specified user to remote SSH access to the trusted computers without having to enter a password.

$sudo vim /etc/ssh/sshd_config
IgnoreRhosts yes
$sudo systemctl restart sshd

12. Disable Empty Passwords Access

 

In some case, a certain user account on the server might not have set a password or has empty password. It is a best to always disable these users connecting with remote SSH server.

$sudo vim /etc/ssh/sshd_config
PermitEmptyPasswords no
$sudo systemctl restart sshd

13. Disable Host-Based Authentication

 

Host-based authentication allows hosts to authenticate on behalf of all or some of the users using the public key.

$sudo vim /etc/ssh/sshd_config
HostbasedAuthentication no
$sudo systemctl restart sshd

14. Enable Informational Log Level

 

It is good to configure SSH server to log INFO level information. Since SSH is an entry point to our server, it is recommended to log as much as possible, so we will a comprehensive log information when we run into a problem.

$sudo vim /etc/ssh/sshd_config
LogLevel INFO
$sudo systemctl restart sshd

15. Reduce Maximum Start Up Connection

 

Reducing the maximum number of concurrent connections to the SSH daemon can be helpful against a brute-force attack. The setting of MaxStartups 4 tells the ssh server to allow only 4 users to attempt logging in at the same time.

$sudo vim /etc/ssh/sshd_config
MaxStartups 4
$sudo systemctl restart sshd

16. Reduce Login Grace Time

 

When we try to remote SSH a server, the default configuration will us 2 minutes to login. If we do not do any thing or cannot successfully login within 2 minutes, SSH session will be disconnected. The default 2 minutes time to login successfully is too much. we should consider reduce it to 1 minute instead.

$sudo vim /etc/ssh/sshd_config
LoginGraceTime 1m
$sudo systemctl restart sshd

Cannot send email from OpenCart 3.x webform?

It’s not OpenCart 3.x the problem! The problem is your internet hosting company bad mail server configuration and spam security policy control! VERY Complicated stuff to fix but all working good on my side!

Hint: Use MAIL and Port 995 Pop3! and the famous -f email option in OpenCart!

😉

Have a good fun with this one!

MBSTRING PHP 7 conflicts with PHP5

Having problem installing mbstring on your Centos 7 Server running php 5.5.x and php 7.x  In my case php-mbstring for php 7.x is missing!

Solutions:

yum install scl-utils

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

yum install php70-php-mbstring

With this you have PHP7 and php-mbstring extension running next to the other PHP versions!

Don’t forget to restart your apache webserver

systemctl restart httpd

Enjoy!

 

Let’s Encrypt Kerio Connect Mail Server on Windows Server

I had a hard time to figure out how to use Let’s Encrypt SSL Certificate on a Kerio Connect Mail server running on a Windows 2012 R2 Webserver / IIS

The first thing I installed is called Certify the Web!
https://certifytheweb.com/

This tool was already deploy on the Windows 2012 R2 Server, follow the step or dig out how to deploy Certify the Web on your Windows 2012 R2 Server.

The first thing to do! You must request a certificate using Certify the Web for the PRIMARY mail domain name;

So now you have a valid certificate for mail.yourdomain.x

just test it… https://mail.yourdomain.x

Now to use the Let’s Encrypt SSL certificate on your Kerio Connect mail server, you must use a tool to be able to export the .key and .crt file to your Kerio Connect mail server. This tool is called DigiCert Certificate Utility Free for Windows!

https://www.digicert.com/util/

The Next Step is to get our hand on those .key and .crt files

1. Yes, export the private key with this…

2. You must provide a password to your private key…

3. Save the Private Key… You will use this KEY file for Kerio Connect

4. Now export the certificate itself

Again save this file! This will generate the .cer for your Kerio Connect mail server.

You should have now in your directory those files…

Now let see in Kerio Connect what to do!

Now import your .key and .crt files into Kerio Connect SSL Certificate

You have now Kerio Connect using a Let’s Encrypt Certificate that will be valid for a period of 3 months. The down side of this is that you will have to manually repeat this every time the key expired or maybe not! Will see in 3 months 😉

Now your Kerio Connect mail server running on a Windows Server will be able to offer secured SSL email connection!

ENJOY!

Cryptsetup on Centos 7 Server

Linux encryption methods

There are two methods to encrypt your data:

#1: Filesystem stacked level encryption

  1. eCryptfs – It is a cryptographic stacked Linux filesystem. eCryptfs stores cryptographic metadata in the header of each file written, so that encrypted files can be copied between hosts; the file will be decrypted with the proper key in the Linux kernel keyring. This solution is widely used, as the basis for Ubuntu’s Encrypted Home Directory, natively within Google’s ChromeOS, and transparently embedded in several network attached storage (NAS) devices.
  2. EncFS -It provides an encrypted filesystem in user-space. It runs without any special permissions and uses the FUSE library and Linux kernel module to provide the filesystem interface. You can find links to source and binary releases below. EncFS is open source software, licensed under the GPL.

#2: Block device level encryption

  1. Loop-AES – Fast and transparent file system and swap encryption package for linux. No source code changes to linux kernel. Works with 3.x, 2.6, 2.4, 2.2 and 2.0 kernels.
  2. VeraCrypt – It is free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X and Linux based on TrueCrypt codebase.
  3. dm-crypt+LUKS – dm-crypt is a transparent disk encryption subsystem in Linux kernel v2.6+ and later and DragonFly BSD. It can encrypt whole disks, removable media, partitions, software RAID volumes, logical volumes, and files.

In this post, I will explain how to encrypt your partitions using Linux Unified Key Setup-on-disk-format (LUKS) on your Linux based computer or laptop.

Step #1: Install cryptsetup utility

You need to install the following package. It contains cryptsetup, a utility for setting up encrypted filesystems using Device Mapper and the dm-crypt target. Debian / Ubuntu Linux user type the following apt-get command or apt command:
# apt-get install cryptsetup
OR
$ sudo apt install cryptsetup
Sample outputs:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  console-setup console-setup-linux cryptsetup-bin kbd keyboard-configuration xkb-data
Suggested packages:
  dosfstools keyutils
The following NEW packages will be installed:
  console-setup console-setup-linux cryptsetup cryptsetup-bin kbd keyboard-configuration xkb-data
0 upgraded, 7 newly installed, 0 to remove and 0 not upgraded.
Need to get 3,130 kB of archives.
After this operation, 13.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 kbd amd64 2.0.3-2+b1 [343 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 keyboard-configuration all 1.164 [644 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 console-setup-linux all 1.164 [983 kB]
Get:4 http://deb.debian.org/debian stretch/main amd64 xkb-data all 2.19-1 [648 kB]
Get:5 http://deb.debian.org/debian stretch/main amd64 console-setup all 1.164 [117 kB]
Get:6 http://deb.debian.org/debian stretch/main amd64 cryptsetup-bin amd64 2:1.7.3-4 [221 kB]
Get:7 http://deb.debian.org/debian stretch/main amd64 cryptsetup amd64 2:1.7.3-4 [174 kB]
Fetched 3,130 kB in 0s (7,803 kB/s)
Preconfiguring packages ...
Selecting previously unselected package kbd.
(Reading database ... 22194 files and directories currently installed.)
Preparing to unpack .../0-kbd_2.0.3-2+b1_amd64.deb ...
Unpacking kbd (2.0.3-2+b1) ...
Selecting previously unselected package keyboard-configuration.
Preparing to unpack .../1-keyboard-configuration_1.164_all.deb ...
Unpacking keyboard-configuration (1.164) ...
Selecting previously unselected package console-setup-linux.
Preparing to unpack .../2-console-setup-linux_1.164_all.deb ...
Unpacking console-setup-linux (1.164) ...
Selecting previously unselected package xkb-data.
Preparing to unpack .../3-xkb-data_2.19-1_all.deb ...
Unpacking xkb-data (2.19-1) ...
Selecting previously unselected package console-setup.
Preparing to unpack .../4-console-setup_1.164_all.deb ...
Unpacking console-setup (1.164) ...
Selecting previously unselected package cryptsetup-bin.
Preparing to unpack .../5-cryptsetup-bin_2%3a1.7.3-4_amd64.deb ...
Unpacking cryptsetup-bin (2:1.7.3-4) ...
Selecting previously unselected package cryptsetup.
Preparing to unpack .../6-cryptsetup_2%3a1.7.3-4_amd64.deb ...
Unpacking cryptsetup (2:1.7.3-4) ...
Setting up keyboard-configuration (1.164) ...
Setting up xkb-data (2.19-1) ...
Setting up kbd (2.0.3-2+b1) ...
Processing triggers for systemd (232-25+deb9u1) ...
Setting up cryptsetup-bin (2:1.7.3-4) ...
Processing triggers for man-db (2.7.6.1-2) ...
Setting up console-setup-linux (1.164) ...
Created symlink /etc/systemd/system/sysinit.target.wants/keyboard-setup.service → /lib/systemd/system/keyboard-setup.service.
Created symlink /etc/systemd/system/multi-user.target.wants/console-setup.service → /lib/systemd/system/console-setup.service.
Setting up console-setup (1.164) ...
Setting up cryptsetup (2:1.7.3-4) ...
update-initramfs: deferring update (trigger activated)
Processing triggers for systemd (232-25+deb9u1) ...
Processing triggers for initramfs-tools (0.130) ...
update-initramfs: Generating /boot/initrd.img-4.9.0-3-amd64

RHEL / CentOS / Oracle / Scientific Linux user type the following yum command:
# yum install cryptsetup-luks
OR Fedora Linux user use the dnf command:
# dnf install cryptsetup-luks

Step #2: Configure LUKS partition

WARNING! The following command will remove all data on the partition that you are encrypting. You WILL lose all your information! So make sure you backup your data to an external source such as NAS or hard disk before typing any one of the following command.

In this example, I’m going to encrpt /dev/xvdc. Type the following command:
# cryptsetup -y -v luksFormat /dev/xvdc
Sample outputs:

WARNING!
========
This will overwrite data on /dev/xvdc irrevocably.
 
Are you sure? (Type uppercase yes): YES
Enter LUKS passphrase: 
Verify passphrase: 
Command successful.

This command initializes the volume, and sets an initial key or passphrase. Please note that the passphrase is not recoverable so do not forget it.Type the following command create a mapping:
# cryptsetup luksOpen /dev/xvdc backup2
Sample outputs:

Enter passphrase for /dev/xvdc:

You can see a mapping name /dev/mapper/backup2 after successful verification of the supplied key material which was created with luksFormat command extension:
# ls -l /dev/mapper/backup2
Sample outputs:

lrwxrwxrwx 1 root root 7 Oct 19 19:37 /dev/mapper/backup2 -> ../dm-0

You can use the following command to see the status for the mapping:
# cryptsetup -v status backup2
Sample outputs:

/dev/mapper/backup2 is active.
  type:    LUKS1
  cipher:  aes-cbc-essiv:sha256
  keysize: 256 bits
  device:  /dev/xvdc
  offset:  4096 sectors
  size:    419426304 sectors
  mode:    read/write
Command successful.

You can dump LUKS headers using the following command:
# cryptsetup luksDump /dev/xvdc
Sample outputs:

LUKS header information for /dev/xvdc
 
Version:       	1
Cipher name:   	aes
Cipher mode:   	xts-plain64
Hash spec:     	sha256
Payload offset:	4096
MK bits:       	256
MK digest:     	21 07 68 54 77 96 11 34 f2 ec 17 e9 85 8a 12 c3 1f 3e cf 5f 
MK salt:       	8c a6 3d 8c e9 de 16 fb 07 fd 8e d3 72 d7 db 94 
               	7e e0 75 f9 e0 23 24 df 50 26 fb 92 f8 b5 dd 70 
MK iterations: 	222000
UUID:          	4dd563a9-5bff-4fea-b51d-b4124f7185d1
 
Key Slot 0: ENABLED
	Iterations:         	2245613
	Salt:               	05 a8 b4 a2 54 f7 c6 ee 52 db 60 b6 12 7f 2f 53 
	                      	3f 5d 2d 62 fb 5a b1 c3 52 da d5 5f 7b 2d 38 32 
	Key material offset:	8
	AF stripes:            	4000
Key Slot 1: DISABLED
Key Slot 2: DISABLED
Key Slot 3: DISABLED
Key Slot 4: DISABLED
Key Slot 5: DISABLED
Key Slot 6: DISABLED
Key Slot 7: DISABLED

Step #3: Format LUKS partition

First, you need to write zeros to /dev/mapper/backup2 encrypted device. This will allocate block data with zeros. This ensures that outside world will see this as random data i.e. it protect against disclosure of usage patterns:
# dd if=/dev/zero of=/dev/mapper/backup2
The dd command may take many hours to complete. I suggest that you use pv command to monitor the progress:
# pv -tpreb /dev/zero | dd of=/dev/mapper/backup2 bs=128M
Sample outputs:

dd: error writing '/dev/mapper/backup2': No space left on device                                                                                                            ]
 200GiB 0:16:47 [ 203MiB/s] [                      <=>                                                                                                                      ]
1600+1 records in
1599+1 records out
214746267648 bytes (215 GB, 200 GiB) copied, 1008.19 s, 213 MB/s

You can also pass the status=progress option to the dd command:
# dd if=/dev/zero of=/dev/mapper/backup2 status=progress
Sample outputs:

2133934592 bytes (2.1 GB, 2.0 GiB) copied, 142 s, 15.0 MB/s

Next, create a filesystem i.e. format filesystem, enter:
# mkfs.ext4 /dev/mapper/backup2
Sample outputs:

mke2fs 1.42.13 (17-May-2015)
Creating filesystem with 52428288 4k blocks and 13107200 inodes
Filesystem UUID: 1c71b0f4-f95d-46d6-93e0-cbd19cb95edb
Superblock backups stored on blocks: 
	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
	4096000, 7962624, 11239424, 20480000, 23887872

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

To mount the new filesystem at /backup2, enter:
# mkdir /backup2
# mount /dev/mapper/backup2 /backup2
# df -H
# cd /backup2
# ls -l

How do I unmount and secure data?

Type the following commands:
# umount /backup2
# cryptsetup luksClose backup2

How do I mount or remount encrypted partition?

Type the following command:
# cryptsetup luksOpen /dev/xvdc backup2
# mount /dev/mapper/backup2 /backup2
# df -H
# mount

Sample outputs:

Fig.01: Encrypted partition mounted on /backup2
Fig.01: Encrypted partition mounted on /backup2

See shell script wrapper that opens LUKS partition and sets up a mapping for nas devices.

Can I run fsck on LUKS based partition / LVM volume?

Yes, you can use the fsck command On LUKS based systems:
# umount /backup2
# fsck -vy /dev/mapper/backup2
# mount /dev/mapper/backup2 /backu2

See how to run fsck On LUKS (dm-crypt) based LVM physical volume for more details.

How do I change LUKS passphrase (password) for encrypted partition?

Type the following command
### see key slots, max -8 i.e. max 8 passwords can be setup for each device ####
# cryptsetup luksDump /dev/xvdc
# cryptsetup luksAddKey /dev/xvdc

Enter any passphrase: 
Enter new passphrase for key slot: 
Verify passphrase: 

Remove or delete the old password:
# cryptsetup luksRemoveKey /dev/xvdc
Please note that you need to enter the old password / passphrase.

What next?

You can store files or store backups using following software:

Check out related media

This tutorial also available in video format:

(Video 01: cryptsetup command demo)

Conclusion

You now have an encrypted partition for all of your data.

Pros:

  1. LUKS encrypts entire block devices and is therefore well-suited for protecting the contents of mobile devices such as removable storage media (usb pen) or laptop disk drives.
  2. You can also use with your nas server to protect backups.
  3. Intel and AMD cpus with AES-NI (Advanced Encryption Standard Instruction Set) can accelerate dm-crypt based encryption for Linux kernel v2.6.32+. This will speed up harddisk encryption.
  4. Works with swap partition too so that your laptop can use hibernation feature (suspend-to-disk) that writes out the contents of RAM to the swap partition before turning off the machine.

Cons:

  1. LUKS only support upto 8 passwords i.e. only 8 users can have distinct access keys to the same device.
  2. LUKS is also not recommend for applications requiring file-level encryption.

For more information see cryptsetup man page and read RHEL 6.x documentation.