Python Program To Verify SSL Certificates

Python Program To Verify SSL Certificates

The SSL certificates are the Secure Sockets Layer certificates used for encryption and authentication. Every day we visit many websites for different purposes. As a user, we visit different websites and requests different web pages. This surfing is secure due to this SSL certificate verification. This SSL certificate provides some information necessary to secure the user’s visit. In this article, we will see more about SSL certificates and how to verify these SSL certificates using Python programs.

Whenever we try to fetch any webpage for our work, we always see a padlock icon or ‘https://’ prefix in the URL. This indicates the secure website, which is authenticated by our browser. For this authentication, the browser checks the SSL certificates of the website and connects the user to the server.

What is an SSL Certificate?

The Secure Sockets Layer(SSL) certificate does the job of digital authentication and verification for the user. Security is the main concern while visiting any website, so digital verification is very necessary. The SSL certificate consists of some information related to the website. This file may contain the domain name, public key, and information related to the organization. As mentioned before, these SSL certificates are indicated on every secure webpage in the two forms, ‘https://’ or the padlock icon.

Padlock Icon SSL Certificate
Padlock Icon SSL Certificate

Here, in the above image, the padlock icon before the URL indicates that this site is digitally secured and verified by the browser. You can buy SSL certificate from the trusted Certificate Authorities (CA’s). Any browser automatically verifies the websites for clients and connects to the server. These SSL certificates also have some expiration dates. Time-to-time renewal of these certificates is necessary for proper authentication and verification purpose.

Confirming the authenticity of websites and defending against potential attacks, like man-in-the-middle attacks and phishing attempts, is what the automatic SSL certificate verification process in browsers does to give users a safe browsing experience.

Importance of SSL Certificate

The SSL certificate is used to build trust and secure connections between the client/user and websites. These certificates have a very big importance in the process of authentication and verification. The different advantages of SSL certificates are as follows:

Secure Connection Between Website and User

Intercepting or tampering with login credentials, credit card details, and personal data is prevented by SSL certificates, which are mainly employed in securing websites and enabling safe communication between web servers and web browsers. The HTTPS (HTTP over SSL/TLS) protocol is used by websites equipped with an SSL certificate to encrypt the data being transmitted between the web server and the user’s browser.

Authentication and Verification

When users visit websites with valid SSL certificates, they can be assured that the website is authentic and belongs to its legitimate owner. SSL certificates, issued by trusted Certificate Authorities, establish trust and authentication by verifying the identity of the entity requesting the certificate. This ensures users are protected from phishing attacks and can interact confidently with trusted websites and services.

Online Payments Security

SSL certificates are an important component of any e-commerce website or online service dealing with financial transactions. They play a vital role in safeguarding the transmission of sensitive payment information, such as credit card details, by ensuring that the data is encrypted and shielded. By creating a trustworthy and secure environment, SSL certificates instill confidence in customers, encouraging them to make online purchases and view the website as reliable.

Login Authentication and Security

The security of login and authentication processes heavily relies on the use of SSL certificates. Encrypting login details, these certificates prevent interception of user credentials, safeguarding against theft. Consequently, unauthorized access and the compromise of sensitive information for user accounts are prevented, ensuring confidentiality.

Data Protection and Encryption

SSL certificates, which are crucial for websites that handle private information like healthcare portals, online banking platforms, and government websites, protect and secure data during transmission. By encrypting data in transit, SSL certificates play a key role in maintaining data confidentiality and reducing the chances of data breaches and unauthorized access.

How do Browsers Automatically Validate the Websites for Users?

Several steps are involved in the process of browsers automatically verifying SSL certificates when establishing an HTTPS connection to a website. With the initiation of an SSL handshake, the browser connects to the server when a user enters a URL with HTTPS or when they click on an HTTPS link on a page.

The server presents its SSL certificate in response to the browser’s request. This certificate includes details about the website such as its domain name and the server’s public key. Using the CA’s public key, which has already been installed in the browser, the validity of the certificate is checked to make sure it has not expired or been revoked and has been issued by a trusted CA. The digital signature of the certificate is then verified.

To ensure that the correct website has been issued the certificate, the browser checks for a valid wildcard domain match or an exact match with the domain name listed in the certificate. It then compares this domain name with the domain name in the URL for hostname verification. The browser ensures that the issuing CA’s certificate is trusted and has not been tampered with by verifying the certificate’s chain of trust.

It then recursively validates the entire certificate chain until it reaches a root CA certificate that the browser trusts and was pre-installed. The browser checks Certificate Revocation Lists (CRLs) or queries Online Certificate Status Protocol (OCSP) servers to confirm that the certificate has not been revoked by the issuing CA. A revocation check is performed to verify the certificate’s revocation status.

The browser generates a session key for encrypting communication after validating the certificate. During the negotiation process, the server and browser agree on the appropriate encryption algorithm, key exchange method, and other security parameters. Proceeding with the SSL certificate validation and agreeing on encryption parameters, the browser and server create a secure encrypted channel. Confidentiality and communication integrity are guaranteed as the session key encrypts all information shared between the browser and server.

Python Program To Verify SSL Certificate

Python language consists of different built-in modules, libraries, and functions which are used to verify SSL certificates. Let’s see the different ways to execute the verification program in Python.

Use of SSL Module

The ssl module in Python Built-in module, which serves as a communications conduit for secure network exchanges, utilizes SSL (Secure Sockets Layer) and TLS (Transport Layer Security). Python applications can utilize this module to create encrypted connections and authenticate SSL certificates. There are different functions available under the ssl module that is used to verify the SSL certificates. Let’s see these functions to understand the program.

The ssl.SSLContext Class

The ssl.SSLContext class is responsible for configuring a secure SSL/TLS setup. With this class, you can customize various aspects including the protocol versions, cipher suites, and certificate verification options. The ssl module facilitates this functionality.

ssl.wrap_socket() Function

The ssl.wrap_socket() function uses the SSL module to create a secure socket, allowing for encrypted communication. This can be done with both client-side and server-side sockets.

SSL module, during the SSL handshake, allows for the verification of SSL certificates provided by the server. You are able to choose the extent of validation needed, such as hostname verification, checks for certificate expiration, and verification of the certificate chain. Let’s see the Python program executed using these functions.

import ssl
import socket

def verify_ssl_certificate(hostname):
    context = ssl.create_default_context()

    with socket.create_connection((hostname, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            ssock.do_handshake()
            cert = ssock.getpeercert()
            print("Certificate is valid.")
           
verify_ssl_certificate("www.w3schools.com")

In this above program, we have used ssl module to execute the verification process. Different functions from ssl module like ssl.wrap_socket(), socket.create_connection(), context.wrap_socket(), we have executed this program. To validate the result, we are printing the message at the end. Let’s see the results.

Openssl Cert Check

The verification is done. This program is used to verify the ssl certificates.

Use of Certifi Package in Python

The curated collection of root CA (Certificate Authority) certificates provided by the certifi package in Python is commonly used to verify SSL certificates during network communication. This third-party package is often used with the ssl module. Ensuring the security and trustworthiness of network communication is made possible by utilizing certifi along with the SSL module. This is due to the constantly updated set of trusted root CA certificates, which allows for the authentication of SSL certificates.

Python applications can significantly benefit from the certifi package, which simplifies the usage and management of trusted CA certificates. For those who require a trustworthy assortment of root CA certificates for SSL certificate authentication, this package is incredibly valuable. Let’s see the program execution to understand the concept thoroughly.

import certifi
import ssl
import socket

def verify_ssl_certificate(hostname):
    context = ssl.create_default_context(cafile=certifi.where())

    with socket.create_connection((hostname, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            ssock.do_handshake()
            cert = ssock.getpeercert()
            print("Certificate is valid.")

verify_ssl_certificate("www.w3schools.com")

In this code, we have used different modules of Python i.e. certifi, ssl, and socket, to execute the program. The certifi module helps to fetch the certificates of the website and verifies them. If the certificates are valid, then the output statement will be printed. Let’s see the execution to understand the implementation.

Certifi Module For Verification
Certifi Module For Verification

This method is also correct to verify the certificates of any website.

Requests Module in Python

Python’s requests library is a widely-used third-party package for making HTTP requests. It streamlines the process of sending HTTP requests, managing responses, and collaborating with APIs. With a high-level interface, the requests library removes the intricacies of HTTP requests, streamlining the utilization of web services.

OAuth and basic authentication are types of authentication that can be performed using requests. The headers parameter allows you to add custom headers to your request for customization purposes. Using properties and methods from the response object, requests offer a simple way to interact with response data. With it, you can conveniently handle JSON responses and typical content types while also accessing response headers and status codes.

get() Method

The requests module has a useful method called get() that allows you to send an HTTP GET request to a specified URL and get back the response. This method is quite popular among users of the requests library. From the response received, you can access the attributes and methods of the Response object generated by the get() method.

Retrieve data from APIs, fetch webpages, and more in diverse scenarios using this versatile method. Access information like status codes, headers, content, and more. In this example, we are using this get() method from the requests module.

raise_for_status() Method

In Python, there is a handy function called raise_for_status() that you can find in the requests module. This function will come in handy when you want to check whether the HTTP response status code indicates an error by raising an exception if it does. The raise_for_status() method operates like this: Using methods like get() or post(), you will receive a Response object as a response after making an HTTP request. An exception is raised if the response status code indicates an error when the raise_for_status() method is called on the Response object.

Let’s execute the program by using this method from the requests library.

import requests

def verify_ssl_certificate(url):
    response = requests.get(url)
    response.raise_for_status()
    print("Certificate is valid.")

verify_ssl_certificate("https://www.w3schools.com/")

This program uses different functions that come under the requests module, like get(), and raise_for_status(). This helps to execute the program successfully.

Requests Module For Verification
Requests Module For Verification

This program is also implemented successfully. In this way, in Python, you can use different modules and functions to verify the SSL certificates.

Summary

In this article, we have studied the details of SSL certificates and their verification process. These certificates are very important while establishing a connection between the user/client with other entities (mostly websites). This authentication is very important for safe and secure searching. The browsers that we use on a daily basis does the job of verification automatically.

These automatic verifications also involve several steps and processes explained in detail. The proper authentication and verification of a website is very important for different domains like e-Commerce websites and online payments. The other uses/applications of SSL verification are explained in detail. The Python language contains different modules and libraries used to implement the verification codes. The libraries like ssl, requests, and certifi are used in verification. Different functions from these modules are explained in detail. Hope you will enjoy this article.

References

Do read the official documentation on the SSL module. You can also refer to this video to understand more about SSL.