def writeSomeData(self, data):
try:
return Connection.writeSomeData(self, data)
except SSL.WantWriteError:
return 0
except SSL.WantReadError:
self.writeBlockedOnRead = 1
Connection.stopWriting(self)
Connection.startReading(self)
return 0
except SSL.ZeroReturnError:
return main.CONNECTION_LOST
except SSL.SysCallError, e:
if e[0] == -1 and data == "":
# errors when writing empty strings are expected
# and can be ignored
return 0
else:
return main.CONNECTION_LOST
except SSL.Error, e:
return e
python类SysCallError()的实例源码
def doRead(self):
if self.writeBlockedOnRead:
self.writeBlockedOnRead = 0
self._resetReadWrite()
try:
return Connection.doRead(self)
except SSL.ZeroReturnError:
return main.CONNECTION_DONE
except SSL.WantReadError:
return
except SSL.WantWriteError:
self.readBlockedOnWrite = 1
Connection.startWriting(self)
Connection.stopReading(self)
return
except SSL.SysCallError, (retval, desc):
if ((retval == -1 and desc == 'Unexpected EOF')
or retval > 0):
return main.CONNECTION_LOST
log.err()
return main.CONNECTION_LOST
except SSL.Error, e:
return e
LuckyThirteen_vulnerability_tester_plugin.py 文件源码
项目:midip-sslyze
作者: soukupa5
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def test_dtls_protocol_support(self, server_connectivity_info, dtls_version, port):
"""Tests if DTLS protocols are supported by server. Returns true if server supports protocol otherwise returns false.
Args:
server_connectivity_info (ServerConnectivityInfo): contains information for connection on server
dtls_protocol (str): contains version of DTLS protocol, which is supposed to be tested
port (int): contains port number for connecting comunication.
"""
cnx = SSL.Context(dtls_version)
cnx.set_cipher_list('ALL:COMPLEMENTOFALL')
conn = SSL.Connection(cnx,socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
try:
conn.connect((server_connectivity_info.ip_address, port))
conn.do_handshake()
except SSL.SysCallError as ex:
if ex[0] == 111:
raise ValueError('LuckyThirteenVulnerabilityTesterPlugin: It is entered wrong port for DTLS connection.')
else:
support = False
else:
support = True
finally:
conn.shutdown()
conn.close()
return support
def send(self, data, flags=0, timeout=timeout_default):
if timeout is timeout_default:
timeout = self.timeout
while True:
try:
return self._sock.send(data, flags)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_write(self.fileno(), timeout=timeout)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=timeout)
except SSL.SysCallError, ex:
if ex[0] == -1 and data == "":
# errors when writing empty strings are expected and can be ignored
return 0
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def recv(self, buflen):
pending = self._sock.pending()
if pending:
return self._sock.recv(min(pending, buflen))
while True:
try:
return self._sock.recv(buflen)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.ZeroReturnError:
return ''
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def send(self, data, flags=0, timeout=timeout_default):
if timeout is timeout_default:
timeout = self.timeout
while True:
try:
return self._sock.send(data, flags)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_write(self.fileno(), timeout=timeout)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=timeout)
except SSL.SysCallError, ex:
if ex[0] == -1 and data == "":
# errors when writing empty strings are expected and can be ignored
return 0
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def recv(self, buflen):
pending = self._sock.pending()
if pending:
return self._sock.recv(min(pending, buflen))
while True:
try:
return self._sock.recv(buflen)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.ZeroReturnError:
return ''
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def test_inline_read_error(self):
# An error on an inline read is raised without logging (on the
# assumption that it will eventually be noticed or logged further
# up the stack).
#
# This test is posix-only because windows os.close() doesn't work
# on socket FDs, but we can't close the socket object normally
# because we won't get the error we want if the socket knows
# it's closed.
server, client = self.make_iostream_pair()
try:
os.close(server.socket.fileno())
if isinstance(server, MicroProxySSLIOStream):
with self.assertRaises(SSL.SysCallError):
server.read_bytes(1, lambda data: None)
if isinstance(server, MicroProxyIOStream):
with self.assertRaises(socket.error):
server.read_bytes(1, lambda data: None)
finally:
server.close()
client.close()
def doRead(self):
if self.writeBlockedOnRead:
self.writeBlockedOnRead = 0
self._resetReadWrite()
try:
return Connection.doRead(self)
except SSL.ZeroReturnError:
return main.CONNECTION_DONE
except SSL.WantReadError:
return
except SSL.WantWriteError:
self.readBlockedOnWrite = 1
Connection.startWriting(self)
Connection.stopReading(self)
return
except SSL.SysCallError, (retval, desc):
if ((retval == -1 and desc == 'Unexpected EOF')
or retval > 0):
return main.CONNECTION_LOST
log.err()
return main.CONNECTION_LOST
except SSL.Error, e:
return e
def writeSomeData(self, data):
try:
return Connection.writeSomeData(self, data)
except SSL.WantWriteError:
return 0
except SSL.WantReadError:
self.writeBlockedOnRead = 1
Connection.stopWriting(self)
Connection.startReading(self)
return 0
except SSL.ZeroReturnError:
return main.CONNECTION_LOST
except SSL.SysCallError, e:
if e[0] == -1 and data == "":
# errors when writing empty strings are expected
# and can be ignored
return 0
else:
return main.CONNECTION_LOST
except SSL.Error, e:
return e
def send(self, data, flags=0, timeout=timeout_default):
if timeout is timeout_default:
timeout = self.timeout
while True:
try:
return self._sock.send(data, flags)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_write(self.fileno(), timeout=timeout)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=timeout)
except SSL.SysCallError, ex:
if ex[0] == -1 and data == "":
# errors when writing empty strings are expected and can be ignored
return 0
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def recv(self, buflen):
pending = self._sock.pending()
if pending:
return self._sock.recv(min(pending, buflen))
while True:
try:
return self._sock.recv(buflen)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.ZeroReturnError:
return ''
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def send(self, data, flags=0, timeout=timeout_default):
if timeout is timeout_default:
timeout = self.timeout
while True:
try:
return self._sock.send(data, flags)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_write(self.fileno(), timeout=timeout)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=timeout)
except SSL.SysCallError, ex:
if ex[0] == -1 and data == "":
# errors when writing empty strings are expected and can be ignored
return 0
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def recv(self, buflen):
pending = self._sock.pending()
if pending:
return self._sock.recv(min(pending, buflen))
while True:
try:
return self._sock.recv(buflen)
except SSL.WantReadError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.WantWriteError, ex:
if self.timeout == 0.0:
raise timeout(str(ex))
else:
sys.exc_clear()
wait_read(self.fileno(), timeout=self.timeout)
except SSL.ZeroReturnError:
return ''
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def recv(self, bufsiz, flags=None):
pending = self._connection.pending()
if pending:
return self._connection.recv(min(pending, bufsiz))
try:
return self.__iowait(self._connection.recv, bufsiz, flags)
except SSL.ZeroReturnError as e:
if self._connection.get_shutdown() == SSL.RECEIVED_SHUTDOWN:
return b''
raise e
except SSL.SysCallError as e:
if e.args == zero_EOF_error:
return b''
elif e.args[0] in zero_errno:
return b''
raise e
def recv_into(self, buffer, nbytes=None, flags=None):
pending = self._connection.pending()
if pending:
return self._connection.recv_into(buffer)
try:
return self.__iowait(self._connection.recv_into, buffer, nbytes, flags)
except SSL.ZeroReturnError as e:
if self._connection.get_shutdown() == SSL.RECEIVED_SHUTDOWN:
return 0
raise e
except SSL.SysCallError as e:
if e.args == zero_EOF_error:
return 0
elif e.args[0] in zero_errno:
return 0
raise e
def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.close_request(request)
except (socket.error, SSL.SysCallError), why:
print 'socket.error finishing request from "%s"; Error: %s' % (client_address, str(why))
self.close_request(request)
except:
self.handle_error(request, client_address)
self.close_request(request)
def close(self):
"""Shutdown the SSL connection and call the close method of the
underlying socket"""
if self._makefile_refs < 1:
try:
self.__ssl_conn.shutdown()
except (SSL.Error, SSL.SysCallError):
# Make errors on shutdown non-fatal
pass
else:
self._makefile_refs -= 1
def do_handshake(self):
while True:
try:
self._sock.do_handshake()
break
except SSL.WantReadError:
sys.exc_clear()
wait_read(self.fileno())
except SSL.WantWriteError:
sys.exc_clear()
wait_write(self.fileno())
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def do_handshake(self):
while True:
try:
self._sock.do_handshake()
break
except SSL.WantReadError:
sys.exc_clear()
wait_read(self.fileno())
except SSL.WantWriteError:
sys.exc_clear()
wait_write(self.fileno())
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def load_crt(self, crt):
'''
Load certificate file content to openssl x509 object.
:param crt: Certificate file path.
:type crt: String.
:returns: Informational result dict {'error': Boolean, 'message': if error String else x509 object}
:rtype: Dict.
'''
try:
x509obj = crypto.load_certificate(
crypto.FILETYPE_PEM, open(crt).read())
except SSL.SysCallError as e:
res = {"error": True, "message": e.strerror + " " + e.filename}
#print(ex.args, ex.errno, ex.filename, ex.strerror)
except SSL.Error as f:
res = {"error": True, "message": f.strerror + " " + f.filename}
except SSL.WantReadError as r:
res = {"error": True, "message": r.strerror + " " + r.filename}
except SSL.WantWriteError as w:
res = {"error": True, "message": w.strerror + " " + w.filename}
except SSL.WantX509LookupError as x:
res = {"error": True, "message": x.strerror + " " + x.filename}
except Exception as ex:
res = {"error": True, "message": ex.strerror + " " + ex.filename}
except:
res = {"error": True, "message": "Unexpected error"}
else:
res = {"error": False, "message": x509obj}
finally:
return(res)
def read_from_fd(self):
if self._ssl_accepting:
return None
try:
chunk = self.socket.read(self.read_chunk_size)
except SSL.WantReadError:
return None
except SSL.ZeroReturnError:
self.close(exc_info=True)
return None
except SSL.SysCallError as e:
err_num = abs(e[0])
if err_num in (errno.EWOULDBLOCK, errno.EAGAIN):
return None
# NOTE: We will handle the self.close in here.
# _read_to_buffer of BaseIOStream will not chceck SSL.SysCallError
if err_num == errno.EPERM:
self.close(exc_info=True)
return None
self.close(exc_info=True)
raise
# NOTE: Just in case we missed some SSL Error type.
except SSL.Error as e:
raise
if not chunk:
self.close()
return None
return chunk
def start_dest_tls(self, hostname, client_alpns):
trusted_ca_certs = self.config["client_certs"] or certifi.where()
try:
logger.debug("start dest tls handshaking: {0}".format(hostname))
dest_stream = yield self.dest_conn.start_tls(
insecure=self.config["insecure"],
trusted_ca_certs=trusted_ca_certs,
hostname=hostname, alpns=client_alpns)
# TODO: tornado_ext.iostream should handle this part.
except SSL.SysCallError as e:
raise DestStreamClosedError(detail="Stream closed when tls Handshaking failed")
except (SSL.Error, VerificationError) as e:
raise TlsError("Tls Handshaking Failed on destination with: ({0}) {1}".format(
type(e).__name__, str(e)))
else:
logger.debug(dest_stream.fileno().get_alpn_proto_negotiated())
select_alpn = (dest_stream.fileno().get_alpn_proto_negotiated() or
b"http/1.1")
logger.debug("{0}:{1} -> Choose {2} as application protocol".format(
self.context.host, self.context.port, select_alpn))
logger.debug("finish dest tls handshake")
raise gen.Return((dest_stream, select_alpn))
def _send_raw(self):
while True:
self.ssl_write = None
slen = 0
try:
slen = self.sock.send(self.send_buf)
except (socket.error, OSError, SSL.ZeroReturnError, SSL.SysCallError, SSL.WantReadError):
break
except SSL.WantWriteError:
self.ssl_write = True
self.send_buf = self.send_buf[slen:]
if len(self.send_buf) < 1:
self.send_buf = None
break
def do_handshake(self):
while True:
try:
self._sock.do_handshake()
break
except SSL.WantReadError:
sys.exc_clear()
wait_read(self.fileno())
except SSL.WantWriteError:
sys.exc_clear()
wait_write(self.fileno())
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def close(self):
"""Shutdown the SSL connection and call the close method of the
underlying socket"""
if self._makefile_refs < 1:
try:
self.__ssl_conn.shutdown()
except (SSL.Error, SSL.SysCallError):
# Make errors on shutdown non-fatal
pass
else:
self._makefile_refs -= 1
def close(self):
"""Shutdown the SSL connection and call the close method of the
underlying socket"""
if self._makefile_refs < 1:
try:
self.__ssl_conn.shutdown()
except (SSL.Error, SSL.SysCallError):
# Make errors on shutdown non-fatal
pass
else:
self._makefile_refs -= 1
def close(self):
"""Shutdown the SSL connection and call the close method of the
underlying socket"""
if self._makefile_refs < 1:
try:
self.__ssl_conn.shutdown()
except (SSL.Error, SSL.SysCallError):
# Make errors on shutdown non-fatal
pass
else:
self._makefile_refs -= 1
def do_handshake(self):
while True:
try:
self._sock.do_handshake()
break
except SSL.WantReadError:
sys.exc_clear()
wait_read(self.fileno())
except SSL.WantWriteError:
sys.exc_clear()
wait_write(self.fileno())
except SSL.SysCallError, ex:
raise sslerror(SysCallError_code_mapping.get(ex.args[0], ex.args[0]), ex.args[1])
except SSL.Error, ex:
raise sslerror(str(ex))
def __iowait(self, io_func, *args, **kwargs):
timeout = self._sock.gettimeout()
fd = self._sock
while self._connection:
try:
return io_func(*args, **kwargs)
except (SSL.WantReadError, SSL.WantX509LookupError):
#exc_clear()
rd, _, ed = select([fd], [], [fd], timeout)
if ed:
raise socket.error(ed)
if not rd:
raise socket.timeout('The read operation timed out')
except SSL.WantWriteError:
#exc_clear()
_, wd, ed = select([], [fd], [fd], timeout)
if ed:
raise socket.error(ed)
if not wd:
raise socket.timeout('The write operation timed out')
except SSL.SysCallError as e:
if e.args[0] == errno.EWOULDBLOCK:
#exc_clear()
rd, wd, ed = select([fd], [fd], [fd], timeout)
if ed:
raise socket.error(ed)
if not rd and not wd:
raise socket.timeout('The socket operation timed out')
elif e.args[0] == errno.EAGAIN:
continue
else:
raise e