Python ssl.SSLEOFError() Examples

The following are 18 code examples of ssl.SSLEOFError(). 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: esworker_sns_sqs.py    From MozDef with Mozilla Public License 2.0 6 votes vote down vote up
def run(self):
        while True:
            try:
                records = self.sqs_queue.receive_messages(MaxNumberOfMessages=self.options.prefetch)
                for msg in records:
                    msg_body = msg.body
                    try:
                        # get_body() should be json
                        message_json = json.loads(msg_body)
                        self.on_message(message_json)
                        # delete message from queue
                        msg.delete()
                    except ValueError:
                        logger.error("Invalid message, not JSON <dropping message and continuing>: %r" % msg_body)
                        msg.delete()
                        continue
                time.sleep(self.options.sleep_time)
            except (SSLEOFError, SSLError, socket.error):
                logger.info("Received network related error...reconnecting")
                time.sleep(5)
                self.sqs_queue = connect_sqs(options.region, options.accesskey, options.secretkey, options.taskexchange) 
Example #2
Source File: main.py    From Seth with MIT License 6 votes vote down vote up
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 on run_fake_server")
        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 ValueError:
                print("Something went wrong during the SSL handshake. "
                      "Make sure that /etc/ssl/openssl.cnf contains this "
                      "line in the section [system_default_sect]:")
                print("    MinProtocol = TLSv1.0")
                os._exit(1)
            except (ConnectionResetError, OSError) as e:
                print("Connection lost (%s)" % str(e))
                if "creds" in self.vars:
                    stop_attack() 
Example #3
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 #4
Source File: httpclient.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #5
Source File: ProxyTool.py    From ProxHTTPSProxyMII with MIT License 6 votes vote down vote up
def handle_one_request(self):
        """Catch more exceptions than default

        Intend to catch exceptions on local side
        Exceptions on remote side should be handled in do_*()
        """
        try:
            BaseHTTPRequestHandler.handle_one_request(self)
            return
        except (ConnectionError, FileNotFoundError) as e:
            logger.warning("%03d " % self.reqNum + Fore.RED + "%s %s", self.server_version, e)
        except (ssl.SSLEOFError, ssl.SSLError) as e:
            if hasattr(self, 'url'):
                # Happens after the tunnel is established
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while operating on established local SSL tunnel for [%s]' % (e, self.url))
            else:
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while trying to establish local SSL tunnel for [%s]' % (e, self.path))
        self.close_connection = 1 
Example #6
Source File: tunnelc.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def evt_write(self):
        if not self.is_conn_ok():
            super().evt_write()
            return

        if not self.__over_https:
            super().evt_write()
            return

        if not self.__ssl_handshake_ok:
            self.remove_evt_write(self.fileno)
            self.do_ssl_handshake()

        if not self.__ssl_handshake_ok: return
        try:
            super().evt_write()
        except ssl.SSLWantReadError:
            pass
        except ssl.SSLWantWriteError:
            self.add_evt_write(self.fileno)
        except ssl.SSLEOFError:
            self.delete_handler(self.fileno)
        except ssl.SSLError:
            self.delete_handler(self.fileno) 
Example #7
Source File: striptls.py    From pub with GNU General Public License v2.0 5 votes vote down vote up
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() 
Example #8
Source File: google.py    From pghoard with Apache License 2.0 5 votes vote down vote up
def _retry_on_reset(self, request, action):
        retries = 60
        retry_wait = 2
        while True:
            try:
                return action()
            except (IncompleteRead, HttpError, ssl.SSLEOFError, socket.timeout, OSError, socket.gaierror) as ex:
                # Note that socket.timeout and ssl.SSLEOFError inherit from OSError
                # and the order of handling the errors here needs to be correct
                if not retries:
                    raise
                elif isinstance(ex, (IncompleteRead, socket.timeout, ssl.SSLEOFError, BrokenPipeError)):
                    pass  # just retry with the same sleep amount
                elif isinstance(ex, HttpError):
                    # https://cloud.google.com/storage/docs/json_api/v1/status-codes
                    # https://cloud.google.com/storage/docs/exponential-backoff
                    if ex.resp["status"] not in ("429", "500", "502", "503", "504"):  # pylint: disable=no-member
                        raise
                    retry_wait = min(10.0, max(1.0, retry_wait * 2) + random.random())
                # httplib2 commonly fails with Bad File Descriptor and Connection Reset
                elif isinstance(ex, OSError) and ex.errno not in [errno.EAGAIN, errno.EBADF, errno.ECONNRESET]:
                    raise
                # getaddrinfo sometimes fails with "Name or service not known"
                elif isinstance(ex, socket.gaierror) and ex.errno != socket.EAI_NONAME:
                    raise

                self.log.warning("%s failed: %s (%s), retrying in %.2fs",
                                 action, ex.__class__.__name__, ex, retry_wait)

            # we want to reset the http connection state in case of error
            if request and hasattr(request, "http"):
                request.http.connections.clear()  # reset connection cache

            retries -= 1
            time.sleep(retry_wait) 
Example #9
Source File: test_poplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #10
Source File: ssl_handler.py    From fdslight with GNU General Public License v2.0 5 votes vote down vote up
def evt_write(self):
        if self.__server_side:
            if not self.__ssl_on:
                super().evt_write()
                return
            ''''''
        else:
            if not self.is_conn_ok():
                super().evt_write()
                return
            ''''''

        if not self.__ssl_handshake_ok:
            self.remove_evt_write(self.fileno)
            self.__do_ssl_handshake()

        if not self.__ssl_handshake_ok: return
        try:
            super().evt_write()
        except ssl.SSLWantReadError:
            pass
        except ssl.SSLWantWriteError:
            self.add_evt_write(self.fileno)
        except ssl.SSLEOFError:
            self.delete_handler(self.fileno)
        except ssl.SSLError:
            self.delete_handler(self.fileno) 
Example #11
Source File: test_poplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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() 
Example #12
Source File: test_poplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #13
Source File: ssl_scan.py    From recon-ng-marketplace with GNU General Public License v3.0 5 votes vote down vote up
def module_run(self, hosts):
        cn_regex_pat = r'.*CN=(.+?)(,|$)'
        dn_regex_pat = r'^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$'
        for host in hosts:
            setdefaulttimeout(10)
            ip, port = host.split(':')
            try:
                cert = ssl.get_server_certificate((ip, port), ssl_version=ssl.PROTOCOL_TLS)
            except (ssl.SSLError, ConnectionResetError, ConnectionRefusedError, ssl.SSLEOFError, OSError):
                self.alert(f"This is not a proper HTTPS service: {ip}:{port}")
                continue
            except timeout:
                self.alert(f"Timed out connecting to host {ip}:{port}")
                continue

            x509 = M2Crypto.X509.load_cert_string(cert)
            regex = re.compile(cn_regex_pat)
            commonname = regex.search(x509.get_subject().as_text()).group(1).lower()

            if re.match(dn_regex_pat, commonname):
                self.output(f"Updating ports table for {ip} to include host {commonname}")
                self.query('UPDATE ports SET ip_address=?, host=?, port=?, protocol=? WHERE ip_address=?',
                           (ip, commonname, port, 'tcp', ip))
            else:
                self.alert(f"Not a valid Common Name: {commonname}")

            try:
                subaltname = x509.get_ext('subjectAltName').get_value().split(',')
            except LookupError:
                continue

            for san in subaltname:
                san = san.split(':')[1].lower()
                if re.match(dn_regex_pat, san):
                    self.insert_hosts(host=san) 
Example #14
Source File: striptls.py    From striptls with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
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() 
Example #15
Source File: ProxyTool.py    From ProxHTTPSProxyMII with MIT License 5 votes vote down vote up
def ssl_get_response(self, conn):
        try:
            server_conn = ssl.wrap_socket(conn, cert_reqs=ssl.CERT_REQUIRED, ca_certs="cacert.pem", ssl_version=ssl.PROTOCOL_TLSv1)
            server_conn.sendall(('%s %s HTTP/1.1\r\n' % (self.command, self.path)).encode('ascii'))
            server_conn.sendall(self.headers.as_bytes())
            if self.postdata:
                server_conn.sendall(self.postdata)
            while True:
                data = server_conn.recv(4096)
                if data:
                    self.wfile.write(data)
                else: break
        except (ssl.SSLEOFError, ssl.SSLError) as e:
            logger.error(Fore.RED + Style.BRIGHT + "[SSLError]")
            self.send_error(417, message="Exception %s" % str(e.__class__), explain=str(e)) 
Example #16
Source File: main.py    From Seth with MIT License 4 votes vote down vote up
def enableSSL(self):
        global SNI
        SNI = ""
        def sni_callback(s, hostname, ctx):
            global SNI
            SNI = hostname
            return None
        print("Enable SSL")
        try:
            sslversion = get_ssl_version(self.lsock)
            ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            ctx.load_cert_chain(args.certfile, keyfile=args.keyfile, password=None)
            try:
                ctx.sni_callback = sni_callback
            except AttributeError:
                # This requires python3.7 or higher. But the feature is not
                # that important anyway, so let's just continue.
                pass
            self.lsock = ctx.wrap_socket(
                self.lsock,
                server_side=True,
                do_handshake_on_connect=True,
            )
            if self.rc4:
                try:
                    print("Try to use RC4-SHA cipher")
                    ctx.set_ciphers("RC4-SHA")
                    self.rsock = ctx.wrap_socket(
                        self.rsock,
                        server_hostname=SNI,
                        do_handshake_on_connect=True,
                    )
                except ssl.SSLError:
                    print("Not using RC4-SHA because of SSL Error:", str(e))
                    self.rsock = ctx.wrap_socket(
                        self.rsock,
                        server_hostname=SNI,
                        do_handshake_on_connect=True,
                    )
                except ConnectionResetError as e:
                    print("Unexpected error: %s" % e)
                    os._exit(1)
            else:
                self.rsock = ctx.wrap_socket(
                    self.rsock,
                    server_hostname=SNI,
                    do_handshake_on_connect=True,
                )
        except ConnectionResetError as e:
            print("Connection lost on enableSSL: %s" % e)
        except ssl.SSLEOFError as e:
            print("SSL EOF Error during handshake: %s" % e)
        except AttributeError as e:
            # happens when there is no rsock, i.e. fake_server==True
            print(e)
            pass 
Example #17
Source File: esworker_sqs.py    From MozDef with Mozilla Public License 2.0 4 votes vote down vote up
def run(self):
        while True:
            try:
                records = self.sqs_queue.receive_messages(MaxNumberOfMessages=options.prefetch)
                for msg in records:
                    # msg.id is the id,
                    # get_body() should be json

                    # pre process the message a bit
                    tmp = msg.body
                    try:
                        msgbody = json.loads(tmp)
                    except ValueError:
                        # If Boto wrote to the queue, it might be base64 encoded, so let's decode that
                        try:
                            tmp = base64.b64decode(tmp)
                            msgbody = json.loads(tmp)
                        except Exception as e:
                            logger.error(
                                "Invalid message, not JSON <dropping message and continuing>: %r" % msg.get_body()
                            )
                            msg.delete()
                            continue

                    # If this is still not a dict,
                    # let's just drop the message and move on
                    if type(msgbody) is not dict:
                        logger.debug("Message is not a dictionary, dropping message.")
                        msg.delete()
                        continue

                    event = dict()
                    event = msgbody

                    if "tags" in event:
                        event["tags"].extend([options.taskexchange])
                    else:
                        event["tags"] = [options.taskexchange]

                    # process message
                    self.on_message(event, msg)

                    # delete message from queue
                    msg.delete()
                time.sleep(options.sleep_time)

            except ValueError as e:
                logger.exception("Exception while handling message: %r" % e)
                msg.delete()
            except (SSLEOFError, SSLError, socket.error):
                logger.info("Received network related error...reconnecting")
                time.sleep(5)
                self.sqs_queue = connect_sqs(options.region, options.accesskey, options.secretkey, options.taskexchange) 
Example #18
Source File: esworker_cloudtrail.py    From MozDef with Mozilla Public License 2.0 4 votes vote down vote up
def run(self):
        while True:
            try:
                records = self.sqs_queue.receive_messages(MaxNumberOfMessages=options.prefetch)
                for msg in records:
                    body_message = msg.body
                    event = json.loads(body_message)

                    if not event["Message"]:
                        logger.error("Invalid message format for cloudtrail SQS messages")
                        logger.error("Malformed Message: %r" % body_message)
                        continue

                    if event["Message"] == "CloudTrail validation message.":
                        # We don't care about these messages
                        continue

                    message_json = json.loads(event["Message"])

                    if "s3ObjectKey" not in message_json:
                        logger.error("Invalid message format, expecting an s3ObjectKey in Message")
                        logger.error("Malformed Message: %r" % body_message)
                        continue

                    s3_log_files = message_json["s3ObjectKey"]
                    for log_file in s3_log_files:
                        logger.debug("Downloading and parsing " + log_file)
                        s3_obj = self.s3_client.get_object(Bucket=message_json["s3Bucket"], Key=log_file)
                        events = self.parse_s3_file(s3_obj)
                        for event in events:
                            self.on_message(event)

                    msg.delete()
            except (SSLEOFError, SSLError, socket.error):
                logger.info("Received network related error...reconnecting")
                time.sleep(5)
                self.sqs_queue = connect_sqs(
                    region_name=options.region,
                    aws_access_key_id=options.accesskey,
                    aws_secret_access_key=options.secretkey,
                    task_exchange=options.taskexchange,
                )
            time.sleep(options.sleep_time)