Python ssl.SSLWantReadError() Examples

The following are 30 code examples of ssl.SSLWantReadError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: tls.py    From heralding with GNU General Public License v3.0 6 votes vote down vote up
def do_tls_handshake(self):
    client_hello = await self.reader.read(4096)
    self._tlsInBuff.write(client_hello)
    try:
      self._tlsObj.do_handshake()
    except ssl.SSLWantReadError:
      server_hello = self._tlsOutBuff.read()
      self.writer.write(server_hello)
      await self.writer.drain()

    client_fin = await self.reader.read(4096)
    self._tlsInBuff.write(client_fin)
    try:
      self._tlsObj.do_handshake()
    except ssl.SSLWantReadError:
      raise TLSHandshakeError("Expected more data in Clinet FIN")

    server_fin = self._tlsOutBuff.read()
    self.writer.write(server_fin)
    await self.writer.drain() 
Example #2
Source File: control_channel.py    From pyopenvpn with MIT License 6 votes vote down vote up
def handle_in(self):
        self._sync_tls_in()

        try:
            data = self.tls.read()
        except ssl.SSLWantReadError:
            return

        if data.startswith(b'\x00\x00\x00\x00'):
            self.read_control_message(data)
        elif data.startswith(b'PUSH_REPLY'):
            self.c.on_push(data)
        elif data.startswith(b'AUTH_FAILED'):
            raise AuthFailed()
        else:
            self.log.warn("Unknown control packet: %r", data) 
Example #3
Source File: mumble.py    From botnet with MIT License 6 votes vote down vote up
def update(self):
        """Main method which should be called."""
        self.logger.debug('Update')
        try:
            self.restart_event.clear()
            self.flush_state()
            self.connect()
            self.identify()
            while not self.stop_event.is_set() and not self.restart_event.is_set():
                try:
                    data = self.soc.recv(4096)
                    if not data:
                        break
                    self.process_data(data)
                except CriticalProtocolError:
                    raise
                except (socket.timeout, ssl.SSLWantReadError) as e:
                    pass
            time.sleep(10)
        finally:
            if self.soc:
                self.soc.close() 
Example #4
Source File: irc.py    From botnet with MIT License 6 votes vote down vote up
def update(self):
        """Main method which should be called."""
        self.logger.debug('Update')
        with self.get_inactivity_monitor():
            try:
                self.restart_event.clear()
                self.buffer = Buffer()
                self.connect()
                self.identify()
                while not self.stop_event.is_set() and not self.restart_event.is_set():
                    try:
                        data = self.soc.recv(4096)
                        if not data:
                            break
                        self.process_data(data)
                    except (socket.timeout, ssl.SSLWantReadError) as e:
                        pass
            finally:
                if self.soc:
                    self.soc.close() 
Example #5
Source File: client_ssl.py    From untwisted with MIT License 6 votes vote down vote up
def do_handshake(self, spin):
        """
        """

        try:
            spin.do_handshake()
        except ssl.CertificateError as excpt:
            spin.drive(SSL_CERTIFICATE_ERR, excpt)
        except ssl.SSLWantReadError:
            pass
        except ssl.SSLWantWriteError:
            pass
        except socket.error as excpt:
            # When it happens then it should spawn SSL_CONNECT_ERR.
            spin.drive(SSL_CONNECT_ERR, excpt)
        except ssl.SSLError as excpt:
            spin.drive(SSL_CONNECT_ERR, excpt)
        else:
            spin.drive(SSL_CONNECT)
            raise Erase 
Example #6
Source File: dump_ssl.py    From untwisted with MIT License 6 votes vote down vote up
def process(self, spin):
        # When ssl.SSLEOFError happens it shouldnt spawn CLOSE
        # because there may exist data to be read.
        # If it spawns CLOSE the socket is closed and no data
        # can be read from.
        try:
            size = spin.send(self.data)  
        except ssl.SSLWantReadError:
            spin.drive(SSL_SEND_ERR, spin, excpt)
        except ssl.SSLWantWriteError:
            spin.drive(SSL_SEND_ERR, spin, excpt)
        except ssl.SSLEOFError as excpt:
            pass
        except ssl.SSLError as excpt:
            spin.drive(CLOSE, excpt)
        except socket.error as excpt:
            self.process_error(spin, excpt)
        else:
            self.data = self.data[size:] 
Example #7
Source File: tunnelc.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def do_ssl_handshake(self):
        try:
            self.socket.do_handshake()
            self.__ssl_handshake_ok = True

            # 如果开启SNI那么匹配证书
            if self.__enable_https_sni:
                cert = self.socket.getpeercert()
                ssl.match_hostname(cert, self.__https_sni_host)

            logging.print_general("TLS_handshake_ok", self.__server_address)
            self.add_evt_read(self.fileno)
            self.send_handshake()
        except ssl.SSLWantReadError:
            self.add_evt_read(self.fileno)
        except ssl.SSLWantWriteError:
            self.add_evt_write(self.fileno)
        except:
            logging.print_error()
            self.delete_handler(self.fileno) 
Example #8
Source File: httpclient.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def __read(self):
        while 1:
            try:
                rdata = self.__socket.recv(4096)
            except BlockingIOError:
                break
            except ssl.SSLWantReadError:
                break
            if self.__ssl_on and not self.__ssl_ok:
                if self.__alpn_on:
                    protocol = self.__socket.selected_alpn_protocol()
                    if protocol == "h2": self.__is_http2 = True
                self.__ssl_ok = True

            if rdata:
                # if not self.__fd: self.__fd = open("test.txt", "wb")
                # self.__fd.write(rdata)
                self.__reader._putvalue(rdata)
            else:
                raise HttpErr("the connection has been closed")
        return 
Example #9
Source File: tls.py    From heralding with GNU General Public License v3.0 6 votes vote down vote up
def read_tls(self, size):
    data = b""
    # Check if we have any leftover data in the buffer
    try:
      data += self._tlsObj.read(size)
    except ssl.SSLWantReadError:
      pass

    # iterate until we have all needed plaintext
    while len(data) < size:
      if self.reader.at_eof():
        break
      try:
        # read ciphertext
        _rData = await self.reader.read(1)
        # put ciphertext into SSL machine
        self._tlsInBuff.write(_rData)
        # try to fill plaintext buffer
        data += self._tlsObj.read(size)
      except ssl.SSLWantReadError:
        pass

    return data 
Example #10
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def serve_ready(self):
		server = self.server()  # server is a weakref
		if not server:
			return False

		try:
			self.socket.do_handshake()
		except ssl.SSLWantReadError:
			return False
		except (socket.error, OSError, ValueError):
			self.socket.close()
			server.request_embryos.remove(self)
			return False

		self.socket.settimeout(None)
		server.request_embryos.remove(self)
		server.request_queue.put((self.socket, self.address))
		server.handle_request()
		return True 
Example #11
Source File: dns.py    From outis with MIT License 6 votes vote down vote up
def upgradetotls(self):
        """
        upgrade to a tls wrapped connection
        :return: None
        """

        # TODO: newer TLS version?
        # noinspection PyUnresolvedReferences
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        # TODO: PLATFORM STAGECERTIFICATEFILE is not the correct name for this value, move to handler or set a different
        #   variable in TRANSPORT with the same initial value?
        certkeyfile = sanatizefilename(self.handler.platform.options['STAGECERTIFICATEFILE']['Value'])
        context.load_cert_chain(certfile=certkeyfile, keyfile=certkeyfile)
        self.conn = context.wrap_bio(self.recvdataqueue.memorybio, self.senddataqueue.memorybio, server_side=True)
        print_message("Waiting for connection and TLS handshake...")
        while True:
            try:
                self.conn.do_handshake()
                break
            except (ssl.SSLWantReadError, ssl.SSLSyscallError):
                pass
        print_message("Upgrade to TLS done") 
Example #12
Source File: striptls.py    From striptls with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def recv_blocked(self, buflen=8*1024, timeout=None, *args, **kwargs):
        force_first_loop_iteration = True
        end = time.time()+timeout if timeout else 0
        while force_first_loop_iteration or (not timeout or time.time()<end):
            # force one recv otherwise we might not even try to read if timeout is too narrow
            try:
                return self.recv(buflen=buflen, *args, **kwargs)
            except ssl.SSLWantReadError:
                pass
            force_first_loop_iteration = False 
Example #13
Source File: selector_events.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _read_ready(self):
        if self._write_wants_read:
            self._write_wants_read = False
            self._write_ready()

            if self._buffer:
                self._loop.add_writer(self._sock_fd, self._write_ready)

        try:
            data = self._sock.recv(self.max_size)
        except (BlockingIOError, InterruptedError, ssl.SSLWantReadError):
            pass
        except ssl.SSLWantWriteError:
            self._read_wants_write = True
            self._loop.remove_reader(self._sock_fd)
            self._loop.add_writer(self._sock_fd, self._write_ready)
        except Exception as exc:
            self._fatal_error(exc, 'Fatal read error on SSL transport')
        else:
            if data:
                self._protocol.data_received(data)
            else:
                try:
                    if self._loop.get_debug():
                        logger.debug("%r received EOF", self)
                    keep_open = self._protocol.eof_received()
                    if keep_open:
                        logger.warning('returning true from eof_received() '
                                       'has no effect when using ssl')
                finally:
                    self.close() 
Example #14
Source File: slack.py    From fabulous with GNU General Public License v3.0 5 votes vote down vote up
def websocket_safe_read(self):
        """ Returns data if available, otherwise ''. Newlines indicate multiple
            messages
        """
        data = []
        while True:
            try:
                data.append(self.websocket.recv())
            except (SSLError, SSLWantReadError) as e:
                if e.errno == 2:
                    # errno 2 occurs when trying to read or write data, but more
                    # data needs to be received on the underlying TCP transport
                    # before the request can be fulfilled.
                    return data
                raise 
Example #15
Source File: selector_events.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def _read_ready(self):
        if self._write_wants_read:
            self._write_wants_read = False
            self._write_ready()

            if self._buffer:
                self._loop.add_writer(self._sock_fd, self._write_ready)

        try:
            data = self._sock.recv(self.max_size)
        except (BlockingIOError, InterruptedError, ssl.SSLWantReadError):
            pass
        except ssl.SSLWantWriteError:
            self._read_wants_write = True
            self._loop.remove_reader(self._sock_fd)
            self._loop.add_writer(self._sock_fd, self._write_ready)
        except Exception as exc:
            self._fatal_error(exc, 'Fatal read error on SSL transport')
        else:
            if data:
                self._protocol.data_received(data)
            else:
                try:
                    if self._loop.get_debug():
                        logger.debug("%r received EOF", self)
                    keep_open = self._protocol.eof_received()
                    if keep_open:
                        logger.warning('returning true from eof_received() '
                                       'has no effect when using ssl')
                finally:
                    self.close() 
Example #16
Source File: selector_events.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def _write_ready(self):
        if self._read_wants_write:
            self._read_wants_write = False
            self._read_ready()

            if not (self._paused or self._closing):
                self._loop.add_reader(self._sock_fd, self._read_ready)

        if self._buffer:
            try:
                n = self._sock.send(self._buffer)
            except (BlockingIOError, InterruptedError, ssl.SSLWantWriteError):
                n = 0
            except ssl.SSLWantReadError:
                n = 0
                self._loop.remove_writer(self._sock_fd)
                self._write_wants_read = True
            except Exception as exc:
                self._loop.remove_writer(self._sock_fd)
                self._buffer.clear()
                self._fatal_error(exc, 'Fatal write error on SSL transport')
                return

            if n:
                del self._buffer[:n]

        self._maybe_resume_protocol()  # May append to buffer.

        if not self._buffer:
            self._loop.remove_writer(self._sock_fd)
            if self._closing:
                self._call_connection_lost(None) 
Example #17
Source File: socket.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def recv(self, timeout: Optional[float] = None) -> bytes:
    """
    Receives a message from the relay.

    :param timeout: maxiumum number of seconds to await a response, this
      blocks indefinitely if **None**

    :returns: bytes for the message received

    :raises:
      * :class:`stem.ProtocolError` the content from the socket is malformed
      * :class:`stem.SocketClosed` if the socket closes before we receive a complete message
    """

    def wrapped_recv(s: ssl.SSLSocket, sf: BinaryIO) -> bytes:
      if timeout is None:
        return s.recv(1024)
      else:
        s.setblocking(False)
        s.settimeout(timeout)

        try:
          return s.recv(1024)
        except (socket.timeout, ssl.SSLError, ssl.SSLWantReadError):
          return None
        finally:
          s.setblocking(True)

    return self._recv(wrapped_recv) 
Example #18
Source File: test_selector_events.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_on_handshake_reader_retry(self):
        self.loop.set_debug(False)
        self.sslsock.do_handshake.side_effect = ssl.SSLWantReadError
        transport = self.ssl_transport()
        self.loop.assert_reader(1, transport._on_handshake, None) 
Example #19
Source File: test_selector_events.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_read_ready_recv_retry(self):
        self.sslsock.recv.side_effect = ssl.SSLWantReadError
        transport = self._make_one()
        transport._read_ready()
        self.assertTrue(self.sslsock.recv.called)
        self.assertFalse(self.protocol.data_received.called)

        self.sslsock.recv.side_effect = BlockingIOError
        transport._read_ready()
        self.assertFalse(self.protocol.data_received.called)

        self.sslsock.recv.side_effect = InterruptedError
        transport._read_ready()
        self.assertFalse(self.protocol.data_received.called) 
Example #20
Source File: test_selector_events.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_close_not_connected(self):
        self.sslsock.do_handshake.side_effect = ssl.SSLWantReadError
        self.check_close()
        self.assertFalse(self.protocol.connection_made.called)
        self.assertFalse(self.protocol.connection_lost.called) 
Example #21
Source File: sockets.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def _check_socket(self):
        """Check if the connection has been established yet."""
        # Ignore if you're already connected
        if self._connected:
            return True

        # Check if the connection was successful
        ret = self._socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if ret != 0 and ret != errno.EINPROGRESS and ret != errno.EWOULDBLOCK:
            self.disconnect(socket.error(ret, os.strerror(ret)))
            return False
        else:
            # Do SSL handshake if needed
            if isinstance(self._socket, ssl.SSLSocket):
                try:
                    self._socket.do_handshake()
                except socket.error as e:
                    if not isinstance(
                        e, ssl.SSLWantReadError
                    ) and not isinstance(e, ssl.SSLWantReadError):
                        self.disconnect(e)
                    return False

            self._connected = True
            self._logger.debug("Connected")
            return True 
Example #22
Source File: control_channel.py    From pyopenvpn with MIT License 5 votes vote down vote up
def try_handshake(self):
        try:
            self.tls.do_handshake()
            return True
        except ssl.SSLWantReadError:
            pass
        self._sync_tls_out()
        self._sync_tls_in()
        return False 
Example #23
Source File: conftest.py    From wee-slack with MIT License 5 votes vote down vote up
def recv_data(self, control_frame=False):
        if self.returndata:
            return ABNF.OPCODE_TEXT, self.returndata.pop(0)
        else:
            raise ssl.SSLWantReadError() 
Example #24
Source File: selector_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def _read_ready(self):
        if self._conn_lost:
            return
        if self._write_wants_read:
            self._write_wants_read = False
            self._write_ready()

            if self._buffer:
                self._loop._add_writer(self._sock_fd, self._write_ready)

        try:
            data = self._sock.recv(self.max_size)
        except (BlockingIOError, InterruptedError, ssl.SSLWantReadError):
            pass
        except ssl.SSLWantWriteError:
            self._read_wants_write = True
            self._loop._remove_reader(self._sock_fd)
            self._loop._add_writer(self._sock_fd, self._write_ready)
        except Exception as exc:
            self._fatal_error(exc, 'Fatal read error on SSL transport')
        else:
            if data:
                self._protocol.data_received(data)
            else:
                try:
                    if self._loop.get_debug():
                        logger.debug("%r received EOF", self)
                    keep_open = self._protocol.eof_received()
                    if keep_open:
                        logger.warning('returning true from eof_received() '
                                       'has no effect when using ssl')
                finally:
                    self.close() 
Example #25
Source File: selector_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def _write_ready(self):
        if self._conn_lost:
            return
        if self._read_wants_write:
            self._read_wants_write = False
            self._read_ready()

            if not (self._paused or self._closing):
                self._loop._add_reader(self._sock_fd, self._read_ready)

        if self._buffer:
            try:
                n = self._sock.send(self._buffer)
            except (BlockingIOError, InterruptedError, ssl.SSLWantWriteError):
                n = 0
            except ssl.SSLWantReadError:
                n = 0
                self._loop._remove_writer(self._sock_fd)
                self._write_wants_read = True
            except Exception as exc:
                self._loop._remove_writer(self._sock_fd)
                self._buffer.clear()
                self._fatal_error(exc, 'Fatal write error on SSL transport')
                return

            if n:
                del self._buffer[:n]

        self._maybe_resume_protocol()  # May append to buffer.

        if not self._buffer:
            self._loop._remove_writer(self._sock_fd)
            if self._closing:
                self._call_connection_lost(None) 
Example #26
Source File: test_selector_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_on_handshake_reader_retry(self):
        self.loop.set_debug(False)
        self.sslsock.do_handshake.side_effect = ssl.SSLWantReadError
        transport = self.ssl_transport()
        self.loop.assert_reader(1, transport._on_handshake, None) 
Example #27
Source File: test_selector_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_read_ready_recv_retry(self):
        self.sslsock.recv.side_effect = ssl.SSLWantReadError
        transport = self._make_one()
        transport._read_ready()
        self.assertTrue(self.sslsock.recv.called)
        self.assertFalse(self.protocol.data_received.called)

        self.sslsock.recv.side_effect = BlockingIOError
        transport._read_ready()
        self.assertFalse(self.protocol.data_received.called)

        self.sslsock.recv.side_effect = InterruptedError
        transport._read_ready()
        self.assertFalse(self.protocol.data_received.called) 
Example #28
Source File: test_selector_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_write_ready_send_read(self):
        transport = self._make_one()
        transport._buffer = list_to_buffer([b'data'])

        self.loop._remove_writer = mock.Mock()
        self.sslsock.send.side_effect = ssl.SSLWantReadError
        transport._write_ready()
        self.assertFalse(self.protocol.data_received.called)
        self.assertTrue(transport._write_wants_read)
        self.loop._remove_writer.assert_called_with(transport._sock_fd) 
Example #29
Source File: rocket.py    From localslackirc with GNU General Public License v3.0 5 votes vote down vote up
def _read(self, event_id: Optional[str] = None, subs_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
        try:
            _, raw_data = self._websocket.recv_data()
            if raw_data == b'\x03\xe8Normal closure':
                log('Server triggered a disconnect. Reaconnecting')
                raise Exception('Trigger reconnect')
        except SSLWantReadError:
            return None
        except Exception:
            self._connect()
            return None

        try:
            data = json.loads(raw_data)
        except Exception:
            log(f'Failed to decode json: {repr(raw_data)}')
            raise


        # Handle the stupid ping thing directly here
        if data == {'msg': 'ping'}:
            self._send_json({'msg': 'pong'})
            return None

        # Search for results of function calls
        if data is not None and (event_id is not None or subs_id is not None):
            if data.get('msg') == 'result' and data.get('id') == event_id:
                return data.get('result')
            elif data.get('subs') == [subs_id]:
                return data
            else:
                # Not the needed item, append it there so it will be returned by the iterator later
                self._internalevents.append(data)
                return None
        else:
            return data 
Example #30
Source File: ssl_socket.py    From fluxclient with GNU Affero General Public License v3.0 5 votes vote down vote up
def do_handshake(self):
        try:
            super(SSLSocket, self).do_handshake()
        except ssl.SSLWantReadError:
            return 1
        except ssl.SSLWantWriteError:
            return 2

        return self._do_flux_handshake()