Wrap an existing Python socket connection and return a TLS socket object.
(
self,
sock: _socket.socket,
server_side: bool = False,
do_handshake_on_connect: bool = True,
suppress_ragged_eofs: bool = True,
server_hostname: Optional[str] = None,
session: Optional[_SSL.Session] = None,
)
| 373 | self._ctx.set_default_verify_paths() |
| 374 | |
| 375 | def wrap_socket( |
| 376 | self, |
| 377 | sock: _socket.socket, |
| 378 | server_side: bool = False, |
| 379 | do_handshake_on_connect: bool = True, |
| 380 | suppress_ragged_eofs: bool = True, |
| 381 | server_hostname: Optional[str] = None, |
| 382 | session: Optional[_SSL.Session] = None, |
| 383 | ) -> _sslConn: |
| 384 | """Wrap an existing Python socket connection and return a TLS socket |
| 385 | object. |
| 386 | """ |
| 387 | ssl_conn = _sslConn(self._ctx, sock, suppress_ragged_eofs) |
| 388 | if session: |
| 389 | ssl_conn.set_session(session) |
| 390 | if server_side is True: |
| 391 | ssl_conn.set_accept_state() |
| 392 | else: |
| 393 | # SNI |
| 394 | if server_hostname and not _is_ip_address(server_hostname): |
| 395 | # XXX: Do this in a callback registered with |
| 396 | # SSLContext.set_info_callback? See Twisted for an example. |
| 397 | ssl_conn.set_tlsext_host_name(server_hostname.encode("idna")) |
| 398 | if self.verify_mode != _stdlibssl.CERT_NONE: |
| 399 | # Request a stapled OCSP response. |
| 400 | ssl_conn.request_ocsp() |
| 401 | ssl_conn.set_connect_state() |
| 402 | # If this wasn't true the caller of wrap_socket would call |
| 403 | # do_handshake() |
| 404 | if do_handshake_on_connect: |
| 405 | # XXX: If we do hostname checking in a callback we can get rid |
| 406 | # of this call to do_handshake() since the handshake |
| 407 | # will happen automatically later. |
| 408 | ssl_conn.do_handshake() |
| 409 | # XXX: Do this in a callback registered with |
| 410 | # SSLContext.set_info_callback? See Twisted for an example. |
| 411 | if self.check_hostname and server_hostname is not None: |
| 412 | from service_identity import pyopenssl |
| 413 | |
| 414 | try: |
| 415 | if _is_ip_address(server_hostname): |
| 416 | pyopenssl.verify_ip_address(ssl_conn, server_hostname) |
| 417 | else: |
| 418 | pyopenssl.verify_hostname(ssl_conn, server_hostname) |
| 419 | except ( |
| 420 | service_identity.CertificateError, |
| 421 | service_identity.VerificationError, |
| 422 | ) as exc: |
| 423 | raise _CertificateError(str(exc)) from None |
| 424 | return ssl_conn |