Pasan W.
Pasan W.

Reputation: 714

Python TLS client code gives Wrap Socket unexpected keyword error

I'm trying to use the following client code to connect to a server which uses TLS.(AES 256)

from socket import create_connection
import ssl
from ssl import SSLContext, PROTOCOL_TLS_CLIENT


hostname='MyHost'
ip = '10.98.1.1'
port = 11900
context = SSLContext(PROTOCOL_TLS_CLIENT)
context.load_verify_locations('client.pem')

with create_connection((ip, port)) as client:
    # with context.wrap_socket(client, server_hostname=hostname) as tls:
    with context.wrap_socket(client, ca_certs="ca.key", cert_reqs=ssl.CERT_REQUIRED, certfile="client.pem", keyfile="client.key") as tls:
        print(f'Using {tls.version()}\n')
        tls.sendall(b'Hello, world')

        data = tls.recv(1024)
        print(f'Server says: {data}')

I'm getting the following error when I'm running it. In Python 3.6/3.7 and 3.9

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    with context.wrap_socket(client, ca_certs="ca.key", cert_reqs=ssl.CERT_REQUIRED, certfile="client.pem", keyfile="client.key") as tls:
TypeError: wrap_socket() got an unexpected keyword argument 'ca_certs'

As per the Googling I did, it seems a break in Python 3.7 but I can't understand why the code doesn't even work in Python 3.6. Is it something wrong with Python or am I using the function call incorrectly?


Following is the updated working code with +TomerPlds solution

from socket import create_connection
import ssl
from ssl import SSLContext, PROTOCOL_TLS_CLIENT


hostname='MyHost'
ip = '10.98.1.1'
port = 11900
context = SSLContext(PROTOCOL_TLS_CLIENT)
context.load_verify_locations('ca.pem')

with create_connection((ip, port)) as client:
    # with context.wrap_socket(client, server_hostname=hostname) as tls:
    with context.wrap_socket(client, server_hostname=hostname) as tls:
        print(f'Using {tls.version()}\n')
        tls.sendall(b'Hello, world')

        while(True):
            data = tls.recv(1024000000)
            print(f'Server says: {data}')

Upvotes: 1

Views: 2233

Answers (1)

TomerPld
TomerPld

Reputation: 76

The reason for the unexpected keyword error is because SSLContext.wrap_socket does not have a ca_cert parameter as you can see in the documentation. Instead, you can use SSLContext.load_verify_locations which you already use to load the CA cert together with the client cert.

BTW, it looks like you mixed the parameters of ssl.wrap_socket and SSLContext.wrap_socket and that's where the wrong parameters come from.

Upvotes: 2

Related Questions