Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
user3096370 Avatar asked Nov 23 '22 04:11

user3096370


1 Answers

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')
like image 86
Ahmad Khan Avatar answered Jun 08 '23 12:06

Ahmad Khan