How to Setup Let’s Encrypt on Ubuntu 18.04

Reading Time: 3 minutes

Sites with SSL are needed more and more every day. It’s ubiquitious enforcement challenges website encryption and is even an effort that Google has taken up. Certbot and Let’s Encrypt are popular solutions for big and small businesses alike because of the ease of implementation.  Certbot is a software client that can be downloaded on a server, like our Ubuntu 18.04, to install and auto-renew SSLs. It obtains these SSLs by working with the well known SSL provider called Let’s Encrypt. In this tutorial, we’ll be showing you a swift way of getting HTTPS enabled on your site.  Let’s get started!

Pre-flight

 

Step 1: Update apt to ensure we are working with the latest package tool.

apt update && upgrade

 

Step 2: We’ll install the Certbot software, as this will aid in obtaining the SSL (certificates) from Let’s Encrypt.  Type Y when prompted to continue.

sudo apt install certbot

 

Step 3: Installing Certbot’s Apache package is also required. Type Y when prompted to continue.

apt install python-certbot-apache

 

Step 4: Time to attain the SSL from Let’s Encrypt.  Enter your email address and go through the prompts.  This step will look through your /etc/apache2/sites-available/yourdomain.com.conf file, specifically the website name set with the ServerName directive.

Note
If your installation gives the “Failed authorization procedure” message ensure you have followed the steps in the Apache Configuration article and that the A record is set for your domain.

certbot --apache

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: A

Your choice to opt in to their newsletter.
-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o:

 

Jumping off of our Apache Configuratio tutorial, we want both of our domains covered with the option of www and non www for our visitors. We’ll leave the input blank and hit ENTER.

Which names would you like to activate HTTPS for?
-------------------------------------------------------------------------------
1: domain.com
2: www.domain.com
3: domain2.com
4: www.domain2.com
-------------------------------------------------------------------------------
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):

 

In our tutorial we will select the Redirect option, you may choose No redirect if you would still like your site reachable through HTTP.

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):2

 

A congratulation message will appear as well as instructions of where your SSL certificates are, just in case you need them later on.

- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/domain.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/domain.com/privkey.pem
Your cert will expire on 2019-07-16. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all* of
your certificates, run "certbot renew"
- If you like Certbot, please consider supporting our work by:
Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
Donating to EFF:                    https://eff.org/donate-le

 

Step 5: Verify your domain was issued the Let’s Encrypt SSL by visiting your site in the browser.  Be sure to clear your browser if you don’t readily see the SSL lock.

You now have an SSL encrypting the traffic to your site.  A few things to point out:

  • SSLs are valid for 90 days at a time
  • Let’s Encrypt will automatically renew
  • Any notifications from Let’s Encrypt will be sent to the email address specified in the .conf file

Get our fully Managed VPS servers, and you can control Let’s Encrypt through your WHM control panel.  Not only will you get a clean control panel to adjust server aspects but you also get 24/7 support at your fingertips.  See how our servers can make admin tasks easier!

How to Install MariaDB on Ubuntu 18.04

Reading Time: 1 minute

MariaDB is a drop in replacement for MySQL, and its popularity makes for several other applications to work in conjunction with it. If you’re interested in a MariaDB server without the maintenance, then check out our high-availability platform. Otherwise, we’ll be installing MariaDB 10 onto our Liquid Web Ubuntu server, let’s get started! Continue reading “How to Install MariaDB on Ubuntu 18.04”

Things to Do After Installing a Ubuntu Server

Reading Time: 5 minutes

After spinning up a new Ubuntu server you may find yourself looking for a guide of what to do next.  Many times the default setting do not provide the top security that your server should have. Throughout this article we provide you security tips and pose questions to help determine the best kind of setup for your environment.

 

1. Secure the Root User

This should be the very first thing you do when setting up a fresh install of Ubuntu server. Typically setting up a password for the root user is done during the installation process. However, if you should ever find yourself in a position where you have assumed the responsibility of a Ubuntu server, it’s best to reset the password keeping in mind the best practices for passwords.

  • Don’t use English words
  • Use a mixture of symbols and alphanumeric characters
  • Length – based on probability and odds of guessing or cracking a password you can provide the best security after a password gets to a certain length. More than ten characters long is good practice, but even longer passwords with complex characters is a safer way to go.

You can also lock the root user password to effectively keep anything from running as root.

Warning:
Please be sure you already have another administrative user on the system with root or “sudo” privileges before locking the root user.

Depending on your version of Ubuntu the root account may be disabled, simply setting or changing the password for root will enable it with the following.

sudo passwd root

Now we can lock the root account by locking the password with the “-l” flag like the following. This will prevent the root user from being used.

sudo passwd -l root

To unlock the root account, again, just change the password for root to enable it.

sudo passwd root

 

2. Secure SSH Access

Many times, once a server is up and running the default configuration for SSH remote logins are set to allow root to log in. We can make the server more secure than this.

You only need to use the root user to run root or administration level commands on the server. This can still be accomplished by logging into a server over SSH with a regular user, and then switching to the root user after you are already logged into the server.
ssh spartacus@myawesomeserver.com

Once logged in you can switch from the user “spartacus” to the root user.

su -

You can disable SSH login for the root user by making some adjustments in the sshd_config file. Be sure to run all of the following commands as root or with a user with sudo privileges.

vim /etc/ssh/sshd_config

Within this file find the Authentication section and look for the following line:

PermitRootLogin yes

Just change that to:

PermitRootLogin no

For the changes to take effect you will need to restart the SSH service with:

/etc/init.d/ssh restart

You can now test this by logging out of the server and then log in again over SSH with the root user and password. It should deny your attempts to do so. This provides a lot more security as it requires a different user (one that others won’t know and probably cannot guess) to log in to the server over SSH. This provides two values that an attacker would need to know, instead of one vaule, as most hackers know that the root user exists on a Linux server.

Also, the following can also be changed to make SSH access more secure.

vim /etc/ssh/sshd_config

PermitEmptyPasswords no

Make sure that directive is set to “no” so that users without a password can’t log in. Otherwise, the attacker would need only one piece of information while also giving them the ability to get in with just knowledge of a user. This, of course, would also mean they could keep attempting guesses at users as well and very easily log in.

A final caution is to adjust any router or firewall settings to make sure that remote SSH access is forwarded to port 22 and does not directly access port 22. This will eliminate a lot of bots or scripts that will try to log in over SSH directly on port 22 with random usernames and passwords. You may need to refer to your router or server firewall documentation on making sure you forward a higher port than port 22.

 

3. Install a Firewall

By default, later versions of Ubuntu should come with Uncomplicated Firewall or UFW. You can check to see if UFW is installed with the following:

sudo ufw status

That will return a status of active or inactive. If it is not installed you can install it with:

sudo apt-get install ufw

It’s a good idea to think through a list of components that will require access to your server. Is SSH access needed? Is web traffic needed? You will want to enable the services through the firewall that are needed so that incoming traffic can access the server in the way you want it to.

In our example let’s allow SSH and web access.

sudo ufw allow ssh

sudo ufw allow http

Those commands will also open up the ports. You can alternatively use the port method to allow services through that specific port.

sudo ufw allow 80/tcp

That will essentially be the same as allowing the HTTP service. Once you have the services you want listed you can enable the firewall with this.

sudo ufw enable

This may interrupt the current SSH connection if that is how you are logged in so be sure your information is correct, so you don’t get logged out.

Also, ensure you have a good grasp on who really needs access to the server and only add users to the Linux operating system that really need access.

 

4. Understand What You Are Trying to Accomplish

It’s important to think through what you will be using your server for. Is it going to be just a file server? Or a web server? Or a web server that needs to send an email out through forms?

You will want to make a clear outline of what you will be using the server for so you can build it to suit those specific needs. It’s best to only build the server with the services that it will require. When you end up putting extra services that are not needed you run the risk of having outdated software which will only add more vulnerability to the server.

Every component and service you run will need to be secured to it’s best practices. For example, if you’re strictly running a static site, you don’t want to expose vulnerabilities due to an outdated email service.

 

5. Keep the File System Up-To-Date

You will want to make sure your server stays up to date with the latest security patches. While a server can run for a while without much maintenance and things will “just work” you will want to be sure not to adapt a “set it and forget it” mentality.

Regular updates on a Ubuntu server can make sure the system stays secure and up to date. You can use the following to do that.

sudo apt-get update

While installing an Ubuntu server is a great way to learn how to work with a Linux it’s a good idea to learn in an environment that is safe. Furthermore, it’s best not to expose the server to the Internet until you are ready.

A great way to get started is at home where you can access the server from your own network without allowing access to the server through the Internet or your home router.

If and when you do deploy a Ubuntu server you’ll want to keep the above five things in mind. It’s important to know the configuration of the server once it’s deployed so you know what type of access the public can get to and what yet needs to be hardened.

Enjoy learning and don’t be afraid to break something in your safe environment, as the experience can be a great teacher when it’s time to go live.

How Do I Secure My Linux Server?

Reading Time: 6 minutes

Our last article on Ubuntu security suggestions touched on the importance of passwords, user roles, console security, and firewalls. We continue with our last article and while the recommendations below are not unique to Ubuntu specifically (nearly all discussed are considered best practice for any Linux server) but they should be an important consideration in securing your server. Continue reading “How Do I Secure My Linux Server?”

Best Practices for Security on Your New Ubuntu Server: Users, Console and Firewall

Reading Time: 4 minutes

Thank you for taking the time to review this important information. You will find this guide broken down into six major sections that coincide with Ubuntu’s security policy guide. The major topics we talk on throughout these articles are as follows:

User Management

User management is one of the most important aspects of any security plan. Balancing your users’ access requirements against their everyday needs, versus the overall security of the server will demand a clear view of those goals to ensure users have the tools they need to get the job done as well as protect the other users’ privacy and confidentiality. We have three types or levels of user access:

  1. Root: This is the main administrator of the server. The root account has full access to everything on the server.  The root user can lock down or, loosen users roles, set file permissions, and ownership, limit folder access, install and remove services or applications, repartition drives and essentially modify any area of the server’s infrastructure. The phrase “with great power comes great responsibility” comes to mind in reference to the root user.
  2. A sudoer (user): This is a user who has been granted special access to a Linux application called sudo.  The “sudoer” user has elevated rights to run a function or program as another user. This user will be included in a specific user group called the sudo group. The rules this user has access to are defined within the “visudo” file which defines and limits their access and can only be initially modified by the root user.
  3. A user: This is a regular user who has been set up using the adduser command, given access to and, who owns the files and folders within the user /home/user/ directory as defined by the basic settings in the /etc/skel/.profile file.

Linux can add an extreme level of granularity to defined user security levels. This allows for the server’s (root user) administrator to outline and delineate as many roles and user types as needed to meet the requirements set forth by the server owner and its assigned task.

 

Enforce Strong Passwords

Because passwords are one of the mainstays in the user’s security arsenal, enforcing strong passwords are a must. In order to enact this guideline, we can modify the file responsible for this setting located here:  /etc/pam.d/common-password.

To enact this guideline, we can modify the file responsible for this setting by using the ‘chage’ command:

chage -m 90 username

This command simply states that the user’s password must be changed every 90 days.

/lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 lcredit=-1 ucredit=-2 dcredit=-2 ocredit=-1

 

Restrict Use of Old Passwords

Open ‘/etc/pam.d/common-password‘ file under Ubuntu/Debian/Linux Mint.
vi /etc/pam.d/common-passwordAdd the following line to ‘auth‘ section.

auth        sufficient  pam_unix.so likeauth nullok

Add the following line to ‘password‘ section to disallow a user from re-using last five of his or her passwords.

sufficient    pam_unix.so nullok use_authtok md5 shadow remember=5Only the last five passwords are remembered by the server. If you tried to use any of five old passwords, you would get an error like:
Password has been already used. Choose another.

 

Checking Accounts for Empty Passwords

Any account having an empty password means its opened for unauthorized access to anyone on the web and it’s a part of security within a Linux server. So, you must make sure all accounts have strong passwords, and no one has any authorized access. Empty password accounts are security risks, and that can be easily hackable. To check if there were any accounts with an empty password, use the following command.

cat /etc/shadow | awk -F: '($2==""){print $1}'

 

What is Console Security?

Console security simply implies that limiting access to the physical server itself is key to ensuring that only those with the proper access can reach the server. Anyone who has access to the server can gain entry to the server, reboot it, remove hard drives, disconnect cables or even power down the server! To curtail malicious actors with harmful intent, we can make sure that servers are kept in a secure location. Another step we can take is to disable the Ctrl+Alt+Delete function. To accomplish this run the following commands:

systemctl mask ctrl-alt-del.target
systemctl daemon-reload
This forces attackers to take more drastic measures to access the server and also limits accidental reboots.

What is UFW?

UFW is simply a front end for a program called iptables which is the actual firewall itself and, UFW provides an easy means to set up and design the needed protection. Ubuntu provides a default firewall frontend called UFW (Uncomplicated firewall). This is another line of defense to keep unwanted or malicious traffic from actually breaching the internal processes of the server.

 

Firewall Logs

The firewall log is a log file which creates and stores information about attempts and other connections to the server. Monitoring these logs for unusual activity and/or attempts to access the server maliciously will aid in securing the server.

When using UFW, you can enable logging by entering the following command in a terminal:

ufw logging on

To disable logging, simply run the following command:

ufw logging off

To learn more about firewalls, visit our Knowledge Base articles.

We’ve covered the importance of passwords, user roles, console security and firewalls all of which are imperative to protecting your Linux server. Let’s continue onto the next article where we’ll cover AppArmor, certificates, eCryptfs and Encrypted LVM.

 

How to Secure a Site in IIS

Reading Time: 6 minutes

When investigating site infections or defacing on a Windows Servers, the most common root cause is poor file security or poor configuration choices when it comes to how IIS should access file content.  The easiest way to prevent this is to start with a secure site.

Setting up a website in IIS is exceedingly easy, but several of the default settings are not optimum when it comes to security or ease of management.  Further, some practices that used to be considered necessary or standards are no longer or were never necessary, to begin with. As such, we recommend that you follow these steps to set up a website to ensure that it is set up correctly and securely. And while some of these setting or permission changes may seem nitpicky, they go a long way on systems that host multiple domains or multiple tenants as they prevent any cross-site file access.

 

Add the Site to IIS

To add a website in IIS (Internet Information Services),  open up the IIS manager, right-click on Sites, and select Add Website.When adding a site to IIS, we typically recommend using the domain name as the “Site name” for easy identification.  Next, under “Physical path”, you will need to supply the path to where your website content is located or use the “” to navigate to and select the folder.  Configuration options under “Connect as…” and “Test Settings…” do not need to be modified.

When it comes to configuring site bindings, popular belief suggests that you should select a specific IP from the “IP address” drop dropdown; however, that is based on out of date practices typically in relation to how SSLs used to require dedicated IPs.  This is no longer necessary and can actually cause issues when getting into any eplicated or highly available configuration, so it is best to leave IP addresses set to All Unassigned and type the domain name you plan to host in the “Host name” field. Do note that you can only supply one value here; additional host names can be added after creating the site by right-clicking on the site and going to Bindings.  Further, depending on your needs, you may opt to select “https” instead of “http”. To host a site with an SSL, please visit our article on the subject after setting up the site to add an SSL and configure it.

 

Set the Anonymous User

Technically that is all you need to do to set up a site in IIS; however, the site may or may not work, and the security settings on the site are not optimum. The next step in securing your site is to configure the IIS user that will access your files. To do this, you will need to change the associated Anonymous user and make a few security changes on the website’s content folder.

In IIS, select your new site on the left, in the main window double click on Authentication, select Anonymous Authentication, and then click “Edit…” on the right action bar.

 

What is IUSR in IIS?

By default, a new site in IIS utilizes the IUSR account for accessing files.  This account is a built-in shared account typically used by IIS to access file content. This means that it will use the application pool’s identity (user) to access file content.

It may be okay to leave this configured if you only plan on hosting one domain; however, when it comes to hosting multiple domains, this is not secure as it would then be possible for any site using the same account to access files from another site.  As such, and as a standard practice, we recommend switching away from using the IUSR account for sites, and instead selecting “Application pool identity” and clicking OK. Alternately, you could manually create a user on the system for each site; however, then you need to manage credentials for an additional user, need to configure permissions for two users (the anonymous user and the application pool user) and possible complications with password complexity and rotation requirements your server or organization may have.

There is nothing further you need to configure in IIS in terms of security; however, for reference, let’s take a look at the application pool settings really quick.  To check the settings on the application pool, in IIS, select Application Pools on the left menu, select the application pool for the site you created (typically the same name as the name of the site), and then click “Advanced Settings…” on the right action bar.

In here, the related setting is the identity, which by default is “ApplicationPoolIdentity”.  This means to access file content, IIS and the associated application pool will use a hidden, dynamic user based off the name of the application pool to access files.  This user has no associated password, can only be used by IIS, and only has access to files specifically granted to it. As such, it removes the requirement of managing system users and credentials.

 

Set Folder Permissions in IIS

Now, as mentioned, the “ApplicationPoolIdentity” user has very few permissions, so the next and last step is to ensure that the website files have proper security settings set on them. Browse through your file system and find the folder where you plan on hosting your site’s files. Right-click on the folder and go to properties. In the properties interface, select the Security tab.

By default, there are a number of security permissions set up on the folder that are unnecessary and potentially insecure (there may be more than shown here).  To best secure a site, we recommend removing all but the “SYSTEM” and “Administrators” groups and adding the “ApplicationPoolIdentity” user (and possibly any other user you may require, such as an FTP user); however, to do this, you will need to disable inheritance.  To do this, click on “Advanced”, then click on “Disable inheritance”.

 

Here you will get a popup asking if you want to copy the current settings or start with no settings.  Either option can work; however, it is easier to copy the current settings and then remove the unnecessary permissions.  So select “ConvertConcert inherited permissions into explicit permission on this object” and then click OK.

At this point, to remove the unnecessary permissions, click Edit and remove everything other than the “SYSTEM” and “Administrators” groups.  Next, you need to add the “ApplicationPoolIdentity” user to this folder. To do this, click “Add…”. Now, depending on your server configuration, you may get a pop-up asking for you to authenticate to an active directory domain.  Simply click the cancel button a few times until you get the Select Users of Groups screen shown below.

On this screen, you will want to make sure that the “Location” selected is your computer.  If it is not, click “Locations…” and select your computer (should be at the top; you may also need to click cancel on some authentication windows here as well).

The “ApplicationPoolIdentity” user is a hidden user, so it is not possible to search for this user.  As such, you will have to type the username to add it. The username you will need to type is “IIS AppPool\<applicationpoolname>“.  Please see the following example and fill yours out accordingly:

Once you type the user name, click OK.  Now that you’ve added the user, which is by default only granted read permissions, you will want to verify your security settings look similar to the following image, and then click OK.

And with that, you’re done and have a secure site ready to be viewed by the masses without needing to fear that hackers will deface it.

 

Securing within Powershell

As a bonus, if you’re looking to get your fingers wet with some Powershell, the steps covered in this article can also be accomplished on a Windows Server 2012 or newer server through Powershell.  Simply fill out the first two variables with your domain name and the path to your content, and then run the rest of the PowerShell commands to set up the site in IIS and configure folder permissions.

[String]$Domain = ‘<domain_Name>’

[String]$Root = ‘<path_to_your_content>’

Import-Module WebAdministration

#Create App pool & Website
New-WebAppPool -Name $Domain
New-Website -Name $Domain -HostHeader $Domain -PhysicalPath $Root -ApplicationPool $Domain
Set-WebConfigurationProperty -Filter system.webServer/security/authentication/anonymousAuthentication -Location $Domain -PSPath MACHINE/WEBROOT/APPHOST -Name userName -Value ''

#Optionally add www. Binding
New-WebBinding -Name $Domain -HostHeader www.$Domain -ErrorAction

#Remove inheritance (copy)
$ACL = Get-ACL $Root
$ACL.SetAccessRuleProtection($True,$True) | Out-Null
$ACL.Access | ?{ !(($_.IdentityReference -eq 'NT AUTHORITY\SYSTEM') -or ($_.IdentityReference -eq 'BUILTIN\Administrators')) } | %{ $ACL.RemoveAccessRule( $_ ) } | Out-Null
$ACL | Set-ACL

#Add IIS user permissions
$ACL = Get-ACL $Root
$acl.SetAccessRuleProtection($False, $True)
$Rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$Domain", "ReadAndExecute", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($Rule)
$acl | Set-Acl

Additional Notes: In some cases, sites may need additional write or modify permissions on specific files or folders for file uploads, cache files, or other content.  It is important that you do not apply modified permissions to the entire site. Instead, modify specific directories or files as needed. To apply these settings, go to the file or folder that needs modification, right-click on it, and select Properties.  Switch to the Security tab and click Edit. In there, select the user that has the name of the website (liquidweb.com in my example above), select modify under the Allow column, and then click OK. This will give the ApplicationPoolIdentity and IIS the ability to write to or modify the file(s) or folder(s).

Still need additional protection for your Liquid Web server?  Our Server Protection packages provides a suite of security tools especially for Windows servers.  You’ll get routine vulnerability scans, hardened server configurations, anti-Virus and even malware cleanup, should your site get hacked. Don’t wait another vunerable minute, check out how we can protect you.

 

Install and Configure Mod_Security on Ubuntu 16.04 Server

Reading Time: 5 minutes

Mod_security, also commonly called Modsec for short, is a powerful WAF (Web Application Firewall) that integrates directly into Apache’s module system. This direct integration allows the security module to intercept traffic at the earliest stages of a request. Early detection is crucial for blocking malicious requests before they are passed along to web applications hosted by Apache web sites. This provides and extra layer of protection against common threats a server faces. This article will explore the installation of mod_security along with the CRS (Core Rule Set) in a Ubuntu 16.04 LTS Server running Apache 2.4.

Prerequisites

The target system environment must meet the following requirements:

  • Ubuntu 16.04 LTS Server
  • Baseline Apache 2.4 pre-installed
  • Pre-configured Network & Internet Connection
  • Root user shell access (console or SSH)

Additionally, familiarity with the following system administration concepts are necessary:

 

Pre-Flight Checks

Mod_security is a standard module in many Apache-based OS images and may already be installed on the target system. Before we continue, lets first make sure we are running Apache 2.4 and mod_security is not already installed. This is done simply with the following two commands.

Note:
sudo is a prefix to all commands in this documentation. It allows execution of root-level permissions on a command by command basis. If you are not familiar with sudo, you may be prompted for your password to authorize execution one or more of the commands in this outline.

Check Apache’s Version

sudo apache2ctl -v

Example Output:
Server version: Apache/2.4.18 (Ubuntu)
Server built:   2018-06-07T19:43:03

Check if the Security Module is Active

apache2ctl -M | grep security

– If this command returns nothing, mod_security is not installed so proceed to the Installation Section.

– If the command returns security2_module, mod_security is installed so proceed to the Configuration Section.

 

Installation Section

The apt package manager in all Debian-based system (like Ubuntu) makes installation quick and painless. Supply the correct package name, libapache-modsecurity in this case, to the apt command and confirm the installation.

Use Apt to Install the libpache2-modseurity Plugin

sudo apt install libapache2-modsecurity -y

Example Output:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libapache2-mod-security2 libyajl2 modsecurity-crs
Suggested packages:
lua geoip-database-contrib ruby
The following NEW packages will be installed:
libapache2-mod-security2 libapache2-modsecurity libyajl2 modsecurity-crs
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 545 kB of archives.
After this operation, 3,960 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 libyajl2 amd64 2.1.0-2 [19.6 kB] Get:2 http://us.archive.ubuntu.com/ubuntu xenial/universe amd64 libapache2-mod-security2 amd64 2.9.0-1 [314 kB] Get:3 http://us.archive.ubuntu.com/ubuntu xenial/universe amd64 libapache2-modsecurity all 2.9.0-1 [2,006 B] Get:4 http://us.archive.ubuntu.com/ubuntu xenial/universe amd64 modsecurity-crs all 2.2.9-1 [210 kB] Fetched 545 kB in 0s (1,659 kB/s)
Selecting previously unselected package libyajl2:amd64.
(Reading database ... 92965 files and directories currently installed.)
Preparing to unpack .../libyajl2_2.1.0-2_amd64.deb ...
Unpacking libyajl2:amd64 (2.1.0-2) ...
Selecting previously unselected package libapache2-mod-security2.
Preparing to unpack .../libapache2-mod-security2_2.9.0-1_amd64.deb ...
Unpacking libapache2-mod-security2 (2.9.0-1) ...
Selecting previously unselected package libapache2-modsecurity.
Preparing to unpack .../libapache2-modsecurity_2.9.0-1_all.deb ...
Unpacking libapache2-modsecurity (2.9.0-1) ...
Selecting previously unselected package modsecurity-crs.
Preparing to unpack .../modsecurity-crs_2.2.9-1_all.deb ...
Unpacking modsecurity-crs (2.2.9-1) ...
Setting up libyajl2:amd64 (2.1.0-2) ...
Setting up libapache2-mod-security2 (2.9.0-1) ...
apache2_invoke: Enable module security2
Setting up libapache2-modsecurity (2.9.0-1) ...
Setting up modsecurity-crs (2.2.9-1) ...
Processing triggers for libc-bin (2.23-0ubuntu11) ...

Once installed, it’s a simple matter to confirm the security module is being loaded by Apache:

Check if the Security Module is Active

apache2ctl -M | grep security

Example Output:

security2_module (shared)

 

Configuration Section

Now that the base module is installed, we need to configure and enable it. This requires a few steps:

Step 1) Copy the recommended config over as the live config

sudo cp /etc/modsecurity/modsecurity.conf{-recommended,}

Step 2) Modify the live config and change “SecRuleEngine DetectionOnly” to “SecRuleEngine On”

sudo sed -i -e 's/DetectionOnly$/On/i' /etc/modsecurity/modsecurity.conf

Step 3) Check Apache’s config syntax & restart Apache if OK

sudo apache2ctl -t && sudo apache2ctl restart

Example output:

Syntax OK

Apache is now actively running with mod_security in place. However, there are no rules in place for it. The next section goes over configuring these rules.

 

Enable Core Rule Set & Base Rules

The security module is only as good as the rules governing it. To help get started, the libapache2-modsecurity package comes with a companion package (modsecurity-crs). This package contains the Core Rule Set or CRS, which is a basic set of rules that handle some of the most common malicious activity on the Internet today.  The CRS protects against many dangerous types of traffic include, but not limited to:

  • SQL Injections (SQLi)
  • Remote Code Execution (RCE)
  • Cross Site Scripting (XSS)
  • And many other common malicious behavior

 

The CRS gets installed along with the security module. Follow these next steps to enable CRS & it’s Base Rules.

Step 1) Add the following lines to modsecurity.conf with your preferred editor

# ModSecurity Core Rule Set (CRS)
IncludeOptional /usr/share/modsecurity-crs/*.conf
IncludeOptional /usr/share/modsecurity-crs/activated_rules/*.conf

Step 2) Create a symlink in the activated_rules directory for all *.conf files in the base_rules directory

CSRD=/usr/share/modsecurity-crs; for e in $CSRD/base_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done

Step 3) [Optional] Confirm symlinks are in the activated_rules directory

sudo ls /usr/share/modsecurity-crs/activated_rules/*.conf

/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_20_protocol_violations.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_21_protocol_anomalies.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_23_request_limits.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_30_http_policy.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_35_bad_robots.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_40_generic_attacks.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_xss_attacks.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_42_tight_security.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_45_trojans.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_47_common_exceptions.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_49_inbound_blocking.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_50_outbound.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_59_outbound_blocking.conf
/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_60_correlation.conf

Step 4) Check Apache’s config syntax & restart Apache if OK

sudo apache2ctl -t && sudo apache2ctl restart

Example output:

Syntax OK

The server is now configured and actively using the base_rules from the CRS. There are additional rules provided by the CRS package. These additional rules are discussed in greater detail in the next section.

Rule of Thumb:
It is necessary to verify syntax and restart Apache, anytime changes are made to one or more mod_security rules.

 

Enable Additional Rules [Optional]

The Core Rule Set includes many additional rules. These rules are separated into three distinct categories: experimental_rules, optional_rules, and slr_rules. Each category’s rules are contained within their own directory of the same name. Activating these rules is the same process as enabling the base_rules. Create a symlink to the desired rule from the activated_rules directory.  The following commands can be used to quickly enable these rules if needed.

Caution:
Discernment is warranted when enabling additional rules beyond those in the base_rules set. The additional rules, especially experimental_rules, are more likely to encounter false positives, blocking legitimate traffic. The commands below are provided for convenience and is not an endorsement of enabling all rules indiscriminately.

experimental_rules

CSRD=/usr/share/modsecurity-crs; for e in $CSRD/experimental_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done

optional_rules

CSRD=/usr/share/modsecurity-crs; for e in $CSRD/optional_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done

slr_rules

CSRD=/usr/share/modsecurity-crs; for e in $CSRD/slr_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done

 

Disable Rules

To disable rules, delete the symlink within the activated_rules directory that pertains to the rule in question. Once deleted, a quick restart of Apache services is necessary to make the change active.

Example: Delete the application_defects rule then restart Apache.

sudo rm -rf /usr/share/modsecurity-crs/activated_rules/modsecurity_crs_55_application_defects.conf

sudo apache2ctl restart

 

The Most Helpful Humans In Hosting

There is more than one-way Liquid Web can help. Whether it’s contacting our support or providing you the managed services you need to succeed, you can rely on us to be there with you. If you find yourself having trouble with these instructions our support teams are here to help. We pride ourselves on being  The Most Helpful Humans In Hosting™.  Our support teams work diligently with Apache and Mod_security daily. With availability 24 hours a day, 7 days a week, and 365 days a year, we are always available to assist when your tasks become too arduous to tackle on your own. We encourage you to share the burden with our support teams by phone, chat or email. We can help!

 

Fully Managed Servers & Applications

All of the Liquid Web Fully Managed Servers & Applications come with mod_security installed, configured, and managed by our support teams. In addition to the Core Rule Set packaged with mod_security, all of our fully managed server kicks include our very own Liquid Web internal rules. These additional rules protect against further threats that our security engineers have identified attacking servers in the wild. These additional rules are a direct countermeasure against known attack vectors and update when new attacks have been identified. We take care of it all, so you don’t have to worry.

 

 

Server Protection Packages

When standard security is not enough, you don’t have to wage war alone. The Liquid Web Server Protection Packages provides additional server hardening beyond just mod_security rules. These packages offer hardened configurations to maintain the best level of protection against intrusion and other malicious activity. This is merely one of our many security-related Hosting Add-on Services.

Windows Firewall Basics

Reading Time: 6 minutes

A firewall is a program installed on your computer or a piece of hardware that uses a rule set to block or allow access to a computer, server or network. It separates your internal network from the external network (the Internet).

Firewalls can permit traffic to be routed through a specific port to a program or destination while blocking other malicious traffic. A firewall can be a hardware, software, or a blending of both.

Continue reading “Windows Firewall Basics”

How to Upgrade Ubuntu 16.04 to Ubuntu 18.04

Reading Time: 6 minutes

If you are still using Ubuntu version 16.04, you may want to consider updating to the latest Long Term Support release, version 18.04. In this post, we will cover what a Long Term Support release is and why you would want to use it. You will also learn the significant changes between 16.04 and 18.04. Last, but not least, you will also learn how to upgrade your server from Ubuntu 16.04 to Ubuntu 18.04.

Continue reading “How to Upgrade Ubuntu 16.04 to Ubuntu 18.04”

How to Install and Configure Fail2ban on Ubuntu Server 16.04

Reading Time: 4 minutes

Have you ever logged into your server and seen a message such as this?

Last failed login: Fri Dec 28 11:37:02 MST 2018 from 192.168.0.102 on ssh:notty
There were 942 failed login attempts since the last successful login.
Last login: Mon Dec 24 13:35:57 2018 from 192.168.0.101

What happened here? This message is informing me that while I was logged out, there were 942 failed attempts to access my server via SSH! This type of message is a strong indicator that my server was probably under a “brute force” attack. In this type of scenario, an attacker will attempt to randomly guess passwords repeatedly until they get lucky with the correct password. This is one reason why using a secure password is so important! Fear not, Fail2ban can be a fantastic tool for dynamically thwarting these types of brute force attacks. This tutorial will walk you through installing and configuring Fail2ban to help protect sshd from brute force attacks. Let’s dig in!

Note:
The remainder of this tutorial requires you to have root privileges. Start by either logging in as root or prefix these commands with sudo.

 

Installing Fail2ban on Ubuntu Server 16.04 is simple. Run the following two commands to install the program:

apt-get update

apt-get install fail2ban -y

We will start the service, so it is running.

service fail2ban restart

Finally, we check to make sure Fail2ban is running after the restart:

service fail2ban status

The output should display active (running) which indicates the service is up and we’re ready to proceed to configuration.

 

Now that Fail2ban is installed and running, we can define custom rules for what services it protects, and how to handle violations.

First, create a configuration file for Fail2ban. This file doesn’t exist by default, but Fail2ban will look for this file and read the contents if it exists:

touch /etc/fail2ban/jail.local

Now we’ll open the configuration file for editing. We’re using vi as our text editor in this example, but feel free to use nano or whatever text editor you are most comfortable with. (Related: check out our helpful tutorial if you need to brush up on how to use vi.) Run the following command to open the file for editing:

vi /etc/fail2ban/jail.local

Paste in the following contents, and save the file:

[DEFAULT] ignoreip = 127.0.0.1/8 ::1
bantime = 3600
findtime = 600
maxretry = 5
[sshd] enabled = true

Let’s review the options we just set. First, we are telling Fail2ban to ignore IP addresses 127.0.0.1 and ::1. These are the IPv4 and IPv6 addresses for localhost, respectively. For the remaining lines, it is important to understand Fail2ban reads time as seconds in the configuration file. These rules will ban IP addresses for one hour {bantime = 3600}, if they make 5 mistakes {maxretry = 5}, within 10 minutes {findtime = 600}. Finally, we enabled the jail for sshd. Feel free to adjust these numbers to your liking, but please consider the following:

Note:
Setting a ban time of -1 will result in a permanent ban on that IP address. You may need to contact Liquid Web support if you accidentally block yourself from your own server. Consider these options carefully!

Now that we have created a configuration to use, restart Fail2ban so that our new rules are read and utilized:

service fail2ban restart

We will also double check to make sure Fail2ban is running after the restart:

service fail2ban status

Note:
If Fail2ban does not start successfully after creating your configuration file, it is possible you have a typo in the configuration file /etc/fail2ban/jail.local. Check the file contents and try again!

 

At this point, you have successfully installed and configured Fail2ban, congratulations! For the remainder of this tutorial, we will show you how to use to use the program and how to manage IP blocks.

Run the following command to check the status of Fail2ban:

fail2ban-client status

Example output shows you the number of currently configured jails. Right now we have only created a jail for sshd:

Status
|- Number of jail:    1
`- Jail list:    sshd

You can also poll the detailed status of individual jails. This command will check the status of the sshd jail we just configured:

fail2ban-client status sshd

Example output shows no IPs blocked, looks good!

Status for the jail: sshd
|- Filter
|  |- Currently failed:    0
|  |- Total failed:    0
|  `- File list:                 /var/log/auth.log
`- Actions
|- Currently banned:    0
|- Total banned:    0
`- Banned IP list:

Now, for example, I’m going to fail five attempts to SSH to my server. After the fifth failed attempt, my IP should be automatically blocked! The following shows the output from my workstation when I try to SSH to the server after the fifth failed attempt:

ssh root@192.168.0.101
ssh: connect to host 192.168.0.101 port 22: Connection refused

The “connection refused” message indicates that the server’s firewall is now blocking us.

Back on the server, let’s again check the status of the SSH jail by running:

fail2ban-client status sshd

The output shows that my IP has indeed been blocked! Looking at the status, we can see my workstation’s IP address has been added to the “Banned IP list”.

Status for the jail: sshd
|- Filter
|  |- Currently failed:    1
|  |- Total failed:    1
|  `- File list:                 /var/log/auth.log
`- Actions
|- Currently banned:    1
|- Total banned:    1
`- Banned IP list:    192.168.0.102

Finally, we will demonstrate how to remove a banned IP. This is helpful if you have clients that accidentally block themselves from incorrect password attempts. The syntax for this command is as follows:

fail2ban-client set <JAIL NAME> unbanip <IP ADDRESS>

For example, this command will delist 192.168.0.102 from the sshd jail.

fail2ban-client  set sshd unbanip 192.168.0.102

Let’s double check our work and make sure my IP address has been successfully unblocked:

fail2ban-client status sshd

Status for the jail: sshd
|- Filter
|  |- Currently failed:    1
|  |- Total failed:    6
|  `- File list:                 /var/log/auth.log
`- Actions
|- Currently banned:    0
|- Total banned:    1
`- Banned IP list:

That wraps it up for this tutorial! We only discussed protecting sshd in this tutorial, but Fail2ban can be used to help protect all kinds of other services such as httpd. We encourage you to do some further reading and see what it is capable of! Just remember that while Fail2ban is awesome, it is not a replacement for a strong set of firewall rules. When properly configured, however, Fail2ban is a great tool to help further harden your server’s security. Have fun and happy IP blocking!