HTTPS TLS X.509 Certificates

Public Key (Asymmetric) Cryptography

Public-key cryptography, or asymmetric cryptography, is the field of cryptographic systems that use pairs of related keys.
Each key pair consists of a private key and a corresponding public key.
Key pairs are generated with cryptographic algorithms.

The main uses of asymmetric cryptography are :

Encryption (public key)
Anyone with a public key can encrypt a message, but only those who own the corresponding private key can decrypt the encrypted message to obtain the original message.

Digital Signatures (private key)
This process proves the Authenticity of the sender and the Integrity of the message.

In many scenarios, the sender and receiver of a message must be sure that a message has not been altered during transmission.
Although encryption hides the contents of a message, it may be possible to alter an encrypted message.
If a message is digitally signed, any change in the message after signature invalidates the signature.
A message is signed with the sender’s private key and can be verified by anyone who has access to the sender’s public key.

Given a message and a private key, a signing algorithm produces a signature.
Given the message, the public key and the signature, a signature verifying algorithm either accepts or rejects the message’s claim to authenticity.

Digital signatures may be attached to the message or detached.
A detached signature is transmitted separately from the message it signs.

Security of public key cryptography depends on keeping the private key secret, while the public key can be openly distributed.

Transport Layer Security (TLS)

Transport Layer Security (TLS) is a protocol that encrypts data sent over the Internet, the most familiar usage is with HTTPS.

TLS uses a combination of symmetric and asymmetric cryptography, as this provides a good compromise between performance and security when transmitting data securely.

With symmetric cryptography, data is encrypted and decrypted with a secret key known to both sender and recipient, typically 128 but preferably 256 bits in length (anything less than 80 bits is now considered insecure).
Symmetric cryptography is efficient in terms of computation, but having a common secret key means it needs to be shared in a secure manner.

Asymmetric cryptography uses key pairs: a public key, and a private key.
The public key is mathematically related to the private key, but given sufficient key length, it is computationally impractical to derive the private key from the public key.
This allows the public key of the recipient to be used by the sender to encrypt the data they wish to send to them, but that data can only be decrypted with the private key of the recipient.

The advantage of asymmetric cryptography is that the process of sharing encryption keys does not have to be secure, but the mathematical relationship between public and private keys means that much larger key sizes are required.
The recommended minimum key length is 1024 bits, with 2048 bits preferred, but this is up to a thousand times more computationally intensive than symmetric keys of equivalent strength (e.g. a 2048-bit asymmetric key is approximately equivalent to a 112-bit symmetric key) and makes asymmetric encryption too slow for many purposes.

For this reason, TLS uses asymmetric cryptography for securely generating and exchanging a session key.
The session key is then used for encrypting the data transmitted by one party, and for decrypting the data received at the other end
.

Once the session is over, the session key is discarded.

X.509 Certificates

ITU-T X.509 | ISO/IEC 9594-8 is an International Telecommunication Union (ITU) standard defining the format of public key certificates.

In cryptography, a public key certificate, also known as a digital certificate or X.509 certificate is an electronic document used to prove the validity of a public key.

An X.509 certificate binds an identity to a public key using a digital signature.

The certificate includes a public key, information about the identity of its owner (called the subject), and the digital signature of an entity that has verified the certificate’s contents (called the issuer).

If the signature is valid, and the software examining the certificate trusts the issuer, then it can use that public key to communicate securely with the subject.

The X.509 standard was first issued in 1988 and is described in several RFCs.
X.509 Version 3 Certificate is defined in RFC 5280 (2008)

A digital certificate is normally issued by an authority, referred to as a Certification Authority (CA).
That authority guarantees the validity of the information in the certificate which is valid for a limited period of time.

A Certification Authority (CA) is an entity that stores, signs, and issues digital certificates.
A digital certificate certifies the ownership of a public key by the named subject of the certificate.

One particularly common use for Certificate Authorities is to sign certificates used for HTTPS, the secure browsing protocol for Internet.

The CA that issues public-key certificates also has the responsibility to indicate the validity of the public-key certificates that it issues. Generally, public-key certificates are subject to possible subsequent revocation. This revocation and a notification of the revocation may be done directly by the same CA that issued the public-key certificate, or indirectly by another authority duly authorized by the CA that issued the public-key certificate.

If, for any reason, a CA revokes a previously issued public-key certificate, entities need to be able to learn that revocation has occurred so they do not use an untrustworthy public-key certificate.
Revocation lists are one scheme that can be used to notify entities of revocations.

CAs that do revoke public-key certificates are required to state what mechanism(s) can be used by relying parties to obtain revocation status information about public-key certificates issued by that CA.
This includes a Certificate Revocation List (CRL) mechanism and Authorization and Validation List (AVL) mechanism, but does not preclude the use of alternative mechanisms.

One such alternative mechanism is the Online Certificate Status Protocol (OCSP) specified in IETF RFC 6960 (2013). Using this protocol, a relying party (client) requests the revocation status of a public-key certificate from an OCSP server. The server may use CRLs, or other mechanisms to check the status of the public-key certificate and respond to the client accordingly.

Steps to get an SSL/TLS certificate from a Certification Authority

1) Create a private key and a Certificate Signing Request (CSR)
2) Send the CSR to the trusted CA
3) The CA sends you the certificate signed by its root certificate and private key
4) Install the certificate on the web server

Certificate Signing Request (CSR)

A Certificate Signing Request (CSR) is the first step to get an SSL/TLS certificate from a Certification Authority.
You normally generate it on the same server you plan to use the certificate (the private key must be kept secret).
The CSR contains identification information (Country, State/Province, Locality, Organization, Organizational Unit, Common Name, Email) AND the public key that the Certificate Authority (CA) will use to create the certificate.
Not all of these fields may be required and will vary depending on the assurance level of your certificate.

Assurance levels for SSL/TLS certificates

Class 1 Certificates are considered to be low assurance, as the verification method simply confirms that the subscriber controls the domain.
They can do this by adding a DNS record associated with the domain, the process is automated.
No verification checks of the subscriber’s identity are performed.
This level of validation is referred to as Domain Validation (DV) and is the cheapest.

Class 2 Certificates are considered to be medium assurance.
They provide a greater level of assurance over Class 1 Certificates, because in addition to domain control, basic verification steps are performed to confirm the identity of the Subscriber.
This level of validation is referred to as Organization Validation (OV).
Organization Validation SSL/TLS certificates will contain the organization’s name and address, making them more trustworthy for users than Domain Validation certificates.

Class 3 Certificates provide a high level of assurance.
They are issued only after rigorous validation of the identity of the Subscriber.
This level of validation is referred to as Extended Validation (EV).

Extended Validation involves a full background check of the organization.
The CA will make sure that the organization exists and is legally registered as a business, that they actually are present at the address they list, and so on.
This validation level takes the longest and costs the most, but Extended Validation SSL certificates are more trustworthy than other types of SSL certificates.
Consequently, these certificates are necessary for a website’s address to turn the browser URL bar green, the visual representation for users of a trustworthy TLS-encrypted site.

PEM Format

A CSR is usually in a PKCS#10 format, by default a CSR is created in a Base-64 PEM format, and isn’t designed to be read by a human.

PEM (originally ‘Privacy Enhanced Mail’) is a standard and the most common format for X.509 certificates, CSRs, and cryptographic keys.

A PEM file is a text file containing one or more items (defined by <type>) in Base64 ASCII encoding, each with plain-text headers and footers :

starting with
-----BEGIN <type>-----

and ending with:
-----END <type>-----

Everything in between is base64 encoded (uppercase and lowercase letters, digits, +, / and =).
Base64 is a binary-to-text encoding scheme. It represents binary data in a printable ASCII string format by translating it into a radix-64 representation.
It is defined in RFC 4648 (2006)

The PEM file will tell you what it is used for in the header (if it is a private key, a CSR, a certificate)

-----BEGIN PRIVATE KEY-----

-----END PRIVATE KEY-----

-----BEGIN CERTIFICATE REQUEST-----

-----END CERTIFICATE REQUEST-----

-----BEGIN CERTIFICATE-----

-----END CERTIFICATE-----

Thus, a Certificate Signing Request (CSR) is a request sent to a Certification Authority to sign your public key and associated informations.

The CSR is signed by the applicant’s private key, this proves to the CA that the applicant has possession and control of the private key that corresponds to the public key included in the CSR.

The CA first verifies the PKCS#10 signature with the public key placed in the PKCS#10.
Once the signature is successfully verified, the requested information in the CSR passes a vetting process and domain control is established, the CA signs the applicant’s public key so that it can be publicly trusted.

It becomes a trusted signed certificate that internet browsers will be able to verify when communication is made to your server.

Most internet browsers and operating systems hold a copy of root CA certificates of all the trusted certified Certificated Authorities.

On Debian it is located in /usr/share/ca-certificates/mozilla/ (package ca-certificates)
It contains the certificate authorities shipped with Mozilla’s browser to allow SSL-based applications to check for the authenticity of SSL connections.

That’s the reason internet browsers won’t show any security messages when you visit websites using https with a certificate issued from a trusted and well-known commercial Certificate Authority.

You can also sign the CSR yourself but this will cause browsers to display warning messages to users attempting to reach your server until they explicitly grant their browsers permission to communicate with it.
If you use a self-signed certificate, your browser will throw a security warning.
The reason is that internet browsers only trust certificates from a trusted Certificate Authority.

For this reason it is recommended only to self-sign a certificate for testing purposes or only if your server needs to be reached internally.

Install OpenSSL (Debian)

# apt install openssl

The /etc/ssl/certs directory is used to store the public certificates, it should already exists on the server.
You may need to create an /etc/ssl/private directory as well, to store the private keys.
Since the secrecy of those private keys is essential for security, it’s important to lock down the permissions to prevent unauthorized access.

# mkdir /etc/ssl/private

$ ls -l /etc/ssl
drwxr-xr-x   root root      certs
-rw-r--r--   root root      openssl.cnf
drwx--x---   root ssl-cert  private

Generate a private key + Certificate Signing Request

Create a specific directory to store CSRs

# mkdir /etc/ssl/csr
Create a private key and generate a Certificate Signing Request from it

# openssl genrsa -out /etc/ssl/private/domain-name.key 2048
# openssl req -new -key /etc/ssl/private/domain-name.key -out /etc/ssl/csr/domain-name.csr

OR 

# openssl req -newkey rsa:2048 -nodes -keyout /etc/ssl/private/domain-name.key -out /etc/ssl/csr/domain-name.csr

You may be prompted to enter extra attributes including an optional challenge password.
Just skip this step by hitting the enter button.
Examine and verify Certificate Signing Request

$ openssl req -in /etc/ssl/csr/domain-name.csr -text -verify -noout

What is a Self Signed Certificate?

A self-signed certificate is an SSL/TSL certificate not signed by a public or private Certification Authority.
Instead, it is signed by the creator’s own private key or root CA certificate.

Many organizations use self-signed certificated for their internal applications that are not internet-facing.
These certificates are generated using the organization’s internal PKI infrastructure.

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.

Create a private key AND a self-signed public certificate with OpenSSL – Method 1

# openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/ssl/private/hostname.key -out /etc/ssl/certs/selfsigned-hostname.crt

openssl req
OpenSSL command line tool, PKCS#10 X.509 Certificate Signing Request (CSR) Management.

-x509
This option tells openssl you want to make a self-signed certificate instead of generating a certificate signing request.

-sha256
This option tells openssl to sign with a sha256 message digest

-nodes
This option tells openssl not to encrypt the private key with a passphrase.
The web server needs to be able to read the file without user intervention, when the server starts up.
A passphrase would prevent this from happening because you would have to enter it after every restart.

-days 3650
This option sets how many days the certificate will be considered valid (3650 = 10 years)

-newkey rsa:2048
This option specifies that you want to generate a new private key at the same time.
(RSA key that is 2048 bits long)

-keyout
This option tells openssl where to place the generated private key file

-out
This option tells openssl where to place the self-signed certificate

Note: It is important that you enter your domain/host name or your server’s IP address when you’re prompted for the Common Name.

Display the contents of the certificate
$ openssl x509 -in /etc/ssl/certs/selfsigned-hostname.crt -text -noout

Create a private key AND a self-signed public certificate with OpenSSL – Method 2

Step 1 - Create a private key
# openssl genrsa -out /etc/ssl/private/hostname.key 2048

Step 2 - Create a CSR
# openssl req -new -key /etc/ssl/private/hostname.key -out /etc/ssl/csr/hostname.csr

NOTE: Step 1 and 2 can be combined in one line
# openssl req -new --nodes newkey rsa:2048 -keyout /etc/ssl/private/hostname.key -out /etc/ssl/csr/hostname.csr

Step 3 - Check the CSR
$ openssl req -in /etc/ssl/csr/hostname.csr -text -noout

Step 4 - Create Self-signed Certificate
# openssl x509 -req -days 3650 -in /etc/ssl/csr/hostname.csr -signkey /etc/ssl/private/hostname.key -out /etc/ssl/certs/selfsigned-hostname.crt

Create a private key AND a self-signed public certificate with OpenSSL – Method 3: own Certification Authority (CA)

IMPORTANT
For security reasons, Certification Authority's private key and certificate SHOULD BE safeguarded on a separate machine.

# mkdir /etc/ssl/MyOwnCA


Step 1 - Create Certification Authority rootCA.key and rootCA.crt
We will use the rootCA.key and rootCA.crt to sign the SSL/TLS certificate.

# openssl req -x509 -nodes  -newkey rsa:2048 -keyout /etc/ssl/MyOwnCA/rootCA.key -days 3650 -sha256 -out /etc/ssl/MyOwnCA/rootCA.crt

Country Name (2 letter code) []: FR
State or Province Name (full name) []: *
Locality Name (eg, city) []:
Organization Name (eg, company) []: COMPANY  
Organizational Unit Name (eg, section) []: PKI ADMINISTRATION
Common Name (e.g. server FQDN or YOUR name) []: COMPANY-ROOT-CA
Email Address []:

Step 2 - Create the Host Private Key and Certificate Signing Request
# openssl req -newkey rsa:2048 -nodes -keyout /etc/ssl/private/hostname.key -out /etc/ssl/csr/hostname.csr

Step 3 - Generate X.509 certificate signed with own CA
# openssl x509 -req -in /etc/ssl/csr/hostname.csr -CA /etc/ssl/MyOwnCA/rootCA.crt -CAkey /etc/ssl/MyOwnCA/rootCA.key -CAcreateserial -days 3650 -sha256 -out /etc/ssl/certs/ownCAsigned-hostname.crt

Install X.509 Certificate on Web Server (Apache – Debian)

In order to set up and use a (self-signed) certificate, you first have to be sure that Apache ssl module which provides support for SSL encryption, is installed and enabled on the server.

# a2enmod ssl

Create an Apache directory for the hosts certificates and private keys

# mkdir /etc/apache2/certificates
Set up the virtual host to use the certificate

# vi /etc/apache2/sites-available/website.conf

<VirtualHost *:443>
...
        SSLEngine on
        SSLCertificateFile /etc/apache2/certificates/website.crt
        SSLCertificateKeyFile /etc/apache2/certificates/website.key
</VirtualHost>


Optionally, you may want to automatically redirect HTTP traffic to HTTPS

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