TLS 握手未完成

TLS handshake not completing

我有一个带有自签名证书的客户端和服务器应用程序。 do_handshake 方法无法正常工作。在客户端中,SSL 协商成功完成,但在服务器上没有。服务器一直说 before SSL initialization(使用 get_state_string())。

查看代码。 客户

from OpenSSL import SSL, crypto
import socket

HOST = "localhost"
PORT = 8080

def verify_cb(conn, cert, errnum, depth, ok):
    print(f"Got certificate: %s {cert.get_subject()}")
    print(f"Issued by: {cert.get_issuer()}")
    return ok

# Initialise SSL context:
ctx = SSL.Context(SSL.TLSv1_2_METHOD)
ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a server certificate
ctx.load_verify_locations("serverpath.pem")
ctx.use_privatekey_file('clientkey.pem')
ctx.use_certificate_file('clientpath.pem')

# Set up client:
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))

sock.connect((HOST, PORT))
sock.set_connect_state()
print(sock.get_state_string())
while True:
    try:
        sock.do_handshake()
        break
    except SSL.WantReadError:
        pass
print(sock.get_state_string())
sock.write("HELLO")

# Read response:
while True:
    try:
        print(sock.recv(4096))
    except SSL.ZeroReturnError:
        break

服务器

from OpenSSL import SSL, crypto
import socket

HOST = "localhost"
PORT = 8080

def verify_cb(conn, cert, errnum, depth, ok):
    print(f"Got certificate: %s {cert.get_subject()}")
    print(f"Issued by: {cert.get_issuer()}")
    return ok

# Initialise SSL context:
ctx = SSL.Context(SSL.TLSv1_2_METHOD)
ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a client certificate
ctx.load_verify_locations("clientpath.pem")
ctx.use_privatekey_file('serverkey.pem')
ctx.use_certificate_file('serverpath.pem')
# Set up sever:
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)

print("Waiting for connections.")

#Wait for clients to connect:
(conn, address) = sock.accept()
sock.set_accept_state()
print(f"Got connection from {address}")
print(sock.get_state_string())
while True:
    try:
        print(sock.get_state_string())
        print(conn.recv(4096))
        print(sock.get_state_string())
    except SSL.ZeroReturnError:
        break

拜托,谁能告诉我我做错了什么?

(conn, address) = sock.accept()
sock.set_accept_state()
print(f"Got connection from {address}")
print(sock.get_state_string())
while True:
    try:
        print(sock.get_state_string())
        print(conn.recv(4096))
        print(sock.get_state_string())

您需要在接受的套接字 conn 上操作,而不是在服务器套接字 sock 上操作。当您从接受的套接字中读取时,您打印的是服务器套接字的状态,这并不反映已连接套接字的状态。此外,您不需要设置接受状态,因为您已经在 SSL 服务器套接字上调用了 accept

(conn, address) = sock.accept()
print(f"Got connection from {address}")
print(conn.get_state_string())
while True:
    try:
        print(conn.get_state_string())
        print(conn.recv(4096))
        print(conn.get_state_string())