user3096370
user3096370

Reputation: 51

How can I perform Two way SSL authentication in python?

I am a beginner of python. I have implemented the one way SSL authentication in python, below is a part of the server side code:

...
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 12345))
s.listen(5)
while True:
    (connection, address) = s.accept()
    connstream = ssl.wrap_socket(connection,
                                server_side=True,
                                certfile="ssl/server.crt",
                                keyfile="ssl/server.key",
                                )
    #print repr(connection.recv(65535));
    try:
        deal_with_client(connstream)
            ....

below is the client side code:

import socket, ssl, pprint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                       ca_certs="ssl/server.crt",
                       cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('localhost', 12345))
print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())
while 1:
ssl_sock.write("boo!")
s.close()

Actually I want to perform two way SSL authentication, then I generated the certificates of ca and client and private key of client and ca by using openssl tool. Now I have below six files:

ca.crt
server.crt
client.crt
ca.key
server.key
client.key

So now how can I modify the server side and client side code to perform two way two way SSL authentication?

Sorry for my english, please help.

Upvotes: 5

Views: 7431

Answers (2)

Ahmad Khan
Ahmad Khan

Reputation: 91

If you are client and want to connect a server and send request at the same time, you can use the following code

response = requests.post(url, data=your_data, cert=('path_client_certificate_file', 'path_certificate_key_file'), verify='path_rootCA')

Upvotes: 1

yeger
yeger

Reputation: 387

You just need to do the same in the client and in the server:

#server
ssl.wrap_socket(connection,
                            server_side=True,
                            certfile="ssl/server.crt",
                            keyfile="ssl/server.key",
                            ca_certs="ssl/client.crt"
                            )


#client
ssl_sock = ssl.wrap_socket(s,
                   ca_certs="ssl/server.crt",
                   cert_reqs=ssl.CERT_REQUIRED,
                   certfile="ssl/client.crt",
                   keyfile="ssl/client.key"
                   )

I know this is an old one, but I looked for the same thing and didn't find an answer.

Upvotes: 0

Related Questions