我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用OpenSSL.SSL.SysCallError()。
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 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 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 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 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 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 __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
def makefile(self, *args): """Specific to Python socket API and required by httplib: convert response into a file-like object. This implementation reads using recv and copies the output into a StringIO buffer to simulate a file object for consumption by httplib Nb. Ignoring optional file open mode (StringIO is generic and will open for read and write unless a string is passed to the constructor) and buffer size - httplib set a zero buffer size which results in recv reading nothing @return: file object for data returned from socket @rtype: cStringIO.StringO """ self._makefile_refs += 1 # Optimisation _buf_size = self.buf_size i=0 stream = BytesIO() startTime = datetime.utcnow() try: dat = self.__ssl_conn.recv(_buf_size) while dat: i+=1 stream.write(dat) dat = self.__ssl_conn.recv(_buf_size) except (SSL.ZeroReturnError, SSL.SysCallError): # Connection is closed - assuming here that all is well and full # response has been received. httplib will catch an error in # incomplete content since it checks the content-length header # against the actual length of data received pass if log.getEffectiveLevel() <= logging.DEBUG: log.debug("Socket.makefile %d recv calls completed in %s", i, datetime.utcnow() - startTime) # Make sure to rewind the buffer otherwise consumers of the content will # read from the end of the buffer stream.seek(0) return stream
def load_crl(self, crlfile): ''' Load crl file content to openssl x509 object. :param crlfile: CRL file path. :type crlfile: String. :returns: Informational result dict {'error': Boolean, 'message': if error String else x509 object} :rtype: Dict. ''' if not ospath.isfile(crlfile): x509obj = crypto.CRL() if self.__verbose: print("INFO: New CRL " + crlfile + " created.") res = {"error": False, "message": x509obj} return(res) else: try: x509obj = crypto.load_crl( crypto.FILETYPE_PEM, open(crlfile).read()) except SSL.SysCallError as e: res = {"error": True, "message": e.strerror + " " + e.filename} #print(e.args, e.errno, e.filename, e.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 _do_ssl_handshake(self): try: self._handshake_reading = False self._handshake_writing = False self.socket.do_handshake() except SSL.WantReadError: self._handshake_reading = True return except SSL.WantWriteError: self._handshake_writing = True return except SSL.SysCallError as e: err_num = abs(e[0]) if err_num in (errno.EBADF, errno.ENOTCONN, errno.EPERM): return self.close(exc_info=True) raise except SSL.Error as err: try: peer = self.socket.getpeername() except Exception: peer = '(not connected)' logger.warning("SSL Error on %s %s: %s", self.socket.fileno(), peer, err) return self.close(exc_info=True) except AttributeError: return self.close(exc_info=True) else: self._ssl_accepting = False verify_mode = self.socket.get_context().get_verify_mode() if (verify_mode != SSL.VERIFY_NONE and self._server_hostname is not None): try: verify_hostname(self.socket, self._server_hostname) except VerificationError as e: logger.warning("Invalid SSL certificate: {0}".format(e)) self.close(exc_info=True) return self._run_ssl_connect_callback()
def _safe_call(self, is_reader, call, *args, **kwargs): """Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """ start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" errnum = e.args[0] if is_reader and errnum in wsgiserver.socket_errors_to_ignore: return "" raise socket.error(errnum) except SSL.Error, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise wsgiserver.NoSSLError() raise wsgiserver.FatalSSLAlert(*e.args) except: raise if time.time() - start > self.ssl_timeout: raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs): """Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """ start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" errnum = e.args[0] if is_reader and errnum in socket_errors_to_ignore: return "" raise socket.error(errnum) except SSL.Error, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise NoSSLError() raise FatalSSLAlert(*e.args) except: raise if time.time() - start > self.ssl_timeout: raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs): """Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """ start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return '' errnum = e.args[0] if is_reader and errnum in wsgiserver.socket_errors_to_ignore: return '' raise socket.error(errnum) except SSL.Error as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return '' thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise wsgiserver.NoSSLError() raise wsgiserver.FatalSSLAlert(*e.args) except: raise if time.time() - start > self.ssl_timeout: raise socket.timeout('timed out')
def _safe_call(self, is_reader, call, *args, **kwargs): """Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """ start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" errnum = e.args[0] if is_reader and errnum in wsgiserver.socket_errors_to_ignore: return "" raise socket.error(errnum) except SSL.Error as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise wsgiserver.NoSSLError() raise wsgiserver.FatalSSLAlert(*e.args) except: raise if time.time() - start > self.ssl_timeout: raise socket.timeout("timed out")
def _ssl_wrap_method(method, is_reader=False): """Wrap the given method with SSL error-trapping. is_reader: if False (the default), EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets). """ def ssl_method_wrapper(self, *args, **kwargs): ## print (id(self), method, args, kwargs) start = time.time() while True: try: return method(self, *args, **kwargs) except (SSL.WantReadError, SSL.WantWriteError): # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. time.sleep(self.ssl_retry) except SSL.SysCallError, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" errno = e.args[0] if is_reader and errno in socket_errors_to_ignore: return "" raise socket.error(errno) except SSL.Error, e: if is_reader and e.args == (-1, 'Unexpected EOF'): return "" thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if is_reader and thirdarg == 'ssl handshake failure': return "" if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise NoSSLError() raise if time.time() - start > self.ssl_timeout: raise socket.timeout("timed out") return ssl_method_wrapper