Tutorial: Configure Apache Web Server on Amazon Linux to use SSL/TLS
Secure Sockets Layer/Transport Layer Security (SSL/TLS) creates an encrypted channel between a web server and web client that protects data in transit from being eavesdropped on. This tutorial explains how to add support manually for SSL/TLS on a single instance of Amazon Linux running Apache web server. The AWS Certificate Manager, not discussed here, is a good option as well, especially if you need to manage several domains or will be offering commercial-grade services.
For historical reasons, web encryption is often referred to as simply SSL. While web browsers still support SSL, its successor protocol TLS is considered to be less vulnerable to attack. Amazon Linux disables SSL version 2 by default, and this tutorial recommends disabling SSL version 3 as well, as described below. For more information about the proposed updated encryption standard, go to RFC7568.
These procedures are intended for use with Amazon Linux. If you are trying to set up a LAMP web server on an instance of a different distribution, this tutorial will not work for you. For information about LAMP web servers on Ubuntu, go to the Ubuntu community documentation ApacheMySQLPHP topic. For information about Red Hat Enterprise Linux, go to the Customer Portal topic Web Servers.
Before you begin this tutorial, complete the following steps:
Launch an Amazon Linux instance. For more information, see Step 1: Launch an Instance.
Configure your security group to allow
HTTP(port 80), and
HTTPS(port 443) connections. For more information, see Setting Up with Amazon EC2.
Install Apache web server. For step-by-step instructions, see Tutorial: Installing a LAMP Web Server on Amazon Linux. Only the http24 package and its dependencies are needed; you can ignore the instructions involving PHP and MySQL.
The SSL/TLS public key infrastructure (PKI) relies on the Domain Name System (DNS) to identify and authenticate web sites. If you plan to use your EC2 instance to host a public web site, you need to register a domain name for your web server or transfer an existing domain name to your Amazon EC2 host. Numerous third-party domain registration and DNS hosting services are available for this, or you may use Amazon Route 53.
Step 1: Enable SSL/TLS on the Server
This procedure takes you through the process of setting up SSL/TLS on Amazon Linux with a self-signed, digital certificate.
To enable SSL/TLS on a server
Connect to your instance and confirm that Apache is running.
sudo service httpd status
If necessary, start Apache.
sudo service httpd start
To ensure that all of your software packages are up to date, perform a quick software update on your instance. This process may take a few minutes, but it is important to make sure you have the latest security updates and bug fixes.
-yoption installs the updates without asking for confirmation. If you would like to examine the updates before installing, you can omit this option.
sudo yum update -y
Now that your instance is current, add SSL/TLS support by installing the Apache module mod_ssl:
sudo yum install -y mod24_ssl
Later in this tutorial you will work with three important files that have been installed:
The configuration file for mod_ssl. It contains "directives" telling Apache where to find encryption keys and certificates, which SSL/TLS protocols to allow, and what encryption algorithms to use.
An automatically generated, 2048-bit RSA private key for your Amazon EC2 host. During installation, OpenSSL used this key to generate a self-signed host certificate, and you can also use it later to generate a certificate signing request (CSR) to submit to a certificate authority (CA).
An automatically generated, self-signed X.509 certificate for your server host. This certificate is useful for testing that Apache is properly set up to use SSL/TLS.
.crtfiles are both in PEM format, with consists of Base64-encoded ASCII characters framed by "BEGIN" and "END" lines, as in this abbreviated example of a certificate:
-----BEGIN CERTIFICATE----- MIIEazCCA1OgAwIBAgICWxQwDQYJKoZIhvcNAQELBQAwgbExCzAJBgNVBAYTAi0t MRIwEAYDVQQIDAlTb21lU3RhdGUxETAPBgNVBAcMCFNvbWVDaXR5MRkwFwYDVQQK DBBTb21lT3JnYW5pemF0aW9uMR8wHQYDVQQLDBZTb21lT3JnYW5pemF0aW9uYWxV bml0MRkwFwYDVQQDDBBpcC0xNzItMzEtMjAtMjM2MSQwIgYJKoZIhvcNAQkBFhVy ... z5rRUE/XzxRLBZOoWZpNWTXJkQ3uFYH6s/sBwtHpKKZMzOvDedREjNKAvk4ws6F0 WanXWehT6FiSZvB4sTEXXJN2jdw8g+sHGnZ8zCOsclknYhHrCVD2vnBlZJKSZvak 3ZazhBxtQSukFMOnWPP2a0DMMFGYUHOd0BQE8sBJxg== -----END CERTIFICATE-----
The file names and extensions are a convenience and have no effect on function; you can call a certificate either
certificate.pem, so long as the related directive in the
ssl.conffile uses the same name.
When you replace the default SSL files with your own customized files, be sure that they are in PEM format.
sudo service httpd restart
Your Apache web server should now support HTTPS (secure HTTP) over port 443. Test it by typing the IP address or fully qualified domain name of your EC2 instance into a browser URL bar with the prefix
https://. Because you are connecting to a site with a self-signed, untrusted certificate, your browser may display a series of warnings.
Override these and proceed to the site. If the default Apache welcome page opens, it means that you have successfully configured SSL/TLS on your server. All data passing between the browser and server is now safely encrypted, as signalled by the lock icon in the browser's URL bar.
To prevent site visitors from encountering warning screens, you need to obtain a certificate that not only encrypts, but also publicly authenticates you as the owner of the site.
Step 2: Obtain a CA-signed Certificate
This section describes the process of generating a certificate signing request (CSR) from a private key, submitting the CSR to a certificate authority (CA), obtaining a signed certificate, and configuring Apache to use it.
A self-signed SSL/TLS X.509 certificate is cryptologically identical to a CA-signed certificate. The difference is social, not mathematical; a CA promises to validate, at a minimum, a domain's ownership before issuing a certificate to an applicant. Each web browser contains a list of CAs trusted by the browser vendor to do this. An X.509 certificate consists primarily of a public key that corresponds to your private server key, and a signature by the CA that is cryptographically tied to the public key. When a browser connects to a web server over HTTPS, the server presents a certificate for the browser to check against its list of trusted CAs. If the signer is on the list, or accessible through a chain of other trusted signers, the browser negotiates a fast encrypted data channel with the server and loads the page.
Certificates generally cost money because of the labor involved in validating the requests, so it pays to shop around. A list of well-known CAs can be found at dmoz.org. A few CAs, such as StartCom, offer basic-level ("Class 1") certificates free of charge.
Underlying the certificate is the key. As of 2013, government and industry groups recommend using a minimum key (modulus) size of 2048 bits for RSA keys. The default modulus size generated by OpenSSL in Amazon Linux is 2048 bits, which means that the existing auto-generated key is suitable for use in a CA-signed certificate. An alternative procedure is described below for those who desire a customized key, for instance, one with a larger modulus or using a different encryption algorithm.
To obtain a CA-signed certificate
Connect to your instance and navigate to /etc/pki/tls/private/. This is the directory where the server's private key for SSL/TLS is stored. If you prefer to use your existing host key to generate the CSR, skip to Step 3.
(Optional) Generate a new private key. Here are some sample key configurations. Any of the resulting keys will work with your web server, but they vary in how (and how much) security they implement.
As a starting point, here is the command to create an RSA key resembling the default host key on your instance:
sudo openssl genrsa -out custom.key 2048
The resulting file,
custom.key, is a 2048-bit RSA private key.
To create a stronger RSA key with a bigger modulus, use the following command:
sudo openssl genrsa -out custom.key 4096
The resulting file,
custom.key, is a 4096--bit RSA private key.
To create a 4096-bit encrypted RSA key with password protection, use the following command:
sudo openssl genrsa -aes128 -passout pass:abcde12345 -out custom.key 4096
This results in a 4096-bit RSA private key that has been encrypted with the AES-128 cipher.
Encryption provides greater security, but because an encrypted key requires a password, services depending on it cannot be auto-started. Each time you use this key, you need to supply the password "abcde12345" over an SSH connection.
RSA cryptography can be relatively slow, because its security relies on the difficulty of factoring the product of two large two prime numbers. However, it is possible to create keys for SSL/TLS that use non-RSA ciphers. Keys based on the mathematics of elliptic curves are smaller and faster when delivering an equivalent level of security. Here is an example:
sudo openssl ecparam -name prime256v1 -out custom.key -genkey
The output in this case is a 256-bit elliptic curve private key using prime256v1, a "named curve" that OpenSSL supports. Its cryptographic strength is slightly greater than a 2048-bit RSA key, according to NIST.
Not all CAs provide the same level of support for elliptic-curve-based keys as for RSA keys.
Make sure that the new private key has highly restrictive permissions (owner root, group root, read/write for owner only). The commands would be as follows:
sudo chown root.root custom.key[ec2-user ~]$
sudo chmod 600 custom.key[ec2-user ~]$
ls -al custom.key
The commands above should yield the following result:
-rw------- root root custom.key
After you have created and configured a satisfactory key, you can create a CSR.
Create a CSR using your preferred key; the example below uses
sudo openssl req -new -key private.key -out csr.pem
OpenSSL opens a dialog and prompts you for information shown in the table below. All of the fields except Common Name are optional for a basic, domain-validated certificate.
Name Description Example Country Name The two-letter ISO abbreviation for your country. US (=United States) State or Province Name The name of the state or province where your organization is located. This name cannot be abbreviated. Washington Locality Name The location of your organization, such as a city. Seattle Organization Name The full legal name of your organization. Do not abbreviate your organization name. Example Corp Organizational Unit Name Additional organizational information, if any. Example Dept Common Name
This value must exactly match the web address that you expect users to type into a browser. Usually, this means a domain name with a prefixed host name or alias in the form
www.example.com. In testing with a self-signed certificate and no DNS resolution, the common name may consist of the host name alone. CAs also offer more expensive certificates that accept wild-card names such as
www.example.com Email Address The server administrator's email address. email@example.com
Finally, OpenSSL prompts you for an optional challenge password. This password applies only to the CSR and to transactions between you and your CA, so follow the CA's recommendations about this and the other optional field, optional company name. The CSR challenge password has no effect on server operation.
The resulting file
csr.pemcontains your public key, your digital signature of your public key, and the metadata that you entered.
Submit the CSR to a CA. This usually consists of opening your CSR file in a text editor and copying the contents into a web form. At this time, you may be asked to supply one or more subject alternate names (SANs) to be placed on the certificate. If
www.example.comis the common name, then
example.comwould be a good SAN, and vice versa. A user typing in either of the listed names would see an error-free connection. If your CA web form allows it, include the common name in the list of SANs. (Some CAs include it automatically.)
After your request has been approved, you will receive a new host certificate signed by the CA. You may also be instructed to download an intermediate certificate file that contains additional certificates needed to complete the CA's chain of trust.
Remove the old self-signed host certificate
localhost.crtfrom the /etc/pki/tls/certs directory and place the new CA-signed certificate there (along with any intermediate certificates).
There are several ways to upload your new certificate to your EC2 instance, but the most straightforward and informative way is to open a text editor (vi, nano, notepad, etc.) on both your local computer and your instance, and then copy and paste the file contents between them. This way, you will see immediately if there are any permission or path problems. Be careful, however, not to add any additional lines while copying the contents, or to change them in any way.
From inside the /etc/pki/tls/certs directory, check that the file ownership, group, and permission settings match the highly restrictive Amazon Linux defaults (owner root, group root, read/write for owner only). The commands would be as follows:
sudo chown root.root custom.crt[ec2-user certs]$
sudo chmod 600 custom.crt[ec2-user certs]$
ls -al custom.crt
The commands above should yield the following result:
-rw------- root root custom.crt
The permissions for the intermediate certificate file are less stringent (owner root, group root, owner can write, world can read). The commands would be:
sudo chown root.root intermediate.crt[ec2-user certs]$
sudo chmod 644 intermediate.crt[ec2-user certs]$
ls -al intermediate.crt
The commands above should yield the following result:
-rw-r--r-- root root intermediate.crt
The file name of the new CA-signed certificate (
custom.crtin this example) probably differs from the old certificate. Edit /etc/httpd/conf.d/ssl.conf and provide the correct path and file name using Apache's SSLCertificateFile directive.
If you received an intermediate certificate file (
intermediate.crtin this example), provide its path and file name using Apache's SSLCACertificateFile directive.
Save /etc/httpd/conf.d/ssl.conf and restart Apache.
sudo service httpd restart
Step 3: Test and Harden the Security Configuration
After your SSL/TLS is operational and exposed to the public, you should test how secure it really is. This is easy to do using online services such as Qualys SSL Labs, which performs a free and thorough analysis of your security setup. Based on the results, you may decide to harden the default security configuration by controlling which protocols you accept, which ciphers you prefer, and which you exclude. For more information, see how Qualys formulates its scores.
Real-world testing is crucial to the security of your server. Small configuration errors may lead to serious security breaches and loss of data. Because recommended security practices change constantly in response to research and emerging threats, periodic security audits are essential to good server administration.
On the Qualys SSL
Labs site, type the fully qualified domain name of your server, in the form
www.example.com. After about two minutes, you will receive a
grade (from A to F) for your site and a detailed breakdown of the findings. The table
below summarizes the report for a domain with settings identical to the default Apache
configuration on Amazon Linux:
The report shows that the configuration is mostly sound, with acceptable ratings for certificate, protocol support, key exchange, and cipher strength issues. However, the report also flags three vulnerabilities that are responsible for lowering the overall grade and should be addressed:
POODLE vulnerability: The POODLE attack, discovered in 2014, exploits a weakness in SSL version 3 that allows an attacker to impersonate a web site. The fix is straightforward: Disable SSL version 3 support on the server. In the configuration file /etc/httpd/conf.d/ssl.conf, comment out the following by typing "#" at the beginning of the line:
SSLProtocol all -SSLv2
Then, add the following directive:
SSLProtocol -SSLv2 -SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2
In addition to explicitly disabling SSL version 2, this command also disables SSL version 3 (the one flagged by the security audit) and explicitly allows all currently existing versions of TLS. The server will now refuse to accept encrypted connections with clients using anything except TLS. The verbose wording in the directive communicates more clearly, to a human reader, what the server is configured to do.
RC4 cipher support: A cipher is the mathematical core of an encryption algorithm. RC4, a fast cipher used to encrypt SSL/TLS data-streams, is known to have several serious weaknesses. The fix is to disable RC4 support in ssl.conf, which we'll do as part of the fix in the next case.
Missing support for forward secrecy: Forward secrecy is a feature of protocols that encrypt using temporary (ephemeral) session keys derived from the private key. This means in practice that attackers cannot decrypt HTTPS data even if they possess a web server's long-term private key. The web browsers that make up Qualys's list of "reference browsers" all support forward secrecy.
The fix for both RC4 and forward secrecy issues is to customize Apache's list of permitted and forbidden ciphers, and to enforce a preference for strong ciphers over weaker ones. This requires two configuration changes.
In the configuration file /etc/httpd/conf.d/ssl.conf, find the section with commented-out examples for configuring
SSLCipherSuite, comment out (but keep) the current list, and add the following directive:
Though shown here on several lines for readability, the entire directive must be on a single line without spaces between the cipher names.
SSLCipherSuite ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384: ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256: AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH: !EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
These ciphers are a subset of the much longer list of supported ciphers in OpenSSL. They were selected and ordered according to the following criteria:
Support for forward secrecy
Specific ciphers before cipher families
Allowed ciphers before denied ciphers
Note that the high-ranking ciphers have ECDHE in their names, for Elliptic Curve Diffie-Hellman Ephemeral ; the ephemeral indicates forward secrecy. Also, RC4 is now among the forbidden ciphers near the end.
We recommend that you use an explicit list of ciphers instead relying on defaults or terse directives whose content isn't visible.
The cipher list shown here is just one of many possible lists; for instance, you might want to optimize a list for speed rather than forward secrecy.
If you anticipate a need to support older clients, you can allow the DES-CBC3-SHA cipher suite.
Finally, each update to OpenSSL introduces new ciphers and deprecates old ones. Keep your EC2 Amazon Linux instance up to date, watch for security announcements from OpenSSL, and be alert to reports of new security exploits in the technical press. For more information, see Predefined SSL Security Policies for Elastic Load Balancing in the Elastic Load Balancing User Guide.
Uncomment the following line by removing the "#":
This command forces the server to prefer high-ranking ciphers, including (in this case) those that support forward secrecy. With this directive turned on, the server tries to establish a strongly secure connection before falling back to allowed ciphers with lesser security.
Restart Apache after saving the edited configuration file.
If you test the domain again on Qualys SSL Labs, you should see that the vulnerabilities are gone and the summary looks something like this:
My Apache webserver won't start unless I supply a password.
This is expected behavior if you installed an encrypted, password-protected, private server key.
You can strip the key of its encryption and password. Assuming you have a private encrypted RSA key called
custom.keyin the default directory, and that the passphrase on it is
abcde12345, run the following commands on your EC2 instance to generate an unencrypted version of this key:
cd /etc/pki/tls/private/[ec2-user private]$
sudo cp custom.key custom.key.bak[ec2-user private]$
sudo openssl rsa -in custom.key -passin pass:abcde12345 -out custom.key.nocrypt[ec2-user private]$
sudo mv custom.key.nocrypt custom.key[ec2-user private]$
sudo chown root.root custom.key[ec2-user private]$
sudo chmod 600 custom.key[ec2-user private]$
sudo service httpd restart
Apache should now start without prompting you for a password.