Project: TCP Connectivity Checker
"Is the database port reachable from the web tier?" "Did the firewall change close 3389 everywhere?" "Which of our lab servers still answer on Telnet?" These are connectivity questions, and the tool that answers them is a TCP connect checker: for each host and port, try to complete the three-way handshake and report open, closed or filtered. It is the simplest network tool there is and the core of every port scanner, which is why it comes with rules.
Scope. Checking ports on systems you do not own or administer, without written permission, is illegal in many jurisdictions and is treated as hostile by every network operator (Authorization, Scope and Rules of Engagement). This project tests a simulated network in the browser and listeners it starts itself on 127.0.0.1 in the sandbox. The scope guard is part of the tool, not a comment.
How a connect check works
connect() sends a SYN. A listening port answers SYN-ACK, the client completes the handshake with ACK, and the port is open. A host with nothing listening answers RST: closed. If nothing comes back before the timeout (a firewall dropped the SYN, or the host is down), the port is filtered. Step through the handshake and its timing in the lab:
A checker only needs the first three segments; it closes the connection immediately after. The TCP handshake lesson covers the state machine in detail.
Version 1: a pure core against a simulated network
The design follows Designing a Small Security Tool: a pure check() that takes a connect function, so the same code runs against a simulated network in tests and against real sockets in the sandbox. The simulated lab network answers like a real one: open ports accept, closed ports refuse, a firewalled host never answers. Addresses are from the lab range 10.10.0.0/24.
import ipaddress, json
SCOPE = [ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.10.0.0/24")]
# The simulated network: host -> {port: behaviour}; anything missing is refused, firewalled hosts drop.
LAB = {
"10.10.0.10": {"ports": {22: "open", 80: "open", 443: "open"}},
"10.10.0.20": {"ports": {22: "open", 23: "open", 3306: "open"}},
"10.10.0.30": {"firewall": "drop", "ports": {443: "open"}},
}
def simulated_connect(host, port, timeout):
h = LAB.get(host)
if h is None:
raise TimeoutError("no route / no answer")
if h.get("firewall") == "drop" and port not in h["ports"]:
raise TimeoutError("no answer")
if h["ports"].get(port) == "open":
return True
raise ConnectionRefusedError("RST")
def in_scope(host):
try:
return any(ipaddress.ip_address(host) in n for n in SCOPE)
except ValueError:
return False
def check(targets, ports, connect, timeout=1.0, max_checks=256):
results = []
for host in targets:
if not in_scope(host):
results.append({"host": host, "port": None, "state": "refused-out-of-scope"})
continue
for port in ports:
if len(results) >= max_checks:
raise ValueError("too many checks; narrow the scope")
try:
connect(host, port, timeout)
state = "open"
except ConnectionRefusedError:
state = "closed"
except TimeoutError:
state = "filtered"
results.append({"host": host, "port": port, "state": state})
return results
results = check(["10.10.0.10", "10.10.0.20", "10.10.0.30", "192.0.2.10"],
[22, 23, 443, 3306], simulated_connect)
for r in results:
print(json.dumps(r))
# A policy check on top: Telnet and database ports must not be reachable from this zone
FORBIDDEN = {23: "telnet", 3306: "mysql"}
for r in results:
if r["state"] == "open" and r["port"] in FORBIDDEN:
print(f"POLICY {r['host']}:{r['port']} ({FORBIDDEN[r['port']]}) reachable"){"host": "10.10.0.10", "port": 22, "state": "open"}
{"host": "10.10.0.10", "port": 23, "state": "closed"}
{"host": "10.10.0.10", "port": 443, "state": "open"}
{"host": "10.10.0.10", "port": 3306, "state": "closed"}
{"host": "10.10.0.20", "port": 22, "state": "open"}
{"host": "10.10.0.20", "port": 23, "state": "open"}
{"host": "10.10.0.20", "port": 443, "state": "closed"}
{"host": "10.10.0.20", "port": 3306, "state": "open"}
{"host": "10.10.0.30", "port": 22, "state": "filtered"}
{"host": "10.10.0.30", "port": 23, "state": "filtered"}
{"host": "10.10.0.30", "port": 443, "state": "open"}
{"host": "10.10.0.30", "port": 3306, "state": "filtered"}
{"host": "192.0.2.10", "port": null, "state": "refused-out-of-scope"}
POLICY 10.10.0.20:23 (telnet) reachable
POLICY 10.10.0.20:3306 (mysql) reachable
The twelve checks show all three states. 10.10.0.30 is behind a dropping firewall: only 443 answers, everything else times out (filtered), which tells the operator a firewall is there. The out-of-scope address is refused before any connection is attempted. The policy step turns raw reachability into findings: Telnet and MySQL reachable on 10.10.0.20.
Version 2: real sockets on loopback
The same core, with socket.create_connection as the connect function, runs in your sandbox against listeners the session starts: an HTTP server on 8000 and two Ncat listeners on 9000 and 9001. Port 9002 has nothing listening. Nmap's connect scan (-sT) gives the reference answer.
python3 -m http.server 8000 --bind 127.0.0.1 >http.log 2>&1 &
ncat -lk 127.0.0.1 9000 >/dev/null 2>&1 &
ncat -lk 127.0.0.1 9001 >/dev/null 2>&1 &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
for i in $(seq 50); do ncat -z 127.0.0.1 9001 && break; sleep 0.1; done
cat > tcpcheck.py <<'PY'
import argparse, ipaddress, json, socket, sys
SCOPE = [ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.10.0.0/24")]
def in_scope(host):
try:
return any(ipaddress.ip_address(host) in n for n in SCOPE)
except ValueError:
return False
def real_connect(host, port, timeout):
with socket.create_connection((host, port), timeout=timeout):
return True
def check(host, port, connect, timeout):
try:
connect(host, port, timeout)
return "open"
except ConnectionRefusedError:
return "closed"
except (TimeoutError, socket.timeout):
return "filtered"
def main(argv=None):
p = argparse.ArgumentParser(prog="tcpcheck")
p.add_argument("host")
p.add_argument("ports", type=lambda s: [int(x) for x in s.split(",")])
p.add_argument("--timeout", type=float, default=1.0)
a = p.parse_args(argv)
if not in_scope(a.host):
print(f"tcpcheck: {a.host} is outside the authorized scope", file=sys.stderr)
return 2
states = {port: check(a.host, port, real_connect, a.timeout) for port in a.ports}
for port, state in states.items():
print(json.dumps({"host": a.host, "port": port, "state": state}))
return 1 if any(s == "open" for s in states.values()) else 0
if __name__ == "__main__":
sys.exit(main())
PY
python3 tcpcheck.py 127.0.0.1 8000,9000,9001,9002; echo "exit $?"
python3 tcpcheck.py 192.0.2.10 80; echo "exit $?"
echo "== reference: nmap connect scan"
nmap -sT -p 8000,9000,9001,9002 127.0.0.1 | grep -E '^[0-9]+/tcp'
kill %1 %2 %3{"host": "127.0.0.1", "port": 8000, "state": "open"}
{"host": "127.0.0.1", "port": 9000, "state": "open"}
{"host": "127.0.0.1", "port": 9001, "state": "open"}
{"host": "127.0.0.1", "port": 9002, "state": "closed"}
exit 1
tcpcheck: 192.0.2.10 is outside the authorized scope
exit 2
== reference: nmap connect scan
8000/tcp open http-alt
9000/tcp open cslistener
9001/tcp open tor-orport
9002/tcp closed dynamid
The tool and Nmap agree. The exit code 1 means "found open ports", which lets a CI job assert that a port is closed (exit 0) after a firewall change.
How defenders detect connectivity checks
- Many connections, little data: a source that opens and immediately closes connections to many ports or hosts. Firewall and NetFlow logs show it as many short flows; on the target,
ss -tanshows connections inTIME_WAITfrom one source. - IDS signatures and thresholds: Suricata/Snort flag "N SYNs to M distinct ports in T seconds" (Network Security). Connect checks are louder than SYN scans because they complete the handshake, so the application often logs them too (many HTTP servers log nothing for a bare connect, but OpenSSH logs the early disconnect, with wording that depends on its version).
- Honeyports: a listener on a port nothing legitimate uses; any connection to it is an alert.
How to run it responsibly (prevention)
- Scope guard in code, allowlist only, addresses not names.
- Rate limits and small batches, so even an authorized check does not look like a flood; record the start, end and source address in a run log for the operators.
- Short timeouts with an upper bound on the number of checks.
- Tell the owners first (change ticket, rules of engagement), so a SOC alert can be matched to your run.
Pitfalls
- "Filtered" is ambiguous: dropped by a firewall, host down, packet loss or a timeout that was too short. Re-test before reporting.
- Open is not vulnerable: an open port is a fact for the inventory; vulnerability needs the service and version.
- Local firewalls can lie: some return RST for filtered ports (
reject with tcp reset), which looks like "closed". - Resolving names in the tool reintroduces the scope gap discussed in argparse.
Practice
1. Add a host 10.10.0.40 to LAB with "firewall": "reject" that answers RST for everything except 22. What do the results look like, and how do they differ from 10.10.0.30?
Make simulated_connect raise ConnectionRefusedError for non-listed ports when the firewall rejects. Every port but 22 shows closed, so you can't tell a reject firewall from a host with nothing listening, whereas the drop firewall on .30 shows filtered. Reject gives faster failures to legitimate clients; drop gives scanners less information.
2. Write a test that runs check() with a fake connect that always raises TimeoutError. What should every result be?
filtered for every in-scope port, and refused-out-of-scope for addresses outside the scope (which must not call connect at all: make the fake count calls and assert it was not called for them).
3. A colleague wants to add --targets 10.10.0.0/24 (a whole network). Which limit in the code protects against /8 by mistake?
max_checks (256 in version 1) raises an error before the run grows; validate the prefix length too (for example refuse anything shorter than /24) and expand the network with ipaddress.ip_network(...).hosts() only after the scope check.
Test yourself
A connect check gets no answer before the timeout. Which state does it report?
- open
- closed
- filtered
- refused-out-of-scope
Why does check() take a connect function as a parameter?
- To run faster
- So the same code can be tested against a simulated network and run against real sockets
- Because sockets need it
- To hide errors
In the sandbox run, which port was closed?
- 8000
- 9000
- 9001
- 9002
Why are connect checks easier to detect than half-open SYN scans?
- They use UDP
- They complete the handshake, so the application and connection logs can record them
- They are encrypted
- They use more ports