How To Install an SSL Certificate from a Commercial Certificate Authority

Introduction

This tutorial will show you how to acquire and install an SSL certificate from a trusted, commercial Certificate Authority (CA). SSL certificates allow web servers to encrypt their traffic, and also offer a mechanism to validate server identities to their visitors. The main benefit of using a purchased SSL certificate from a trusted CA, over self-signed certificates, is that your site’s visitors will not be presented with a scary warning about not being able to verify your site’s identity.

This tutorial covers how to acquire an SSL certificate from the following trusted certificate authorities:

  • GoDaddy
  • RapidSSL (via Namecheap)

You may also use any other CA of your choice.

After you have acquired your SSL certificate, we will show you how to install it on Nginx and Apache HTTP web servers.

Prerequisites

There are several prerequisites that you should ensure before attempting to obtain an SSL certificate from a commercial CA. This section will cover what you will need in order to be issued an SSL certificate from most CAs.

Money

SSL certificates that are issued from commercial CAs have to be purchased. The best free alternative are certificates issued from Let’s Encrypt. Let’s Encrypt is a new certificate authority that issues free SSL/TLS certificates that are trusted in most web browsers.

Registered Domain Name

Before acquiring an SSL certificate, you must own or control the registered domain name that you wish to use the certificate with. If you do not already have a registered domain name, you may register one with one of the many domain name registrars out there (e.g. Namecheap, GoDaddy, etc.).

Domain Validation Rights

For the basic domain validation process, you must have access to one of the email addresses on your domain’s WHOIS record or to an “admin type” email address at the domain itself. Certificate authorities that issue SSL certificates will typically validate domain control by sending a validation email to one of the addresses on the domain’s WHOIS record, or to a generic admin email address at the domain itself. Some CAs provide alternative domain validation methods, such as DNS- or HTTP-based validation, which are outside the scope of this guide.

If you wish to be issued an Organization Validation (OV) or Extended Validation (EV) SSL certificate, you will also be required to provide the CA with paperwork to establish the legal identity of the website’s owner, among other things.

Web Server

In addition to the previously mentioned points, you will need a web server to install the SSL certificate on. This is the server that is reachable at the domain name for which the SSL certificate will be issued for. Typically, this will be an Apache HTTP, Nginx, HAProxy, or Varnish server. If you need help setting up a web server that is accessible via your registered domain name, follow these steps:

  1. Set up a web server of your choice. For example, a LEMP (Nginx) or LAMP (Apache) server–be sure to configure the web server software to use the name of your registered domain
  2. Configure your domain to use the appropriate nameservers. If your web server is hosted on DigitalOcean, this guide can help you get set up: How To Point to DigitalOcean’s Nameservers from Common Domain Registrars
  3. Add DNS records for your web server to your nameservers. If you are using DigitalOcean’s nameservers, follow this guide to learn how to add the appropriate records: How To Set Up a Host Name with DigitalOcean

Choose Your Certificate Authority

If you are not sure of which Certificate Authority you are going to use, there are a few important factors to consider. At an overview level, the most important thing is that the CA you choose provides the features you want at a price that you are comfortable with. This section will focus more on the features that most SSL certificate buyers should be aware of, rather than prices.

Root Certificate Program Memberships

The most crucial point is that the CA that you choose is a member of the root certificate programs of the most commonly used operating systems and web browsers, i.e. it is a “trusted” CA, and its root certificate is trusted by common browsers and other software. If your website’s SSL certificate is signed by a trusted” CA, its identity is considered to be valid by software that trusts the CA–this is in contrast to self-signed SSL certificates, which also provide encryption capabilities but are accompanied by identity validation warnings that are off-putting to most website visitors.

Most commercial CAs that you will encounter will be members of the common root CA programs, and will say they are compatible with 99% of browsers, but it does not hurt to check before making your certificate purchase. For example, Apple provides its list of trusted SSL root certificates for iOS8 here.

Certificate Types

Ensure that you choose a CA that offers the certificate type that you require. Many CAs offer variations of these certificate types under a variety of, often confusing, names and pricing structures. Here is a short description of each type:

  • Single Domain: Used for a single domain, e.g. example.com. Note that additional subdomains, such as www.example.com, are not included
  • Wildcard: Used for a domain and any of its subdomains. For example, a wildcard certificate for*.example.com can also be used for www.example.com and store.example.com
  • Multiple Domain: Known as a SAN or UC certificate, these can be used with multiple domains and subdomains that are added to the Subject Alternative Name field. For example, a single multi-domain certificate could be used with example.com, www.example.com, and example.net

In addition to the aforementioned certificate types, there are different levels of validations that CAs offer. We will cover them here:

  • Domain Validation (DV): DV certificates are issued after the CA validates that the requestor owns or controls the domain in question
  • Organization Validation (OV): OV certificates can be issued only after the issuing CA validates the legal identity of the requestor
  • Extended Validation (EV): EV certificates can be issued only after the issuing CA validates the legal identity, among other things, of the requestor, according to a strict set of guidelines. The purpose of this type of certificate is to provide additional assurance of the legitimacy of your organization’s identity to your site’s visitors. EV certificates can be single or multiple domain, but not wildcard

This guide will show you how to obtain a single domain or wildcard SSL certificate from GoDaddy and RapidSSL, but obtaining the other types of certificates is very similar.

Additional Features

Many CAs offer a large variety of “bonus” features to differentiate themselves from the rest of the SSL certificate-issuing vendors. Some of these features can end up saving you money, so it is important that you weigh your needs against the offerings carefully before making a purchase. Example of features to look out for include free certificate reissues or a single domain-priced certificate that works for www. and the domain basename, e.g. www.example.com with a SAN of example.com

Generate a CSR and Private Key

After you have all of your prerequisites sorted out, and you know the type of certificate you want to get, it’s time to generate a certificate signing request (CSR) and private key.

If you are planning on using Apache HTTP or Nginx as your web server, use openssl to generate your private key and CSR on your web server. In this tutorial, we will just keep all of the relevant files in our home directory but feel free to store them in any secure location on your server:

cd ~

To generate a private key, called example.com.key, and a CSR, called example.com.csr, run this command (replace the example.com with the name of your domain):

openssl req -newkey rsa:2048 -nodes -keyout example.com.key -out example.com.csr

At this point, you will be prompted for several lines of information that will be included in your certificate request. The most important part is the Common Name field which should match the name that you want to use your certificate with–for example, example.com, www.example.com, or (for a wildcard certificate request) *.example.com. If you are planning on getting an OV or EV certificate, ensure that all of the other fields accurately reflect your organization or business details.

For example:

Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:sammy@example.com

This will generate a .key and .csr file. The .key file is your private key, and should be kept secure. The.csr file is what you will send to the CA to request your SSL certificate.

You will need to copy and paste your CSR when submitting your certificate request to your CA. To print the contents of your CSR, use this command (replace the filename with your own):

cat example.com.csr

Now we are ready to buy a certificate from a CA. We will show two examples, GoDaddy and RapidSSL via Namecheap, but feel free to get a certificate from any other vendor.

Example CA 1: RapidSSL via Namecheap

Namecheap provides a way to buy SSL certificates from a variety of CAs. We will walk through the process of acquiring a single domain certificate from RapidSSL, but you can deviate if you want a different type of certificate.

Note: If you request a single domain certificate from RapidSSL for the www subdomain of your domain (e.g.www.example.com), they will issue the certificate with a SAN of your base domain. For example, if your certificate request is for www.example.com, the resulting certificate will work for both www.example.comand example.com.

Select and Purchase Certificate

Go to Namecheap’s SSL certificate page: https://www.namecheap.com/security/ssl-certificates.aspx.

Here you can start selecting your validation level, certificate type (“Domains Secured”), or CA (“Brand”).

For our example, we will click on the Compare Products button in the “Domain Validation” box. Then we will find “RapidSSL”, and click the Add to Cart button.

At this point, you must register or log in to Namecheap. Then finish the payment process.

Request Certificate

After paying for the certificate of your choice, go to the Manage SSL Certificates link, under the “HiUsername” section.

Namecheap: SSL

Here, you will see a list of all of the SSL certificates that you have purchased through Namecheap. Click on the Activate Now link for the certificate that you want to use.

Namecheap: SSL Management

Now select the software of your web server. This will determine the format of the certificate that Namecheap will deliver to you. Commonly selected options are “Apache + MOD SSL”, “nginx”, or “Tomcat”.

Paste your CSR into the box then click the Next button.

You should now be at the “Select Approver” step in the process, which will send a validation request email to an address in your domain’s WHOIS record or to an administrator type address of the domain that you are getting a certificate for. Select the address that you want to send the validation email to.

Provide the “Administrative Contact Information”. Click the Submit order button.

Validate Domain

At this point, an email will be sent to the “approver” address. Open the email and approve the certificate request.

Download Certificates

After approving the certificate, the certificate will be emailed to the Technical Contact. The certificate issued for your domain and the CA’s intermediate certificate will be at the bottom of the email.

Copy and save them to your server in the same location that you generated your private key and CSR. Name the certificate with the domain name and a .crt extension, e.g. example.com.crt, and name the intermediate certificate intermediate.crt.

The certificate is now ready to be installed on your web server.

Example CA 2: GoDaddy

GoDaddy is a popular CA, and has all of the basic certificate types. We will walk through the process of acquiring a single domain certificate, but you can deviate if you want a different type of certificate.

Select and Purchase Certificate

Go to GoDaddy’s SSL certificate page: https://www.godaddy.com/ssl/ssl-certificates.aspx.

Scroll down and click on the Get Started button.

Go Daddy: Get started

Select the type of SSL certificate that you want from the drop down menu: single domain, multidomain (UCC), or wildcard.

GoDaddy: Certificate Type

Then select your plan type: domain, organization, or extended validation.

Then select the term (duration of validity).

Then click the Add to Cart button.

Review your current order, then click the Proceed to Checkout button.

Complete the registration and payment process.

Request Certificate

After you complete your order, click the SSL Certificates* button (or click on My Account > Manage SSL Certificates in the top-right corner).

Find the SSL certificate that you just purchased and click the Set Up button. If you have not used GoDaddy for SSL certificates before, you will be prompted to set up the “SSL Certificates” product, and associate your recent certificate order with the product (Click the green Set Up button and wait a few minutes before refreshing your browser).

After the “SSL Certificates” Product is added to your GoDaddy account, you should see your “New Certificate” and a “Launch” button. Click on the Launch button next to your new certificate.

Provide your CSR by pasting it into the box. The SHA-2 algorithm will be used by default.

Tick the I agree checkbox, and click the Request Certificate button.

Validate Domain

Now you will have to verify that you have control of the domain, and provide GoDaddy with a few documents. GoDaddy will send a domain ownership verification email to the address that is on your domain’s WHOIS record. Follow the directions in the emails that you are sent to you, and authorize the issuance of the certificate.

Download Certificate

After verifying to GoDaddy that you control the domain, check your email (the one that you registered with GoDaddy with) for a message that says that your SSL certificate has been issued. Open it, and follow the download certificate link (or click the Launch button next to your SSL certificate in the GoDaddy control panel).

Now click the Download button.

Select the server software that you are using from the Server type dropdown menu–if you are using Apache HTTP or Nginx, select “Apache”–then click the Download Zip File button.

Extract the ZIP archive. It should contain two .crt files; your SSL certificate (which should have a random name) and the GoDaddy intermediate certificate bundle (gd_bundle-g2-1.crt). Copy both two your web server. Rename the certificate to the domain name with a .crt extension, e.g. example.com.crt, and rename the intermediate certificate bundle as intermediate.crt.

The certificate is now ready to be installed on your web server.

Install Certificate On Web Server

After acquiring your certificate from the CA of your choice, you must install it on your web server. This involves adding a few SSL-related lines to your web server software configuration.

We will cover basic Nginx and Apache HTTP configurations on Ubuntu 14.04 in this section.

We will assume the following things:

  • The private key, SSL certificate, and, if applicable, the CA’s intermediate certificates are located in a home directory at /home/sammy
  • The private key is called example.com.key
  • The SSL certificate is called example.com.crt
  • The CA intermediate certificate(s) are in a file called intermediate.crt
  • If you have a firewall enabled, be sure that it allows port 443 (HTTPS)

Note: In a real environment, these files should be stored somewhere that only the user that runs the web server master process (usually root) can access. The private key should be kept secure.

Nginx

If you want to use your certificate with Nginx on Ubuntu 14.04, follow this section.

With Nginx, if your CA included an intermediate certificate, you must create a single “chained” certificate file that contains your certificate and the CA’s intermediate certificates.

Change to the directory that contains your private key, certificate, and the CA intermediate certificates (in the intermediate.crt file). We will assume that they are in your home directory for the example:

cd ~

Assuming your certificate file is called example.com.crt, use this command to create a combined file called example.com.chained.crt (replace the highlighted part with your own domain):

cat example.com.crt intermediate.crt > example.com.chained.crt

Now go to your Nginx server block configuration directory. Assuming that is located at/etc/nginx/sites-enabled, use this command to change to it:

cd /etc/nginx/sites-enabled

Assuming want to add SSL to your default server block file, open the file for editing:

sudo vi default

Find and modify the listen directive, and modify it so it looks like this:

    listen 443 ssl;

Then find the server_name directive, and make sure that its value matches the common name of your certificate. Also, add the ssl_certificate and ssl_certificate_key directives to specify the paths of your certificate and private key files (replace the highlighted part with the actual path of your files):

    server_name example.com;
    ssl_certificate /home/sammy/example.com.chained.crt;
    ssl_certificate_key /home/sammy/example.com.key;

To allow only the most secure SSL protocols and ciphers, add the following lines to the file:

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

If you want HTTP traffic to redirect to HTTPS, you can add this additional server block at the top of the file (replace the highlighted parts with your own information):

server {
    listen 80;
    server_name example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

Then save and quit.

Now restart Nginx to load the new configuration and enable TLS/SSL over HTTPS!

sudo service nginx restart

Test it out by accessing your site via HTTPS, e.g. https://example.com.

Apache

If want to use your certificate with Apache on Ubuntu 14.04, follow this section.

Make a backup of your configuration file by copying it. Assuming your server is running on the default virtual host configuration file, /etc/apache2/sites-available/000-default.conf, use these commands to to make a copy:

cd /etc/apache2/sites-available
cp 000-default.conf 000-default.conf.orig

Then open the file for editing:

sudo vi 000-default.conf

Find the <VirtualHost *:80> entry and modify it so your web server will listen on port 443:

<VirtualHost *:443>

Then add the ServerName directive, if it doesn’t already exist (substitute your domain name here):

ServerName example.com

Then add the following lines to specify your certificate and key paths (substitute your actual paths here):

SSLEngine on
SSLCertificateFile /home/sammy/example.com.crt
SSLCertificateKeyFile /home/sammy/example.com.key

If you are using Apache 2.4.8 or greater, specify the CA intermediate bundle by adding this line (substitute the path):

SSLCACertificateFile /home/sammy/intermediate.crt

If you are using an older version of Apache, specify the CA intermediate bundle with this line (substitute the path):

SSLCertificateChainFile /home/sammy/intermediate.crt

At this point, your server is configured to listen on HTTPS only (port 443), so requests to HTTP (port 80) will not be served. To redirect HTTP requests to HTTPS, add the following to the top of the file (substitute the name in both places):

<VirtualHost *:80>
   ServerName example.com
   Redirect permanent / https://example.com/
</VirtualHost>

Save and exit.

Enable the Apache SSL module by running this command:

sudo a2enmod ssl

Now restart Apache to load the new configuration and enable TLS/SSL over HTTPS!

sudo service apache2 restart

Test it out by accessing your site via HTTPS, e.g. https://example.com. You will also want to try connecting via HTTP, e.g. http://example.com to ensure that the redirect is working properly!

Conclusion

Now you should have a good idea of how to add a trusted SSL certificate to secure your web server. Be sure to shop around for a CA that you are happy with!

How To Create a SSL Certificate on Apache for Ubuntu 14.04

Introduction

TLS, or transport layer security, and its predecessor SSL, secure sockets layer, are secure protocols created in order to place normal traffic in a protected, encrypted wrapper.

These protocols allow traffic to be sent safely between remote parties without the possibility of the traffic being intercepted and read by someone in the middle. They are also instrumental in validating the identity of domains and servers throughout the internet by establishing a server as trusted and genuine by a certificate authority.

In this guide, we’ll cover how to create a self-signed SSL certificate for Apache on an Ubuntu 14.04 server, which will allow you to encrypt traffic to your server. While this does not provide the benefit of third party validation of your server’s identity, it fulfills the requirements of those simply wanting to transfer information securely.

Note: You may want to consider using Let’s Encrypt instead of a self-signed certificate. Let’s Encrypt is a new certificate authority that issues free SSL/TLS certificates that are trusted in most web browsers. Check out the tutorial to get started: How To Secure Apache with Let’s Encrypt on Ubuntu 14.04

Prerequisites

Before you begin, you should have some configuration already taken care of.

We will be operating as a non-root user with sudo privileges in this guide. You can set one up by following steps 1-4 in our Ubuntu 14.04 initial server setup guide.

You are also going to need to have Apache installed. If you don’t already have that up and running, you can quickly fix that by typing:

sudo apt-get update
sudo apt-get install apache2

Step One — Activate the SSL Module

SSL support actually comes standard in the Ubuntu 14.04 Apache package. We simply need to enable it to take advantage of SSL on our system.

Enable the module by typing:

sudo a2enmod ssl

After you have enabled SSL, you’ll have to restart the web server for the change to be recognized:

sudo service apache2 restart

With that, our web server is now able to handle SSL if we configure it to do so.

Step Two — Create a Self-Signed SSL Certificate

Let’s start off by creating a subdirectory within Apache’s configuration hierarchy to place the certificate files that we will be making:

sudo mkdir /etc/apache2/ssl

Now that we have a location to place our key and certificate, we can create them both in one step by typing:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt

Let’s go over exactly what this means.

  • openssl: This is the basic command line tool provided by OpenSSL to create and manage certificates, keys, signing requests, etc.
  • req: This specifies a subcommand for X.509 certificate signing request (CSR) management. X.509 is a public key infrastructure standard that SSL adheres to for its key and certificate managment. Since we are wanting to create a new X.509 certificate, this is what we want.
  • -x509: This option specifies that we want to make a self-signed certificate file instead of generating a certificate request.
  • -nodes: This option tells OpenSSL that we do not wish to secure our key file with a passphrase. Having a password protected key file would get in the way of Apache starting automatically as we would have to enter the password every time the service restarts.
  • -days 365: This specifies that the certificate we are creating will be valid for one year.
  • -newkey rsa:2048: This option will create the certificate request and a new private key at the same time. This is necessary since we didn’t create a private key in advance. The rsa:2048 tells OpenSSL to generate an RSA key that is 2048 bits long.
  • -keyout: This parameter names the output file for the private key file that is being created.
  • -out: This option names the output file for the certificate that we are generating.

When you hit “ENTER”, you will be asked a number of questions.

The most important item that is requested is the line that reads “Common Name (e.g. server FQDN or YOUR name)”. You should enter the domain name you want to associate with the certificate, or the server’s public IP address if you do not have a domain name.

The questions portion looks something like this:

Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Your Company
Organizational Unit Name (eg, section) []:Department of Kittens
Common Name (e.g. server FQDN or YOUR name) []:your_domain.com
Email Address []:your_email@domain.com

The key and certificate will be created and placed in your /etc/apache2/ssl directory.

Step Three — Configure Apache to Use SSL

Now that we have our certificate and key available, we can configure Apache to use these files in a virtual host file. You can learn more about how to set up Apache virtual hosts here.

Instead of basing our configuration file off of the 000-default.conf file in the sites-availablesubdirectory, we’re going to base this configuration on the default-ssl.conf file that contains some default SSL configuration.

Open the file with root privileges now:

sudo nano /etc/apache2/sites-available/default-ssl.conf

With the comments removed, the file looks something like this:

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                        SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                        SSLOptions +StdEnvVars
        </Directory>
        BrowserMatch "MSIE [2-6]" \
                        nokeepalive ssl-unclean-shutdown \
                        downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>

This may look a bit complicated, but luckily, we don’t need to worry about most of the options here.

We want to set the normal things we’d configure for a virtual host (ServerAdmin, ServerName, ServerAlias, DocumentRoot, etc.) as well as change the location where Apache looks for the SSL certificate and key.

In the end, it will look something like this. The entries in red were modified from the original file:

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin admin@example.com
        ServerName your_domain.com
        ServerAlias www.your_domain.com
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/apache.crt
        SSLCertificateKeyFile /etc/apache2/ssl/apache.key
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                        SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                        SSLOptions +StdEnvVars
        </Directory>
        BrowserMatch "MSIE [2-6]" \
                        nokeepalive ssl-unclean-shutdown \
                        downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>

Save and exit the file when you are finished.

Step Four — Activate the SSL Virtual Host

Now that we have configured our SSL-enabled virtual host, we need to enable it.

We can do this by typing:

sudo a2ensite default-ssl.conf

We then need to restart Apache to load our new virtual host file:

sudo service apache2 restart

This should enable your new virtual host, which will serve encrypted content using the SSL certificate you created.

Step Five — Test your Setup

Now that you have everything prepared, you can test your configuration by visiting your server’s domain name or public IP address after specifying the https:// protocol, like this:

https://server_domain_name_or_IP

You will get a warning that your browser cannot verify the identity of your server because it has not been signed by one of the certificate authorities that it trusts.

apache ssl warning

This is expected since we have self-signed our certificate. While our certificate will not validate our server for our users because it has had no interaction with a trusted certificate authority, it will still be able to encrypt communication.

Since this is expected, you can hit the “Proceed anyway” button or whatever similar option you have in your browser.

You will now be taken to content in the DocumentRoot that you configured for your SSL virtual host. This time your traffic is encrypted. You can check this by clicking on the lock icon in the menu bar:

apache ssl encrypted

You can see in the middle green section that the connection is encrypted.

Conclusion

You should now have SSL enabled on your website. This will help to secure communication between visitors and your site, but it will warn each user that the browser cannot verify the validity of the certificate.

If you are planning on launching a public site and need SSL, you will be better off purchasing an SSL certificate from a trusted certificate authority.

If you want to learn more about how to configure Apache, click here. Check out this link for more ideas on how to secure your Linux server.

How To Set Up a Basic Iptables Firewall on Centos 6

Intro

This article will show how to create a simple firewall on a Centos VPS. It will only open up ports that we want and close up other services. I will also show how to prevent simpler attacks, and how to let yourself back in to the VPS if you deny access to yourself by accident.

The tutorial is not by any means exhaustive and only shows how to open up a few incoming ports: for apache, SSH and email and close all the others. We will not be blocking any outgoing traffic, and only create a few most common rules to block the usual scripts and bots that look for vulnerable VPS.

iptables is a simple firewall installed on most linux distributions. The linux manual page for iptables says it is an administration tool for IPv4 packet filtering and NAT, which, in translation, means it is a tool to filter out and block Internet traffic. iptables firewall is included by default in Centos 6.4 linux images provided by DigitalOcean.

We will set up firewall one by one rule. To simplify: a firewall is a list of rules, so when an incomming connection is open, if it matches any of the rules, this rule can accept that connection or reject it. If no rules are met, we use the default rule.

Note: This tutorial covers IPv4 security. In Linux, IPv6 security is maintained separately from IPv4. For example, “iptables” only maintains firewall rules for IPv4 addresses but it has an IPv6 counterpart called “ip6tables”, which can be used to maintain firewall rules for IPv6 network addresses.

If your VPS is configured for IPv6, please remember to secure both your IPv4 and IPv6 network interfaces with the appropriate tools. For more information about IPv6 tools, refer to this guide: How To Configure Tools to Use IPv6 on a Linux VPS

Decide which ports and services to open

To start with, we want to know what services we want to open to public. Let’s use the typical web-hosting server: it is a web and email server, and we also need to let ourselves in by SSH server.

First, we want to leave SSH port open so we can connect to the VPS remotely: that is port 22.

Also, we need port 80 and 443 (SSL port) for web traffic. For sending email, we will open port 25 (regular SMTP) and 465 (secure SMTP). To let users receive email, we will open the usual port 110 (POP3) and 995 (secure POP3 port).

Additionally, we’ll open IMAP ports, if we have it installed: 143 for IMAP, and 993 for IMAP over SSL.Note: It is recommended to only allow secure protocols, but that may not be an option, if we cannot influence the mail service users to change their email clients.

Block the most common attacks

DigitalOcean VPSs usually come with the empty configuration: all traffic is allowed. Just to make sure of this, we can flush the firewall rules – that is, erase them all:

iptables -F

We can then add a few simple firewall rules to block the most common attacks, to protect our VPS from script-kiddies. We can’t really count on iptables alone to protect us from a full-scale DDOS or similar, but we can at least put off the usual network scanning bots that will eventually find our VPS and start looking for security holes to exploit. First, we start with blocking null packets.

iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

We told the firewall to take all incoming packets with tcp flags NONE and just DROP them. Null packetsare, simply said, recon packets. The attack patterns use these to try and see how we configured the VPS and find out weaknesses. The next pattern to reject is a syn-flood attack.

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Syn-flood attack means that the attackers open a new connection, but do not state what they want (ie. SYN, ACK, whatever). They just want to take up our servers’ resources. We won’t accept such packages. Now we move on to one more common pattern: XMAS packets, also a recon packet.

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

We have ruled out at least some of the usual patterns that find vulnerabilities in our VPS.

Open up ports for selected services

Now we can start adding selected services to our firewall filter. The first such thing is a localhost interface:

iptables -A INPUT -i lo -j ACCEPT

We tell iptables to add (-A) a rule to the incoming (INPUT) filter table any trafic that comes to localhost interface (-i lo) and to accept (-j ACCEPT) it. Localhost is often used for, ie. your website or email server communicating with a database locally installed. That way our VPS can use the database, but the database is closed to exploits from the internet.

Now we can allow web server traffic:

iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

We added the two ports (http port 80, and https port 443) to the ACCEPT chain – allowing traffic in on those ports. Now, let’s allow users use our SMTP servers:

iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT

Like stated before, if we can influence our users, we should rather use the secure version, but often we can’t dictate the terms and the clients will connect using port 25, which is much more easier to have passwords sniffed from. We now proceed to allow the users read email on their server:

iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT

Those two rules will allow POP3 traffic. Again, we could increase security of our email server by just using the secure version of the service. Now we also need to allow IMAP mail protocol:

iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT

Limiting SSH access

We should also allow SSH traffic, so we can connect to the VPS remotely. The simple way to do it would be with this command:

iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

We now told iptables to add a rule for accepting tcp traffic incomming to port 22 (the default SSH port). It is advised to change the SSH configuration to a different port, and this firewall filter should be changed accordingly, but configuring SSH is not a part of this article.

However, we could do one more thing about that with firewall itself. If our office has a permanent IP address, we could only allow connections to SSH from this source. This would allow only people from our location to connect.

First, find out your outside IP address. Make sure it is not an address from your LAN, or it will not work. You could do that simply by visiting the whatismyip.com site. Another way to find it out is to type:

w

in the terminal, we should see us logged in (if we’re the only one logged in’ and our IP address written down.

The output looks something like this:

root@iptables# w
 11:42:59 up 60 days, 11:21,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root   pts/0    213.191.xxx.xxx  09:27    0.00s  0.05s  0.00s w

Now, you can create the firewall rule to only allow traffic to SSH port if it comes from one source: your IP address:

iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 22 -j ACCEPT

Replace YOUR_IP_ADDRESS with the actuall IP, of course.

We could open more ports on our firewall as needed by changing the port numbers. That way our firewall will allow access only to services we want. Right now, we need to add one more rule that will allow us to use outgoing connections (ie. ping from VPS or run software updates);

iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

It will allow any established outgoing connections to receive replies from the VPS on the other side of that connection. When we have it all set up, we will block everything else, and allow all outgoing connections.

iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP

Now we have our firewall rules in place.

Save the configuration

Now that we have all the configuration in, we can list the rules to see if anything is missing.

iptables -L -n

The -n switch here is because we need only ip addresses, not domain names. Ie. if there is an IP in the rules like this: 69.55.48.33: the firewall would go look it up and see that it was a digitalocean.com IP. We don’t need that, just the address itself. Now we can finally save our firewall configuration:

iptables-save | sudo tee /etc/sysconfig/iptables

The iptables configuration file on CentOS is located at /etc/sysconfig/iptables. The above command saved the rules we created into that file. Just to make sure everything works, we can restart the firewall:

service iptables restart

The saved rules will persist even when the VPS is rebooted.

Flush to unlock yourself

If we made an accident in our configuration, we may have blocked ourselves from accessing the VPS. Perhaps we have put in the incorrect IP address so the firewall does not allow connections from our workstation. Now we can’t reach those rules, and if we saved them, even a restart won’t help us. Luckily, the DO web interface allowes us to connect to server via console:

Console

Once connected, we log in as root and issue the following command:

iptables -F

This will flush the filters, we’ll be able to get in the VPS again.

Conclusion

This article is not exhaustive, and it only scratched the surface of running a simple firewall on a linux machine. It will do enough for a typical web and email server scenario for a developer not familiar with linux command line or iptables.

However, a lot more could be done. There are good tutorials and samples on the internet to help us provide more robust configuration. For production environments, it would be advised to create a more detailed configuration or to have a security expert prepare the configuration.

Hopefully, the short instructions will provide basic security to new VPSs.