Verify Peer in python
I am trying to create a socket connection using python.
Here is my python code...
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.settimeout(config['timeout'])
self.socket.connect((config['host'], config['port']))
self.ssl = ssl.wrap_socket(
self.socket,
certfile=config['certificate'],
keyfile=config['key']
)
It didn't work as remote server's certificate seems to be self-signed or missing from trust store. I am new to python and could not figure out how to disable verify_peer in python so connection could work.
I have working code in php...
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'local_cert' => $config['certificate'],
'local_pk' => $config['key']
]
]);
$socket = stream_socket_client(
'ssl://secure.test.com:700',
$errno, $errstr, $config['timeout'],
STREAM_CLIENT_CONNECT, $context
);
Setting 'verify_peer' => false
helps to establish the connection. How can i do something like that in python?
openssl debug
openssl s_client -connect secure.test.com:700
verify error:num=20:unable to get local issuer certificate
verify return:1
verify error:num=21:unable to verify the first certificate
verify return:1
Please help and suggest. Thanks
Disabling certificate validation can simply be done by adding cert_reqs = ssl.CERT_NONE
. But, just disabling certificate validation is a very bad idea since you know open to man-in-the-middle attacks .
Therefore you should check that the certificate is the expected one. With self-signed certificates (and others too) you can check for example that the received certificate matches the expected certificate fingerprint, like in the following code:
import socket
import ssl
import hashlib
dst = ('www.paypal.com',443)
fp_expected = '0722d46c216327bab8075f5db57ebed64d80e6699204c249c3f6ea9cc281c15b'
# connect to the target with TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(dst)
# upgrade the socket to SSL without checking the certificate
s = ssl.wrap_socket(s,cert_reqs = ssl.CERT_NONE)
# get certificate, compute fingerprint and check against expected value
cert_bin = s.getpeercert(True)
fp = hashlib.sha256()
fp.update(cert_bin)
assert(fp.hexdigest() == fp_expected)
链接地址: http://www.djcxy.com/p/21750.html
上一篇: ssl证书如何验证?
下一篇: 在Python中验证Peer