4-step Python SSL Tutorial to Secure Your Websites

FREE Online Courses: Click, Learn, Succeed, Start Now!

Data protection is essential now for business operations. Every business domain is going digital, and this transformation requires higher security to ensure data protection. Integrating advanced technologies like AI, ML, and voice recognition increases the need for effective cybersecurity.

Python is a high-level and interpreted programming language that helps develop websites, data analytics software, AI, scientific computing, and more. It does come with several security features, but some vulnerabilities can cause cyber-attacks.

Take an example of the 15-year-old Python bug called CVE-2007-4559. It is a vulnerability in the Python tar file package, which uses an unsanitized tarfile. extract(). Attackers can overwrite arbitrary files using this vulnerability.

The CVE-2007-4559 vulnerability never received a patch. Such vulnerabilities and bugs in the Python packages can lead to the development of websites susceptible to cyber-attacks. However, when you use an SSL certificate in Python, you can ensure data security and prevent attackers from exploiting such vulnerabilities.

This article will discuss an SSL certificate and how to secure Python code.

What is SSL Certificate?

SSL or Secure Socket Layer, encodes the data exchanged between a server and a browser. SSL certificates enable businesses to establish HTTPS protocols and verify the identity of a website publisher.

These are key to protecting sensitive information like user credentials, financial details, and even the source code of a website. It helps improve the trust among users due to increased data security.

How to get an SSL certificate?

You can get an SSL certificate from trusted certificate authorities (CAs). These CAs issue certificates after validating the website publisher’s identity, organization details, and domain ownership.

Validation details that you need to provide to a CA differ according to the type of SSL certificate. There are different certificate types, such as domain-validated (DV), organization-validated (OV), and extended validation (EV), which offer different levels of assurance and validation.

1. Domain Validated (DV) SSL Certificates are mainly used for securing small to medium-sized websites. To get a DV certificate, you must prove domain ownership to the CA and pass email validation process.

2. Organization Validated (OV) SSL Certificates provide a higher verification level. CAs verify an organization’s identity and legal existence to issue the certificate, making them ideal for businesses that handle sensitive information.

3. Extended Validation (EV) SSL Certificates offer the highest level of security by providing highly secure encryption and a comprehensive verification process. CAs verify the domain ownership and organization’s identity with additional legal checks.

4. Wildcard SSL certificates help in securing more than one subdomain. For example, if you have one primary domain like domain.com then, you can secure first level of subdomains like blog.domain.com, mail.domain.com, etc.

5. Multi-domain certificates allow you to secure more than one domain and subdomains through SANs (Subject Alternative Names).

To install an SSL certificate on a website, you must generate a certificate signing request (CSR) and submit it to the CA. Further, CA verifies your details and issues the certificate.

You can download the certificate from CA’s bundle sent through an email and install it on their web server.

Once installed, the SSL certificate will secure communications between the server and the browser indicated through a padlock icon. You can also notice the HTTPS prefix in the browser address bar, indicating a secure connection.

How to use SSL Certificate in Python?

The first and most important aspect of using a TLS/SSL certificate in python is to find the right CA. Many leading certificate authorities provide secure certificates. CAs will need details of your domain and other organizational details for issuing the certificate.

The certificate process begins with a CSR, which is an encoded representation of your request to the CA to issue the certificate. However, before we understand the process of generating a CSR, you need to know how an SSL certificate works in Python.

How SSL works in Python?

SSL provides both encryption and authentication to secure your Python code. So, the data is protected from cyberattacks keeping the integrity of Python code. SSL certificates work on asymmetric encryptions using two security key pairs- “private & public.”

In asymmetric encryptions, one security key is used for encryption, and the other is used for decryption. This is important to understand because the first step to using TLS/SSL certificate in Python is to generate CSR and private key pair.

Steps to install requests library for Python and certifi package

Install the requests library for Python if it is not already installed. You can use pip to install it:

pip install requests

Install the certifi package using pip. This package provides a set of trusted root certificates that Python can use to verify SSL certificates. You can install it using the following command:

pip install certifi

Steps involved for installation of Python SSL certificate

You can use a Bash, Dash, or any other console to generate a private key and CSR using the OpenSSL command. Let us start our Python SSL tutorial by first understanding the CSR generation process.

Step 1- CSR generation process

Generate a private key and a Certificate Signing Request (CSR) using OpenSSL:

openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.com.key -out mydomain.com.csr

When you enter the command in OpenSSL, it will ask you to answer specific details like:

  • Common Name-It is your website’s hostname, e.g., www.mydomain.com.
  • Organization-name of your business.
  • Organization unit-You can either indicate a specific department of your organization or just provide the organization’s name.
  • City or locality-Provide details regarding the location of the business.
  • State or province- Provide details of the state from which your organization belongs.
  • Country- State the country’s name with an ISO code.

The CSR and private key files will be saved in the current working directory.

Submit the CSR to a Certificate Authority (CA) of your choice and follow their instructions to obtain a signed SSL certificate.

Step 2- Store the cert file.

Once you have the certificate and chain file, create a directory locally on your machine with the certificate file on top. Save the new directory as “mydomain.com.combinecd.cert.” Further, send an encrypted private key securely with the CSR to a CA so that they can verify your identity as a Python developer or as a requestor before issuing the certificate.

Step 3- Installing the SSL certificate in Python.

1. Once you have obtained the SSL certificate, save it in a file with a .pem extension. For example, if the certificate is named ‘certificate.crt’, you could save it as ‘certificate.pem’.

2. If the SSL certificate provider has given you any intermediate certificates, concatenate them to your SSL certificate file, in the order of your SSL certificate followed by the intermediate certificates.

3. In your Python code, use the ssl module to create an SSL context:

import ssl
context = ssl.create_default_context()

4. Load the SSL certificate file you saved earlier into the SSL context:

Replace ‘path/to/your/certificate.pem’ with the path to your SSL certificate file and ‘path/to/your/private.key’ with the path to your private key file.

context.load_cert_chain(certfile='/path/to/your/certificate.pem', keyfile='/path/to/your/private.key')

Step 4- Verifying the SSL Certificate Installation

Verify that the SSL certificate is being used by examining the SSL certificate chain presented by the server. You can use the ssl module in Python to retrieve the SSL certificate chain presented by the server:

import ssl
import socket

hostname = 'www.example.com' # Replace with your domain name
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
chain = ssock.getpeercert(chain=True)
print(chain)

This code creates an SSL context with ‘ssl.create_default_context()’, then connects to ‘www.example.com’(should be replaced with the hostname of your server) using a socket and wraps the socket with SSL using ‘context.wrap_socket()’. Finally, the SSL certificate chain is retrieved using ‘ssock.getpeercert(chain=True)’. This will print out the SSL certificate chain presented by the server.

Check TLS Version

Note that you may need to adjust the ‘ssl.PROTOCOL_’ constant used by ‘create_default_context()’ to match the SSL/TLS protocol version required by the SSL certificate provider.

For example, if the SSL certificate requires TLSv1.2, you would use ‘ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None, protocols=ssl.PROTOCOL_TLSv1_2)’ to create the SSL context.

Conclusion

It should be noted that the precise procedures for installing an SSL certificate may change depending on your unique use case, such as if you are using a different library or framework to send HTTPS requests.

Using SSL certificate in Python has become a necessity with increased exposure of users to cyber-attacks. It secures the communication between a client and server to ensure there are no man-in-the-middle attacks.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *