지원 중단된 ssl.wrap_socket 사용

지원 중단된 ssl.wrap_socket 사용

설명

모듈 함수 ssl.wrap_socket은 Python 3.7에서 사용 중단이 예고됐고 3.12에서 제거됐습니다. 소켓을 TLS로 연결하려면 ssl.SSLContext의 wrap_socket()을 사용하세요.

잠재적 영향

Python 3.12 이상에서는 이전 함수를 호출할 수 없습니다. 이전 버전에서도 인증서와 호스트명을 검증하지 않으면 서버를 사칭한 상대에게 민감한 데이터를 보낼 수 있습니다.

해결 방법

  • 클라이언트에서는 ssl.create_default_context()로 서버 인증서 체인을 검증하세요. 사설 CA를 쓴다면 해당 CA를 추가하고, server_hostname에 접속할 호스트명을 전달하세요.
  • 최소 TLS 버전을 1.2 이상으로 설정하고, 호환되는 환경에서는 TLS 1.3을 허용하세요.

예시

서버 예시를 실행하려면 서버 인증서와 개인키를 제공하고 요청 처리 코드를 추가하세요. 예시는 클라이언트 인증서를 요구하지 않습니다.

변경 전

python
# Unsafe ssl.wrap_socket
import socket
import ssl

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
wrapped_socket = ssl.wrap_socket(sock)
wrapped_socket.connect(('example.com', 443))

변경 후

Client 측

python
# Safe ssl.SSLContext Client
import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

Server 측

python
# Safe ssl.SSLContext Server
import socket
import ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...

설명

클라이언트는 TCP 연결을 연 뒤 SSLContext.wrap_socket()으로 서버를 검증합니다. 서버는 자체 인증서와 개인키를 불러와 TLS 연결을 받습니다.

참조