【问题标题】:Python SSL socket can't connect to self-signed certificatePython SSL套接字无法连接到自签名证书
【发布时间】:2017-05-10 13:31:36
【问题描述】:

我需要将 SSL 套接字连接到 SSL 服务器。如果服务器的证书是自签名的,则以下脚本将失败。但是如果服务器的证书是签名的,它就可以工作。您能帮我如何使用自签名证书成功连接到服务器吗?

import StringIO
import csv     #for csv
from M2Crypto.Err import SSLError
import ssl
import socket
import pprint
import M2Crypto
from M2Crypto import X509, RSA

from datetime import datetime
import MySQLdb

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_NONE

host='209.18.59.115'
print 'host is: ', host
port=443

#creating ssl socket
ssock = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=host)

#ssl connection
try:
    ssock.connect((host, port))
except socket.error: #if tls connection is not possible, print error message, then go to next host.
    print "Faile connection with: " + host

编辑: 我得到的输出是异常语句中的内容:

host is:  209.18.59.115
Faile connection with: 209.18.59.115 

EDIT2: 回溯是:

Traceback (most recent call last):
  File "C:/Users/xxx/PycharmProjects/tlsScan/test2.py", line 28, in <module>
    ssock.connect((host, port))
  File "C:\Python27\lib\ssl.py", line 824, in connect
    self._real_connect(addr, False)
  File "C:\Python27\lib\ssl.py", line 815, in _real_connect
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 788, in do_handshake
Faile connection with: 209.18.59.115
    self._sslobj.do_handshake()
SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:581)
None

【问题讨论】:

  • 调用上下文的load_verify_locations 方法,将cafile 参数设置为包含自签名证书的文件的名称。
  • @fuglede:简单地忽略证书会使中间人攻击变得容易。即使是自签名证书也可以并且应该得到正确验证。
  • @James K Polk 这对我不起作用。我将需要连接到我不知道其证书文件名的服务器列表。它们是远程服务器。
  • @Steffen Ullrich 我知道这一点。但这不是我的问题。我的脚本用于测试目的,需要连接到自签名证书。

标签: python python-2.7 sockets ssl tls1.2


【解决方案1】:

问题出在这一行: 上下文 = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

碰巧我尝试连接的服务器不支持 TLSv1.2。当我将行更改为以下内容时,它可以工作: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) #我们选择SSLv23,因为它兼容除SSLv2之外的所有版本。

TLS 客户端/服务器兼容性表(来源:https://docs.python.org/2/library/ssl.html): 下表显示了客户端中的哪些版本(下方)可以连接到服务器中的哪些版本(上方):

client / server     SSLv2   SSLv3   SSLv23  TLSv1   TLSv1.1     TLSv1.2
SSLv2                yes     no       yes    no        no         no
SSLv3                no      yes      yes    no        no         no
SSLv23               no      yes      yes    yes       yes        yes
TLSv1                no      no       yes    yes       no         no
TLSv1.1              no      no       yes    no        yes        no
TLSv1.2              no      no       yes    no        no         yes

因为 TLSv23 与服务器支持的大多数版本兼容,所以我选择了它并且它工作正常。

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2017-05-08
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2023-03-02
    • 2019-04-26
    相关资源
    最近更新 更多