Learning Python Network Programming

(Sean Pound) #1
Chapter 7
cert = ssl_socket.getpeercert()
pprint(cert)
if not cert or ('commonName', TARGET_HOST) not in
cert['subject'][4]:
raise Exception("Invalid SSL cert for host %s. Check if
this is a man-in-the-middle attack!" )
ssl_socket.write('GET / \n'.encode('utf-8'))
#pprint(ssl_socket .recv(1024).split(b"\r\n"))
ssl_socket.close()
client_sock.close()

If you run the preceding example, you will see the details of the SSL certificate of a
remote web server such as http://www.google.com. Here we have created a TCP socket
and connected it to HTTPS port 443. Then that socket connection is wrapped
into SSL packets using our ssl_wrap_socket() function. This function takes
the following parameters as arguments:



  • sock: TCP socket

  • keyfile: SSL private key file path

  • certfile: SSL public certificate path

  • cert_reqs: Confirmation if certificate is required from other side to make
    connection and if validation test is required

  • ca_certs: Public certificate authority certificate path

  • server_hostname: The target remote server's hostname

  • ssl_version: The intended SSL version to be used by the client


At the beginning of the SSL socket wrapping process, we have created an SSL context
using the SSLContext() class. This is necessary to set up the SSL connection specific
properties. Instead of using a custom context, we could also use a default context,
supplied by default with the ssl module, using the create_default_context()
function. You can specify whether you'd like to create client or server side sockets
using a constant. The following is an example for creating a client side socket:


context = ssl.create_default_context(Purpose.SERVER_AUTH)

The SSLContext object takes the SSL version argument, that in our example is set to
PROTOCOL_TLSv1, or you should use the latest version. Note that SSLv2 and SSLv3
are broken and must not be used in any production code for serious security issues.


In the preceding example, CERT_REQUIRED indicates that server certificate is
necessary for the connection to continue, and this certificate will be validated later.

Free download pdf