One place for hosting & domains

      How To Create a Self-Signed SSL Certificate for Apache in Debian 10


      Introduction

      TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to wrap normal traffic in a protected, encrypted wrapper.

      Using this technology, servers can send traffic safely between servers and clients without the possibility of messages being intercepted by outside parties. The certificate system also assists users in verifying the identity of the sites that they are connecting with.

      In this guide, we will show you how to set up a self-signed SSL certificate for use with an Apache web server on Debian 10.

      Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers, users cannot use the certificate to validate the identity of your server automatically.

      A self-signed certificate may be appropriate if you do not have a domain name associated with your server and for instances where an encrypted web interface is not user-facing. If you do have a domain name, in many cases it is better to use a CA-signed certificate. You can find out how to set up a free trusted certificate with the Let’s Encrypt project here.

      Prerequisites

      Before you begin, you should have a non-root user configured with sudo privileges. You can learn how to set up such a user account by following our Initial Server Setup with Debian 10.

      You will also need to have the Apache web server installed. If you would like to install an entire LAMP (Linux, Apache, MariaDB, PHP) stack on your server, you can follow our guide on setting up LAMP on Debian 10. If you just want the Apache web server, skip the steps pertaining to PHP and MariaDB.

      When you have completed these prerequisites, continue below.

      Step 1 — Creating the SSL Certificate

      TLS/SSL works by using a combination of a public certificate and a private key. The SSL key is kept secret on the server. It is used to encrypt content sent to clients. The SSL certificate is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.

      We can create a self-signed key and certificate pair with OpenSSL in a single command:

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

      You will be asked a series of questions. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The “X.509” is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand.
      • -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen.
      • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart.
      • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.
      • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
      • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
      • -out: This tells OpenSSL where to place the certificate that we are creating.

      As we stated above, these options will create both a key file and a certificate. We will be asked a few questions about our server in order to embed the information correctly in the certificate.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name associated with your server or, more likely, your server’s public IP address.

      The entirety of the prompts will look something like this:

      Output

      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]:Bouncy Castles, Inc. Organizational Unit Name (eg, section) []:Ministry of Water Slides Common Name (e.g. server FQDN or YOUR name) []:server_IP_address Email Address []:admin@your_domain.com

      Both of the files you created will be placed in the appropriate subdirectories under /etc/ssl.

      Step 2 — Configuring Apache to Use SSL

      We have created our key and certificate files under the /etc/ssl directory. Now we just need to modify our Apache configuration to take advantage of these.

      We will make a few adjustments to our configuration:

      1. We will create a configuration snippet to specify strong default SSL settings.
      2. We will modify the included SSL Apache Virtual Host file to point to our generated SSL certificates.
      3. (Recommended) We will modify the unencrypted Virtual Host file to automatically redirect requests to the encrypted Virtual Host.

      When we are finished, we should have a secure SSL configuration.

      Creating an Apache Configuration Snippet with Strong Encryption Settings

      First, we will create an Apache configuration snippet to define some SSL settings. This will set Apache up with a strong SSL cipher suite and enable some advanced features that will help keep our server secure. The parameters we will set can be used by any Virtual Hosts enabling SSL.

      Create a new snippet in the /etc/apache2/conf-available directory. We will name the file ssl-params.conf to make its purpose clear:

      • sudo nano /etc/apache2/conf-available/ssl-params.conf

      To set up Apache SSL securely, we will be using the recommendations by Remy van Elst on the Cipherli.st site. This site is designed to provide easy-to-consume encryption settings for popular software.

      The suggested settings on the site linked to above offer strong security. Sometimes, this comes at the cost of greater client compatibility. If you need to support older clients, there is an alternative list that can be accessed by clicking the link on the page labelled “Yes, give me a ciphersuite that works with legacy / old software.” That list can be substituted for the items copied below.

      The choice of which config you use will depend largely on what you need to support. They both will provide great security.

      For our purposes, we can copy the provided settings in their entirety. We will just make one small change to this and disable the Strict-Transport-Security header (HSTS).

      Preloading HSTS provides increased security, but can have far-reaching consequences if accidentally enabled or enabled incorrectly. In this guide, we will not enable the settings, but you can modify that if you are sure you understand the implications.

      Before deciding, take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically about the “preload” functionality.

      Paste the following configuration into the ssl-params.conf file we opened:

      /etc/apache2/conf-available/ssl-params.conf

      SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
      SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
      SSLHonorCipherOrder On
      # Disable preloading HSTS for now.  You can use the commented out header line that includes
      # the "preload" directive if you understand the implications.
      # Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
      Header always set X-Frame-Options DENY
      Header always set X-Content-Type-Options nosniff
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"
      # Requires Apache >= 2.4.11
      SSLSessionTickets Off
      

      Save and close the file when you are finished.

      Modifying the Default Apache SSL Virtual Host File

      Next, let’s modify /etc/apache2/sites-available/default-ssl.conf, the default Apache SSL Virtual Host file. If you are using a different server block file, substitute its name in the commands below.

      Before we go any further, let’s back up the original SSL Virtual Host file:

      • sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak

      Now, open the SSL Virtual Host file to make adjustments:

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

      Inside, with most of the comments removed, the Virtual Host block should look something like this by default:

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

      <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>
      
              </VirtualHost>
      </IfModule>
      

      We will be making some minor adjustments to the file. We will set the normal things we’d want to adjust in a Virtual Host file (ServerAdmin email address, ServerName, etc.), and adjust the SSL directives to point to our certificate and key files. Again, if you’re using a different document root, be sure to update the DocumentRoot directive.

      After making these changes, your server block should look similar to this:

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

      <IfModule mod_ssl.c>
              <VirtualHost _default_:443>
                      ServerAdmin your_email@example.com
                      ServerName server_domain_or_IP
      
                      DocumentRoot /var/www/html
      
                      ErrorLog ${APACHE_LOG_DIR}/error.log
                      CustomLog ${APACHE_LOG_DIR}/access.log combined
      
                      SSLEngine on
      
                      SSLCertificateFile      /etc/ssl/certs/apache-selfsigned.crt
                      SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
      
                      <FilesMatch ".(cgi|shtml|phtml|php)$">
                                      SSLOptions +StdEnvVars
                      </FilesMatch>
                      <Directory /usr/lib/cgi-bin>
                                      SSLOptions +StdEnvVars
                      </Directory>
      
              </VirtualHost>
      </IfModule>
      

      Save and close the file when you are finished.

      As it stands now, the server will provide both unencrypted HTTP and encrypted HTTPS traffic. For better security, it is recommended in most cases to redirect HTTP to HTTPS automatically. If you do not want or need this functionality, you can safely skip this section.

      To adjust the unencrypted Virtual Host file to redirect all traffic to be SSL encrypted, open the /etc/apache2/sites-available/000-default.conf file:

      • sudo nano /etc/apache2/sites-available/000-default.conf

      Inside, within the VirtualHost configuration blocks, add a Redirect directive, pointing all traffic to the SSL version of the site:

      /etc/apache2/sites-available/000-default.conf

      <VirtualHost *:80>
              . . .
      
              Redirect "/" "https://your_domain_or_IP/"
      
              . . .
      </VirtualHost>
      

      Save and close the file when you are finished.

      That’s all of the configuration changes you need to make to Apache. Next, we will discuss how to update firewall rules with ufw to allow encrypted HTTPS traffic to your server.

      Step 3 — Adjusting the Firewall

      If you have the ufw firewall enabled, as recommended by the prerequisite guides, you might need to adjust the settings to allow for SSL traffic. Fortunately, when installed on Debian 10, ufw comes loaded with app profiles which you can use to tweak your firewall settings

      We can see the available profiles by typing:

      You should see a list like this, with the following four profiles near the bottom of the output:

      Output

      Available applications: . . . WWW WWW Cache WWW Full WWW Secure . . .

      You can see the current setting by typing:

      If you allowed only regular HTTP traffic earlier, your output might look like this:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere WWW ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) WWW (v6) ALLOW Anywhere (v6)

      To additionally let in HTTPS traffic, allow the "WWW Full" profile and then delete the redundant "WWW" profile allowance:

      • sudo ufw allow 'WWW Full'
      • sudo ufw delete allow 'WWW'

      Your status should look like this now:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere WWW Full ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) WWW Full (v6) ALLOW Anywhere (v6)

      With your firewall configured to allow HTTPS traffic, you can move on to the next step where we’ll go over how to enable a few modules and configuration files to allow SSL to function properly.

      Step 4 — Enabling the Changes in Apache

      Now that we've made our changes and adjusted our firewall, we can enable the SSL and headers modules in Apache, enable our SSL-ready Virtual Host, and then restart Apache to put these changes into effect.

      Enable mod_ssl, the Apache SSL module, and mod_headers, which is needed by some of the settings in our SSL snippet, with the a2enmod command:

      • sudo a2enmod ssl
      • sudo a2enmod headers

      Next, enable your SSL Virtual Host with the a2ensite command:

      • sudo a2ensite default-ssl

      You will also need to enable your ssl-params.conf file, to read in the values you’ve set:

      At this point, the site and the necessary modules are enabled. We should check to make sure that there are no syntax errors in our files. Do this by typing:

      • sudo apache2ctl configtest

      If everything is successful, you will get a result that looks like this:

      Output

      Syntax OK

      As long as your output has Syntax OK in it, then your configuration file has no syntax errors and you can safely restart Apache to implement the changes:

      • sudo systemctl restart apache2

      With that, your self-signed SSL certificate is all set. You can now test that your server is correctly encrypting its traffic.

      Step 5 — Testing Encryption

      You’re now ready to test your SSL server.

      Open your web browser and type https:// followed by your server's domain name or IP into the address bar:

      https://server_domain_or_IP
      

      Because the certificate you created isn't signed by one of your browser's trusted certificate authorities, you will likely see a scary looking warning like the one below:

      Apache self-signed cert warning

      This is expected and normal. We are only interested in the encryption aspect of our certificate, not the third party validation of our host's authenticity. Click ADVANCED and then the link provided to proceed to your host anyways:

      Apache self-signed override

      You should be taken to your site. If you look in the browser address bar, you will see a lock with an "x" over it or another similar “not secure” notice. In this case, this just means that the certificate cannot be validated. It is still encrypting your connection.

      If you configured Apache to redirect HTTP to HTTPS, you can also check whether the redirect functions correctly:

      http://server_domain_or_IP
      

      If this results in the same icon, this means that your redirect worked correctly. However, the redirect you created earlier is only a temporary redirect. If you’d like to make the redirection to HTTPS permanent, continue on to the final step.

      Step 6 — Changing to a Permanent Redirect

      If your redirect worked correctly and you are sure you want to allow only encrypted traffic, you should modify the unencrypted Apache Virtual Host again to make the redirect permanent.

      Open your server block configuration file again:

      • sudo nano /etc/apache2/sites-available/000-default.conf

      Find the Redirect line we added earlier. Add permanent to that line, which changes the redirect from a 302 temporary redirect to a 301 permanent redirect:

      /etc/apache2/sites-available/000-default.conf

      <VirtualHost *:80>
              . . .
      
              Redirect permanent "/" "https://your_domain_or_IP/"
      
              . . .
      </VirtualHost>
      

      Save and close the file.

      Check your configuration for syntax errors:

      • sudo apache2ctl configtest

      If this command doesn’t report any syntax errors, restart Apache:

      • sudo systemctl restart apache2

      This will make the redirect permanent, and your site will only serve traffic over HTTPS.

      Conclusion

      You have configured your Apache server to use strong encryption for client connections. This will allow you serve requests securely, and will prevent outside parties from reading your traffic.



      Source link

      How To Use Certbot Standalone Mode to Retrieve Let’s Encrypt SSL Certificates on Debian 10


      Introduction

      Let’s Encrypt is a service that offers free SSL certificates through an automated API. The most popular Let’s Encrypt client is EFF’s Certbot client.

      Certbot offers a variety of ways to validate your domain, fetch certificates, and automatically configure Apache and Nginx. In this tutorial, we’ll discuss Certbot’s standalone mode and how to use it to secure other types of services, such as a mail server or a message broker like RabbitMQ.

      We won’t discuss the details of SSL configuration, but when you are done you will have a valid certificate that is automatically renewed. Additionally, you will be able to automate reloading your service to pick up the renewed certificate.

      Prerequisites

      Before starting this tutorial, you will need:

      • A Debian 10 server, a non-root user with sudo privileges, and a basic firewall, as detailed in this Debian 10 server setup tutorial.
      • A domain name pointed at your server, which you can accomplish by following this documentation on creating DNS records on DigitalOcean.
      • Port 80 or 443 must be unused on your server. If the service you’re trying to secure is on a machine with a web server that occupies both of those ports, you’ll need to use a different mode such as Certbot’s webroot mode or DNS-based challenge mode.

      Step 1 — Installing Certbot

      Debian 10 includes the Certbot client in their default repository, and it should be up-to-date enough for basic use. If you need to do DNS-based challenges or use other newer Certbot features, you should instead install from the buster-backports repo as instructed by the official Certbot documentation.

      Update your package list:

      Use apt to install the certbot package:

      You can test your installation by asking certbot to output its version number:

      Output

      certbot 0.31.0

      Now that we have Certbot installed, let's run it to get our certificate.

      Step 2 — Running Certbot

      Certbot needs to answer a cryptographic challenge issued by the Let's Encrypt API in order to prove we control our domain. It uses ports 80 (HTTP) or 443 (HTTPS) to accomplish this. Open up the appropriate port in your firewall:

      Substitute 443 above if that's the port you're using. ufw will output confirmation that your rule was added:

      Output

      Rule added Rule added (v6)

      We can now run Certbot to get our certificate. We'll use the --standalone option to tell Certbot to handle the challenge using its own built-in web server. The --preferred-challenges option instructs Certbot to use port 80 or port 443. If you're using port 80, you will use the --preferred-challenges http option. For port 443, use --preferred-challenges tls-sni. Finally, we'll use the -d flag to specify the domain we're requesting a certificate for. You can add multiple -d options to cover multiple domains in one certificate.

      We will use the --preferred-challenges http option to demonstrate, but you should use the option that makes sense for your use case. Run the following command with your preferred options to get your certificate:

      • sudo certbot certonly --standalone --preferred-challenges http -d your_domain

      When running the command, you will be prompted to enter an email address and agree to the terms of service. After doing so, you should see a message telling you the process was successful and where your certificates are stored:

      Output

      IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/your_domain/privkey.pem Your cert will expire on 2019-08-28. To obtain a new or tweaked version of this certificate in the future, simply run certbot again. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - 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

      We've got our certificates. Let's take a look at what we downloaded and how to use the files with our software.

      Step 3 — Configuring Your Application

      Configuring your application for SSL is beyond the scope of this article, as each application has different requirements and configuration options, but let's take a look at what Certbot has downloaded for us. Use ls to list out the directory that holds your keys and certificates:

      • sudo ls /etc/letsencrypt/live/your_domain

      You will see the following output:

      Output

      cert.pem chain.pem fullchain.pem privkey.pem README

      The README file in this directory has more information about each of these files. Most often you'll only need two of these files:

      • privkey.pem: This is the private key for the certificate. This needs to be kept safe and secret, which is why most of the /etc/letsencrypt directory has very restrictive permissions and is accessible by only the root user. Most software configuration will refer to this as ssl-certificate-key or ssl-certificate-key-file.
      • fullchain.pem: This is our certificate, bundled with all intermediate certificates. Most software will use this file for the actual certificate, and will refer to it in their configuration with a name like ssl-certificate.

      For more information on the other files present, refer to the Where are my certificates? section of the Certbot docs.

      Some software will need its certificates in other formats or locations, or with other user permissions. It is best to leave everything in the letsencrypt directory, and not change any permissions there (permissions will just be overwritten upon renewal anyway), but sometimes that's not an option. In that case, you'll need to write a script to move files and change permissions as needed. This script will need to be run whenever Certbot renews the certificates, which we'll talk about next.

      Step 4 — Handling Certbot Automatic Renewals

      Let's Encrypt certificates are only valid for ninety days. This is to encourage users to automate the certificate renewal process. The certbot package we installed takes care of this for us by adding a renew script to /etc/cron.d. This script runs twice a day and will renew any certificate that's within thirty days of expiring.

      With our certificates renewing automatically, we still need a way to run other tasks after a renewal. We need to at least restart or reload our server to pick up the new certificates, and as mentioned in Step 3 we may need to manipulate the certificate files in some way to make them work with the software we're using. This is the purpose of Certbot's renew_hook option.

      To add a renew_hook, we need to update Certbot's renewal config file. Certbot remembers all the details of how you first fetched the certificate, and will run with the same options upon renewal. We just need to add in our hook. Open the config file with your favorite editor:

      • sudo nano /etc/letsencrypt/renewal/your_domain.conf

      A text file will open with some configuration options. Add your hook on the last line. In this case, we're using an example that would reload a rabbitmq service:

      /etc/letsencrypt/renewal/your_domain.conf

      renew_hook = systemctl reload rabbitmq
      

      Update the command above to whatever you need to run to reload your server or run your custom file munging script. On Debian, you’ll usually use systemctl to reload a service.

      Save and close the file, then run a Certbot dry run to make sure the syntax is ok:

      • sudo certbot renew --dry-run

      If you see no errors, you're all set. Certbot is set to renew when necessary and run any commands needed to get your service using the new files.

      Conclusion

      In this tutorial, we've installed the Certbot Let's Encrypt client, downloaded an SSL certificate using standalone mode, and enabled automatic renewals with renew hooks. This should give you a good start on using Let's Encrypt certificates with services other than your typical web server.

      For more information, please refer to Certbot's documentation.



      Source link

      How To Create a Self-Signed SSL Certificate for Nginx on Debian 10


      Introduction

      TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to wrap normal traffic in a protected, encrypted wrapper.

      Using this technology, servers can send traffic safely between the server and clients without the possibility of the messages being intercepted by outside parties. The certificate system also assists users in verifying the identity of the sites that they are connecting with.

      In this guide, we will show you how to set up a self-signed SSL certificate for use with an Nginx web server on a Debian 10 server.

      Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers, users cannot use the certificate to validate the identity of your server automatically.

      A self-signed certificate may be appropriate if you do not have a domain name associated with your server and for instances where the encrypted web interface is not user-facing. If you do have a domain name, in many cases it is better to use a CA-signed certificate. To learn how to set up a free trusted certificate with the Let’s Encrypt project, consult How to Secure Nginx with Let’s Encrypt on Debian 10.

      Prerequisites

      Step 1 — Creating the SSL Certificate

      TLS/SSL works by using a combination of a public certificate and a private key. The SSL key is kept secret on the server and is used to encrypt content sent to clients. The SSL certificate is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.

      We can create a self-signed key and certificate pair with OpenSSL in a single command:

      • sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

      You will be asked a series of questions. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The “X.509” is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand.
      • -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen.
      • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Nginx to be able to read the file without user intervention when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart.
      • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.
      • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
      • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
      • -out: This tells OpenSSL where to place the certificate that we are creating.

      As we stated above, these options will create both a key file and a certificate. We will be asked a few questions about our server in order to embed the information correctly in the certificate.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name associated with your server or your server’s public IP address.

      The entirety of the prompts will look something like this:

      Output

      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]:Bouncy Castles, Inc. Organizational Unit Name (eg, section) []:Ministry of Water Slides Common Name (e.g. server FQDN or YOUR name) []:your_domain_or_server_IP_address Email Address []:admin@your_domain.com

      Both of the files you created will be placed in the appropriate subdirectories of the /etc/ssl directory.

      While we are using OpenSSL, we should also create a strong Diffie-Hellman group, which is used in negotiating Perfect Forward Secrecy with clients.

      We can do this by typing:

      • sudo openssl dhparam -out /etc/nginx/dhparam.pem 4096

      This will take a while, but when it’s done you will have a strong DH group at /etc/nginx/dhparam.pem that you can use in your configuration.

      Step 2 — Configuring Nginx to Use SSL

      We have created our key and certificate files under the /etc/ssl directory. Now we just need to modify our Nginx configuration to take advantage of these.

      We will make a few adjustments to our configuration.

      1. We will create a configuration snippet containing our SSL key and certificate file locations.
      2. We will create a configuration snippet containing strong SSL settings that can be used with any certificates in the future.
      3. We will adjust our Nginx server blocks to handle SSL requests and use the two snippets above.

      This method of configuring Nginx will allow us to keep clean server blocks and put common configuration segments into reusable modules.

      Creating a Configuration Snippet Pointing to the SSL Key and Certificate

      First, let’s create a new Nginx configuration snippet in the /etc/nginx/snippets directory.

      To properly distinguish the purpose of this file, let’s call it self-signed.conf:

      • sudo nano /etc/nginx/snippets/self-signed.conf

      Within this file, we need to set the ssl_certificate directive to our certificate file and the ssl_certificate_key to the associated key. Add the following lines to the file:

      /etc/nginx/snippets/self-signed.conf

      ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
      ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
      

      When you’ve added those lines, save and close the file.

      Creating a Configuration Snippet with Strong Encryption Settings

      Next, we will create another snippet that will define some SSL settings. This will set Nginx up with a strong SSL cipher suite and enable some advanced features that will help keep our server secure.

      The parameters we will set can be reused in future Nginx configurations, so we will give the file a generic name:

      • sudo nano /etc/nginx/snippets/ssl-params.conf

      To set up Nginx SSL securely, we will be using the recommendations by Remy van Elst on the Cipherli.st site. This site is designed to provide easy-to-consume encryption settings for popular software.

      Note: The suggested settings on the Cipherli.st site offer strong security. Sometimes this comes at the cost of greater client compatibility. If you need to support older clients, there is an alternative list that you can access by clicking the link on the page labeled Yes, give me a ciphersuite that works with legacy / old software. That list can be substituted for the items below.

      The choice of which config you use will depend largely on what you need to support. They both will provide great security.

      For our purposes, we can copy the provided settings in their entirety. We just need to make a few small modifications.

      First, we will add our preferred DNS resolver for upstream requests. We will use Google’s for this guide.

      Second, we will comment out the line that sets the strict transport security header. Before uncommenting this line, you should take take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically its “preload” functionality. Preloading HSTS provides increased security, but can have far-reaching consequences if accidentally enabled or enabled incorrectly.

      Copy the following into your ssl-params.conf snippet file:

      /etc/nginx/snippets/ssl-params.conf

      ssl_protocols TLSv1.2;
      ssl_prefer_server_ciphers on;
      ssl_dhparam /etc/nginx/dhparam.pem;
      ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
      ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
      ssl_session_timeout  10m;
      ssl_session_cache shared:SSL:10m;
      ssl_session_tickets off; # Requires nginx >= 1.5.9
      ssl_stapling on; # Requires nginx >= 1.3.7
      ssl_stapling_verify on; # Requires nginx => 1.3.7
      resolver 8.8.8.8 8.8.4.4 valid=300s;
      resolver_timeout 5s;
      # Disable strict transport security for now. You can uncomment the following
      # line if you understand the implications.
      # add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
      add_header X-Frame-Options DENY;
      add_header X-Content-Type-Options nosniff;
      add_header X-XSS-Protection "1; mode=block";
      

      Because we are using a self-signed certificate, SSL stapling will not be used. Nginx will output a warning but continue to operate correctly.

      Save and close the file when you are finished.

      Adjusting the Nginx Configuration to Use SSL

      Now that we have our snippets, we can adjust our Nginx configuration to enable SSL.

      We will assume in this guide that you are using a custom server block configuration file in the /etc/nginx/sites-available directory, as outlined in Step 5 of the prerequisite tutorial on installing Nginx. We will use /etc/nginx/sites-available/your_domain for this example. Substitute your configuration filename/domain name as needed.

      Before we go any further, let’s back up our current configuration file:

      • sudo cp /etc/nginx/sites-available/your_domain /etc/nginx/sites-available/your_domain.bak

      Now, open the configuration file to make adjustments:

      • sudo nano /etc/nginx/sites-available/your_domain

      If you followed the prerequisites, your server block will look like this:

      /etc/nginx/sites-available/your_domain

      server {
          listen 80;
          listen [::]:80;
      
          root /var/www/your_domain/html;
          index index.html index.htm index.nginx-debian.html;
      
          server_name your_domain www.your_domain;
      
          location / {
                  try_files $uri $uri/ =404;
          }
      
      }
      

      Your file may be in a different order, and instead of the root and index directives you may have some location, proxy_pass, or other custom configuration statements. This is ok, as we only need to update the listen directives and include our SSL snippets. We will modify this existing server block to serve SSL traffic on port 443, and then create a new server block to respond on port 80 and automatically redirect traffic to port 443.

      Note: We will use a 302 redirect until we have verified that everything is working properly. Afterwards, we can change this to a permanent 301 redirect.

      In your existing configuration file, update the two listen statements to use port 443 and SSL, and then include the two snippet files we created in previous steps:

      /etc/nginx/sites-available/your_domain

      server {
          listen 443 ssl;
          listen [::]:443 ssl;
          include snippets/self-signed.conf;
          include snippets/ssl-params.conf;
      
          root /var/www/your_domain/html;
          index index.html index.htm index.nginx-debian.html;
      
          server_name your_domain www.your_domain;
      
          . . .
      }
      

      Next, paste a second server block into the configuration file, after the closing bracket (}) of the first block:

      /etc/nginx/sites-available/your_domain

      . . .
      server {
          listen 80;
          listen [::]:80;
      
          server_name your_domain www.your_domain;
      
          return 302 https://$server_name$request_uri;
      }
      

      This is a bare-bones configuration that listens on port 80 and performs the redirect to HTTPS. Save and close the file when you are finished editing.

      Step 3 — Adjusting the Firewall

      If you have the ufw firewall enabled, as recommended by the prerequisite guides, you’ll need to adjust the settings to allow for SSL traffic. Luckily, Nginx registers a few profiles with ufw upon installation.

      We can see the available profiles by typing:

      You should see a list like this:

      Output

      Available applications: . . . Nginx Full Nginx HTTP Nginx HTTPS . . .

      You can see the current setting by typing:

      If you followed the prerequisites, it will look like this, meaning that only HTTP traffic is allowed to the web server:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Nginx HTTP ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6)

      To additionally let in HTTPS traffic, we can allow the "Nginx Full" profile and then delete the redundant "Nginx HTTP" profile allowance:

      • sudo ufw allow 'Nginx Full'
      • sudo ufw delete allow 'Nginx HTTP'

      Your status should now look like this:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Nginx Full ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Nginx Full (v6) ALLOW Anywhere (v6)

      With our firewall configured properly, we can move on to testing our Nginx configuration.

      Step 4 — Enabling the Changes in Nginx

      Now that we've made our changes and adjusted our firewall, we can restart Nginx to implement our new changes.

      First, we should check to make sure that there are no syntax errors in our files. We can do this by typing:

      If everything is successful, you will get a result that looks like this:

      Output

      nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/ssl/certs/nginx-selfsigned.crt" nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      Note the warning in the beginning. As discussed earlier, this particular setting throws a warning since our self-signed certificate can't use SSL stapling. This is expected and our server can still encrypt connections correctly.

      If your output matches the above, your configuration file has no syntax errors. We can safely restart Nginx to implement our changes:

      • sudo systemctl restart nginx

      With our Nginx configuration tested, we can move on to testing our setup.

      Step 5 — Testing Encryption

      We're now ready to test our SSL server.

      Open your web browser and type https:// followed by your server's domain name or IP into the address bar:

      https://your_domain_or_server_IP
      

      Because the certificate we created isn't signed by one of your browser's trusted certificate authorities, you will likely see a scary looking warning like the one below (the following appears when using Google Chrome) :

      Nginx self-signed cert warning

      This is expected and normal. We are only interested in the encryption aspect of our certificate, not the third party validation of our host's authenticity. Click "ADVANCED" and then the link provided to proceed to your host:

      Nginx self-signed override

      You should be taken to your site. If you look in the browser address bar, you will see a lock with an "x" over it. In this case, this just means that the certificate cannot be validated. It is still encrypting your connection.

      If you configured Nginx with two server blocks, automatically redirecting HTTP content to HTTPS, you can also check whether the redirect functions correctly:

      http://server_domain_or_IP
      

      If this results in the same icon, this means that your redirect worked correctly.

      Step 6 — Changing to a Permanent Redirect

      If your redirect worked correctly and you are sure you want to allow only encrypted traffic, you should modify the Nginx configuration to make the redirect permanent.

      Open your server block configuration file again:

      • sudo nano /etc/nginx/sites-available/<^>your_domain^>

      Find the return 302 and change it to return 301:

      /etc/nginx/sites-available/your_domain

          return 301 https://$server_name$request_uri;
      

      Save and close the file.

      Check your configuration for syntax errors:

      When you're ready, restart Nginx to make the redirect permanent:

      • sudo systemctl restart nginx

      Conclusion

      You have configured your Nginx server to use strong encryption for client connections. This will allow you serve requests securely, and will prevent outside parties from reading your traffic.



      Source link