A stateful firewall remembers connections started from inside, so their replies are let back in while unrequested packets from outside are dropped.
What to build
Simulate a stateful firewall over a log of connection events.
Requirements
- Inside hosts may open connections out only to the ports listed on line 1 (space-separated). Each event line is one of:
out INSIDE OUTSIDE PORT: if PORT is allowed, printallowedand remember the connection (INSIDE, OUTSIDE, PORT); otherwise printblocked.in OUTSIDE INSIDE PORT: printallowedif that exact connection (INSIDE, OUTSIDE, PORT) is remembered, otherwisedropped.close INSIDE OUTSIDE PORT: forget the connection and printclosed, ornot openif it was not remembered.- At the end print
open connections: N.
Input
Line 1: allowed outbound ports. Then one event per line.
Output
One line per event, then the count.
Constraints
Up to 100 events. Addresses and ports contain no spaces.
Example
Input:
443 53
out 10.0.0.5 192.0.2.10 443
in 192.0.2.10 10.0.0.5 443
in 198.51.100.66 10.0.0.5 443
Output:
allowed
allowed
dropped
open connections: 1
Why it works
Keeping a set of open connections, keyed by both ends and the port, is exactly what lets replies in: only a packet that belongs to a conversation the inside started can match a remembered entry.
Examples
443 53 out 10.0.0.5 192.0.2.10 443 in 192.0.2.10 10.0.0.5 443 in 198.51.100.66 10.0.0.5 443
allowed allowed dropped open connections: 1
443 out 10.0.0.5 192.0.2.10 22 in 192.0.2.10 10.0.0.5 22
blocked dropped open connections: 0
Hints
Hint 1
Use a Set of strings such as `${inside}|${outside}|${port}`.
Hint 2
An incoming packet names the outside host first, so build the key in the same order as for out.
Solution
Show one correct solution (try it yourself first)
const allowed = new Set(prompt().trim().split(/\s+/));
const open = new Set();
let line = prompt();
while (line !== null) {
if (line.trim()) {
const [kind, a, b, port] = line.trim().split(/\s+/);
if (kind === "out") {
if (allowed.has(port)) {
open.add(`${a}|${b}|${port}`);
console.log("allowed");
} else console.log("blocked");
} else if (kind === "in") {
console.log(open.has(`${b}|${a}|${port}`) ? "allowed" : "dropped");
} else if (kind === "close") {
console.log(open.delete(`${a}|${b}|${port}`) ? "closed" : "not open");
}
}
line = prompt();
}
console.log(`open connections: ${open.size}`);
▶ Open this solution in the compiler, then press Visualize to watch it run step by step