1

We have a python script which is used by monitoring software to check if a TCP port is open. The script works well in most circumstances, however we have found that certain application aware firewalls actually send an initial syn/ack response to try to get more information to determine the application in use before deciding whether allow or drop the traffic, regardless of whether the rule actually specifies application. This causes the test to pass even if the connection is then dropped.

Is there a way to check if the connection is still open after the initial exchange?

I am aware a simple script like this won't get past application based rules on the firewall, however in our use case the relevant rules are not application based.

def port(self, target, timeout, port):
    remote_server = socket.gethostbyname(target)
    response_time = 0.0
    try:
        start_time = time.time()
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.settimeout(float(timeout))
        conn.connect((remote_server, int(port)))
        conn.close()
        end_time = time.time()
        response_time = (end_time - start_time) * 1000
    except socket.gaierror as e:
        logging.error(e)
        raise
    except socket.timeout as e:
        logging.error(e)
        raise
    except Exception as e:
        logging.error(e)
        raise
mkh500
  • 11
  • 1
  • Can you `conn.send(spam\r\n')` or something, or would that been too unpleasant to your servers? You'll probably get an exception with `ECONNRESET` or something similar in the case where a firewall has accepted then immediately closed the connection, but any real server probably won't hard-drop before at least receiving one buffer. – abarnert Apr 12 '18 at 00:55
  • Possible duplicate of [Python: detect when a socket disconnects for any reason?](https://stackoverflow.com/questions/17386487/python-detect-when-a-socket-disconnects-for-any-reason) – Steffen Ullrich Apr 12 '18 at 04:40

0 Answers0