Wrap_socket() Method Of SSLContext Class In Python

Method Name:

wrap_socket

Method Signature:

wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None);

Parameters:

sock                                                          – The socket instance from which the SSLSocket needs to be created.

server_side                                     Denotes whether the SSLSocket being created is a server socket or a client socket.               

do_handshake_on_connect A Boolean flag indicating whether to complete the SSL Handshake subsequent to the creation of SSLSocket                                                             instance or a call will be made later separately to take care of the SSL Handshake

suppress_ragged_eofs Tells how to handle ragged EOFs from the peer. A ragged EOF is an unexpected EOF received from a peer.

server_hostname Server hostname to which the client is connecting to. This parameter needs to be supplied a value only if the server_side = False.

session  An SSL session.

Return Value:

An object of type ssl.SSLSocket

Overview:

  • Given a connection oriented socket, the SSLContext.wrap_socket() method returns an SSLSocket. The method copies the attributes/options of the socket instance and creates an SSLSocket. The original socket is detached. Hence it is safer to close the original socket right after an SSLSocket is obtained through SSLContext.wrap_socket() method.
  • Created SSLSocket can be a client socket or a server socket.
  • The SSLContext.wrap_socket() adds the SSL layer to the socket.

 

Example:

import socket

import ssl

import certifi

import os

 

# Create a place holder to consolidate SSL settings

# i.e., Create an SSLContext

contextInstance                 = ssl.SSLContext();

contextInstance.verify_mode     = ssl.CERT_REQUIRED;

 

# Load the CA certificates used for validating the peer's certificate

contextInstance.load_verify_locations(cafile=os.path.relpath(certifi.where()),

                                      capath=None,

                                      cadata=None);

 

# Create a client socket

socketInstance = socket.socket();

 

# Get an instance of SSLSocket

sslSocketInstance  = contextInstance.wrap_socket(socketInstance);

 

print(type(sslSocketInstance));

 

# Connect to a server

sslSocketInstance.connect(("example.org", 443));

 

print("Version of the SSL Protocol:%s"%sslSocketInstance.version());

print("Cipher used:");

print(sslSocketInstance.cipher());

 

Output:

<class 'ssl.SSLSocket'>

Version of the SSL Protocol:TLSv1.2

Cipher used:

('ECDHE-RSA-AES128-GCM-SHA256', 'TLSv1.2', 128)

 


Copyright 2022 © pythontic.com