def test_ssl_https_compatibility_disagreement():
client, server = ssl_memory_stream_pair(
server_kwargs={"https_compatible": False},
client_kwargs={"https_compatible": True}
)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
# client is in HTTPS-mode, server is not
# so client doing graceful_shutdown causes an error on server
async def receive_and_expect_error():
with pytest.raises(BrokenStreamError) as excinfo:
await server.receive_some(10)
assert isinstance(excinfo.value.__cause__, tssl.SSLEOFError)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.aclose)
nursery.start_soon(receive_and_expect_error)
python类SSLEOFError()的实例源码
def __write(self):
size = self.__writer.size()
data = self.__writer._getvalue()
try:
sent_size = self.__socket.send(data)
except BlockingIOError:
self.__write_ok = False
self.__writer.write(data)
except ssl.SSLWantWriteError:
return
except (ConnectionError, ssl.SSLEOFError):
raise HttpErr("the connection has been closed")
if size == sent_size:
self.__write_ok = True
return
bdata = data[sent_size:]
self.__writer.write(bdata)
self.__write_ok = False
def run(self):
self.handle_protocol_negotiation()
if not (self.cancelled or self.vars["RDP_PROTOCOL"] == 0):
self.enableSSL()
if args.fake_server:
try:
self.run_fake_server()
except ConnectionResetError:
print("Connection lost")
while not self.cancelled and not args.fake_server:
try:
self.forward_data()
except (ssl.SSLError, ssl.SSLEOFError) as e:
print("SSLError: %s" % str(e))
except (ConnectionResetError, OSError) as e:
print("Connection lost")
if "creds" in self.vars:
stop_attack()
def enableSSL(self):
print("Enable SSL")
try:
sslversion = get_ssl_version(self.lsock)
self.lsock = ssl.wrap_socket(
self.lsock,
server_side=True,
keyfile=args.keyfile,
certfile=args.certfile,
ssl_version=sslversion,
)
try:
self.rsock = ssl.wrap_socket(self.rsock, ciphers="RC4-SHA")
except ssl.SSLError:
self.rsock = ssl.wrap_socket(self.rsock, ciphers=None)
except ConnectionResetError:
print("Connection lost")
except ssl.SSLEOFError:
print("SSL EOF Error during handshake")
except AttributeError:
# happens when there is no rsock, i.e. fake_server==True
pass
def finish_response(self):
# If the browser closes the connection while we still want to sen stuff back,
# we want to fail silently and give up. This often happens in tests where the
# browser may want to request embedded links (like stylesheets) too, yet the
# test has already clicked on the next link.
if six.PY3:
ssl_eof_error = ssl.SSLEOFError
broken_pipe_error = BrokenPipeError
else:
ssl_eof_error = ssl.SSLError
broken_pipe_error = socket.error
try:
ServerHandler.finish_response(self)
except (ssl_eof_error, broken_pipe_error):
# Silently ignore it if it looks like the client browser closed the connection.
pass
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
data += "INJECTED_INVALID_COMMAND\r\n"
#logger.debug("%s [client] => [server][mangled] %s"%(session,repr(data)))
try:
Vectors.SMTP.UntrustedIntercept.mangle_client_data(session, data, rewrite)
except ssl.SSLEOFError, se:
logging.info("%s - Server failed to negotiate SSL with Exception: %s"%(session, repr(se)))
session.close()
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
def handle_read(self):
if self.tls_starting:
self._do_tls_handshake()
else:
try:
asynchat.async_chat.handle_read(self)
except ssl.SSLEOFError:
self.handle_close()
def handle_read(self):
if self.tls_starting:
self._do_tls_handshake()
else:
try:
asynchat.async_chat.handle_read(self)
except ssl.SSLEOFError:
self.handle_close()
def ssl_echo_serve_sync(sock, *, expect_fail=False):
try:
wrapped = SERVER_CTX.wrap_socket(
sock, server_side=True, suppress_ragged_eofs=False
)
wrapped.do_handshake()
while True:
data = wrapped.recv(4096)
if not data:
# other side has initiated a graceful shutdown; we try to
# respond in kind but it's legal for them to have already gone
# away.
exceptions = (BrokenPipeError,)
# Under unclear conditions, CPython sometimes raises
# SSLWantWriteError here. This is a bug (bpo-32219), but it's
# not our bug, so ignore it.
exceptions += (stdlib_ssl.SSLWantWriteError,)
if WORKAROUND_PYPY_BUG:
exceptions += (stdlib_ssl.SSLEOFError,)
try:
wrapped.unwrap()
except exceptions:
pass
return
wrapped.sendall(data)
except Exception as exc:
if expect_fail:
print("ssl_echo_serve_sync got error as expected:", exc)
else: # pragma: no cover
raise
else:
if expect_fail: # pragma: no cover
raise RuntimeError("failed to fail?")
# Fixture that gives a raw socket connected to a trio-test-1 echo server
# (running in a thread). Useful for testing making connections with different
# SSLContexts.
#
# This way of writing it is pretty janky, with the nursery hidden inside the
# fixture and no proper parental supervision. Don't copy this code; it was
# written this way before we knew better.
def rpc_call_raw(self, json_data, send_only=False):
"""
Send a raw JSON request to the server
This method does not validate the input JSON. Also you have to make sure
that if you send a request where the "id" parameter has the value "null"
the parameter send_only must be True. Otherwise the client will block
indefinitely because the server sees it as a notify request and does not
send an answer.
If we are currently not connected with the server this method will call
__connect() to create a connection.
Args:
json_data (str): The JSON that is sent to the server as is
send_only (bool): Only send the request, don't try to read a response
Returns:
str: The response string as returned by the server
None: If send_only is True
Raises:
NetworkError: Any network error
"""
try:
if not self.is_connected():
self.__connect()
retry_count = 0
json_reply = None
while True:
try:
self.send_request(json_data)
if send_only:
return
json_reply = self.receive_response()
break
except IOError as e:
if e.errno == errno.ECONNRESET and self.auto_reconnect and retry_count < 1:
retry_count += 1
self.__connect()
else:
raise e
return json_reply
except (ConnectionRefusedError, socket.error, SSLEOFError,
TLSHostnameError) as e:
self.close_connection()
raise NetworkError(e)