24 min read · Smart factory

You want to see machine data from a laptop in the office, so you plug the PLC into the same switch as the computers. Then a vendor asks for remote access to fix a program, so you open a port straight through. Everything works. But if a single office machine catches malware, it can see and command the PLC too, because Modbus TCP has no authentication in the protocol itself.
This article turns network segmentation into something you can check. You write the zones, devices and allowed paths as one set of data (JSON), then use that data two ways. The first checks a log for connections that are not on the list. The second generates an example nftables ruleset. The code is TypeScript that Node 24 runs directly, with nothing to install.
The real problem: a flat network where every machine can talk to every other
A plant network that grows one device at a time usually ends up flat: PLCs, HMIs, office computers and vendor machines all in the same segment. The problem is not that anyone means harm. It is that one mistake or one piece of malware on a single machine can spread to the machines on the line, and nobody can say who is talking to which PLC right now.
Consider three hypothetical situations. They are not BT San customer projects.
- A mid-size plastic parts plant: IT connected the PLCs to the office switch so the planning team could see the values. An employee opened an attachment with malware. That machine scanned the network and saw port 502 on every PLC.
- A food plant whose machine vendor asked for remote access: IT opened an RDP port from the internet straight to the HMI to rush a program fix, then forgot to close it. The machine has been hit with password guesses from outside every day, and nobody reads the log.
- A newly connected production reporting system: the team set a temporary any-any firewall rule for testing. The rule stayed for a year. Nobody knows why it is there, and nobody dares delete it for fear of stopping the system.
All three have the same fix: decide who should talk to whom over which port, write it down as a list you can check, and close everything that is not on the list.
Concepts to know: zones, conduits, Purdue levels and the DMZ
- Zone: a group of devices with a similar risk level and role, for example a control zone (PLC, HMI), a SCADA zone, a data gateway zone, and an office zone.
- Conduit: a communication path between zones. It is the place to put rules and to watch. In the example, each allow entry is a conduit.
- Purdue level: a way to layer a plant's systems. Levels 0-1 are field devices and PLCs, level 2 is HMIs and gateways, level 3 is SCADA and the historian, and levels 4-5 are business systems.
- DMZ: a middle zone between the plant and the office. Put data copies, brokers and a jump host here. The office reads from the copy and does not reach into the plant directly.
The terms zones and conduits come from the ISA/IEC 62443 series of standards. This article uses them as a vocabulary only. It does not claim the example conforms to the standard or is certified under it. The actual requirements must be read from the standard itself.
What the public documents say
| Topic | What the document says | Effect on the example |
|---|---|---|
| Firewall and DMZ | CISA advisory AA22-265A recommends a firewall and DMZ between the control system and the points where vendors connect. | A dmz zone sits in between, so neither the office nor vendors reach the plant directly. |
| Remote access | The same advisory has a section on identifying and protecting remote access points. It mentions VPNs and jump boxes (the page we read does not mention MFA). | Remote access goes only through a jump host in the DMZ. MFA is a setting on the gateway and is not in the example code. |
| OT overview | NIST SP 800-82 Rev. 3 gives an overview of OT and common system topologies. | A starting point for reading about architecture. It was not used to confirm any number in the example. |
| Standards series | The ISA page says the 62443 series sets requirements and processes for industrial automation and control systems, covering asset owners, manufacturers, integrators and service providers (the page we read does not define zones and conduits). | Used as a way of thinking. We do not claim the example follows the standard. |
| Ports used | IANA port registry: mbap (Modbus TCP) 502, opcua-tcp 4840, secure-mqtt 8883. | Used as the ports in the allow list. |
| nftables | The nftables wiki shows an inet family table and a chain with policy drop, ct state established,related, and the log statement. | Used as the shape of the generated rules. |
A port is only a convention. Anyone can run any protocol on any port. A rule based on ports is therefore one layer of defense. It does not prove that the traffic that gets through is really Modbus.
Overview of the example
The code is in the folder examples/ot-it-network-segmentation/. It uses only Node 24 built-ins. There is no npm install, no network use, and no call to nft or any command that touches the machine's network. Node runs the .ts files by simply stripping the types, so there are no enums and the .ts extension must be written in imports.
| File | Purpose |
|---|---|
| policy.json | Zones, devices, allowed paths and the main deny rules, as one set of data. |
| flows.json | A hypothetical log and firewall rules, with deliberate violations included. |
| checker.ts | Compares connections against the allow list and says which rule should have blocked them. |
| nft.ts | Generates nftables rule text from policy.json (print only). |
| demo.ts / policy.test.ts | A script that runs the checker, and a node:test test suite. |
| output.txt / ruleset.example.nft.txt | The actual output of the demo and of nft.ts. |
Step 0: survey the devices before writing rules
Rules written from an old diagram will be wrong from day one. Start from the real list of devices: PLCs, HMIs, SCADA, gateways and switches. For each one, record its IP, its zone, who it talks to and over which port. Write down any path that nobody remembers the purpose of, and do not delete it yet, because a machine may depend on it. A safe way to check is to run in watch-only mode (a mirror port, or logging without blocking) for long enough to cover production cycles and different shifts, then compare against the list.
Step 1: write zones and paths as data
One data set says which zones exist (with VLAN and subnet), which devices are in which zone, and which paths are allowed. Each path names the source and destination devices. It does not open a whole zone.
{
"zones": [
{ "name": "internet", "cidr": "203.0.113.0/24", "purdue": "นอกองค์กร", "note": "ตัวอย่างใช้ช่วงเอกสาร 203.0.113.0/24 แทนอินเทอร์เน็ต" },
{ "name": "office", "cidr": "192.168.10.0/24", "purdue": "ระดับ 4-5 (ธุรกิจ)", "vlan": 10 },
{ "name": "dmz", "cidr": "172.16.50.0/24", "purdue": "ระดับ 3.5 (DMZ)", "vlan": 50 },
{ "name": "plant_sup", "cidr": "10.20.1.0/24", "purdue": "ระดับ 2-3 (SCADA, historian)", "vlan": 120 },
{ "name": "plant_ctrl", "cidr": "10.20.2.0/24", "purdue": "ระดับ 0-1 (PLC, HMI)", "vlan": 121 },
{ "name": "edge", "cidr": "10.20.3.0/24", "purdue": "ระดับ 2 (เกตเวย์ข้อมูล)", "vlan": 122 }
],
"assets": [
{ "name": "scada-01", "ip": "10.20.1.10", "zone": "plant_sup" },
{ "name": "historian-01", "ip": "10.20.1.20", "zone": "plant_sup" },
{ "name": "eng-01", "ip": "10.20.1.30", "zone": "plant_sup" },
{ "name": "plc-01", "ip": "10.20.2.11", "zone": "plant_ctrl" },
{ "name": "plc-02", "ip": "10.20.2.12", "zone": "plant_ctrl" },
{ "name": "plc-03", "ip": "10.20.2.13", "zone": "plant_ctrl" },
{ "name": "hmi-01", "ip": "10.20.2.21", "zone": "plant_ctrl" },
{ "name": "opcua-gw-01", "ip": "10.20.3.10", "zone": "edge" },
{ "name": "edge-gw-01", "ip": "10.20.3.11", "zone": "edge" },
{ "name": "mqtt-broker", "ip": "172.16.50.10", "zone": "dmz" },
{ "name": "historian-dmz", "ip": "172.16.50.20", "zone": "dmz" },
{ "name": "jump-01", "ip": "172.16.50.30", "zone": "dmz" },
{ "name": "office-bi", "ip": "192.168.10.50", "zone": "office" }
],
"allow": [
{ "id": "A1", "from": "scada-01", "to": ["plc-01", "plc-02", "plc-03"], "proto": "tcp", "port": 502, "why": "Modbus TCP: SCADA อ่านค่า PLC" },
{ "id": "A2", "from": "hmi-01", "to": ["plc-01"], "proto": "tcp", "port": 502, "why": "HMI หน้าเครื่องคุยกับ PLC ของตัวเอง" },
{ "id": "A3", "from": "scada-01", "to": ["opcua-gw-01"], "proto": "tcp", "port": 4840, "why": "OPC UA ระหว่างโฮสต์ที่ระบุชื่อ" },
{ "id": "A4", "from": "edge-gw-01", "to": ["mqtt-broker"], "proto": "tcp", "port": 8883, "why": "MQTT over TLS จากเกตเวย์ไปโบรกเกอร์ใน DMZ" },
{ "id": "A5", "from": "historian-01", "to": ["historian-dmz"], "proto": "tcp", "port": 5432, "why": "ส่งสำเนาข้อมูล historian ออกไปที่ DMZ (ตัวอย่างใช้พอร์ต PostgreSQL)" },
{ "id": "A6", "from": "office-bi", "to": ["historian-dmz"], "proto": "tcp", "port": 443, "why": "ออฟฟิศอ่านรายงานจากสำเนาใน DMZ เท่านั้น" },
{ "id": "A7", "from": "office", "to": ["jump-01"], "proto": "tcp", "port": 443, "why": "ผู้ใช้รีโมตเข้าทางเกตเวย์ที่บังคับ MFA" },
{ "id": "A8", "from": "jump-01", "to": ["eng-01", "scada-01"], "proto": "tcp", "port": 3389, "why": "จาก jump host เข้าเครื่องวิศวกรรม/SCADA" }
],
"guards": [
{ "id": "G1", "from": "office", "to": "plant_ctrl", "port": null, "msg": "ห้ามออฟฟิศเข้าโซนควบคุมโดยตรง" },
{ "id": "G2", "from": "office", "to": "plant_sup", "port": null, "msg": "ห้ามออฟฟิศเข้าโซน SCADA โดยตรง (รวม SMB 445)" },
{ "id": "G3", "from": "internet", "to": "plant_sup", "port": null, "msg": "ห้ามอินเทอร์เน็ตเข้าโรงงาน" },
{ "id": "G4", "from": "internet", "to": "plant_ctrl", "port": null, "msg": "ห้ามอินเทอร์เน็ตเข้าโรงงาน" }
]
}- Modbus TCP port 502 is allowed only from scada-01 and hmi-01 to the named PLCs, not from any zone.
- OPC UA 4840 between scada-01 and the named opcua-gw-01.
- MQTT over TLS 8883 from the edge gateway to the broker in the DMZ, one direction only. The gateway starts the connection outward.
- Historian data is pushed out to a copy in the DMZ. The office reads from the copy (A6) and does not need to reach the real historian.
- There is no path from the office to a PLC at all. Remote access is only 443 to the jump host, then from the jump host to the engineering machine and SCADA (A7, A8).
- guards are named deny rules. They answer the question: which rule should have stopped this wrong connection?
Step 2: the checker compares the log with the allow list
The checker turns IPs into zones and device names, then asks whether an allow rule matches the source, destination, protocol and port. If none does, and the firewall let the connection through (accept), it is a violation.
export function matchAllow(p: Policy, c: Conn): Allow | undefined {
const s = assetOf(p, c.src), d = assetOf(p, c.dst);
const sZone = zoneOf(p, c.src);
return p.allow.find((a) => a.proto === c.proto && a.port === c.port
&& (a.from === s || a.from === sZone) && d !== undefined && a.to.includes(d));
}export function guardFor(p: Policy, c: Conn): string {
const sz = zoneOf(p, c.src), dz = zoneOf(p, c.dst);
const g = p.guards.find((x) => x.from === sz && x.to === dz && (x.port === null || x.port === c.port));
return g ? `${g.id} (${g.msg})` : "DEFAULT-DROP (ไม่มีกฎอนุญาตที่ตรง)";
}
export function checkConnections(p: Policy, conns: Conn[]): Finding[] {
const out: Finding[] = [];
for (const c of conns) {
if (c.action !== "accept") continue; // already blocked: fine
if (matchAllow(p, c)) continue;
out.push({ kind: "unlisted-flow", where: `${c.t} ${c.src} -> ${c.dst}:${c.port}/${c.proto}`,
detail: `${zoneOf(p, c.src)} -> ${zoneOf(p, c.dst)} ไม่อยู่ใน allow-list`, catchedBy: guardFor(p, c) });
}
return out;
}export function checkRules(rules: FwRule[]): Finding[] {
return rules.filter((r) => r.action === "accept" && (r.src === "any" || r.dst === "any" || r.port === "any"))
.map((r) => ({ kind: "wide-rule", where: r.id, detail: `accept ${r.src} -> ${r.dst} port ${r.port}`,
catchedBy: "ลบกฎนี้ แล้วใช้ default drop + กฎ allow เฉพาะเจาะจง" }));
}Watch out for one thing. A connection that the firewall already blocked (drop) does not count as a violation, but it is still worth reading because it shows that someone is trying. A device that is not on the list is placed in the unknown zone, which is a sign to go and survey more. The example uses a linear search. A real site with thousands of devices should use a device database.
Step 3: generate example nftables rules from the same data
The generated text is not applied to any machine, and the example does not call nft. The code only prints text. Before putting real rules into use, you need to survey the devices, test in watch mode, set a change window and have a way to roll back, as described in the sections below.
export function genNft(p: Policy): string {
const lines = [
"# EXAMPLE ONLY - generated text, never applied. Review, test in monitor-only mode first.",
"table inet seg {",
" chain forward {",
" type filter hook forward priority 0; policy drop;",
" ct state established,related accept",
" ct state invalid drop",
];
for (const a of p.allow) {
const src = p.zones.find((z) => z.name === a.from)?.cidr ?? ip(p, a.from);
const dst = a.to.map((n) => ip(p, n)).join(", ");
lines.push(` ip saddr ${src} ip daddr { ${dst} } ${a.proto} dport ${a.port} accept comment "${a.id}"`);
}
lines.push(' limit rate 5/minute log prefix "seg-drop: "', " counter drop", " }", "}");
return lines.join("\n");
}# EXAMPLE ONLY - generated text, never applied. Review, test in monitor-only mode first.
table inet seg {
chain forward {
type filter hook forward priority 0; policy drop;
ct state established,related accept
ct state invalid drop
ip saddr 10.20.1.10 ip daddr { 10.20.2.11, 10.20.2.12, 10.20.2.13 } tcp dport 502 accept comment "A1"
ip saddr 10.20.2.21 ip daddr { 10.20.2.11 } tcp dport 502 accept comment "A2"
ip saddr 10.20.1.10 ip daddr { 10.20.3.10 } tcp dport 4840 accept comment "A3"
ip saddr 10.20.3.11 ip daddr { 172.16.50.10 } tcp dport 8883 accept comment "A4"
ip saddr 10.20.1.20 ip daddr { 172.16.50.20 } tcp dport 5432 accept comment "A5"
ip saddr 192.168.10.50 ip daddr { 172.16.50.20 } tcp dport 443 accept comment "A6"
ip saddr 192.168.10.0/24 ip daddr { 172.16.50.30 } tcp dport 443 accept comment "A7"
ip saddr 172.16.50.30 ip daddr { 10.20.1.30, 10.20.1.10 } tcp dport 3389 accept comment "A8"
limit rate 5/minute log prefix "seg-drop: "
counter drop
}
}The pattern follows the nftables wiki: a chain with policy drop, accept ct state established,related first, then walk through the allow rules. Last comes a rate-limited log (limit rate), so the log does not flood, and then drop. Every rule has a comment with a code A1-A8 that matches policy.json, so you can trace back to the reason for each path.
- This example uses the forward chain, for a firewall that sits between zones. To protect the machine itself you need a separate input chain.
- There is no NAT, IPv6, ICMP, DNS or NTP. A real deployment must decide each of these one by one.
- Some plant switches support VLANs but have no good ACLs. You then need a separate firewall in between, which depends on the equipment you have.
Actual run: a log with deliberate violations
flows.json has 13 connections. Most are correct, and some were deliberately made wrong, including rule fw-99, which is any-any.
connections in log: 13 (accepted 12)
violations found: 6
[wide-rule] fw-99
accept any -> any port any
ควรถูกกันโดย: ลบกฎนี้ แล้วใช้ default drop + กฎ allow เฉพาะเจาะจง
[unlisted-flow] 09:12:44 192.168.10.77 -> 10.20.2.12:502/tcp
office -> plant_ctrl ไม่อยู่ใน allow-list
ควรถูกกันโดย: G1 (ห้ามออฟฟิศเข้าโซนควบคุมโดยตรง)
[unlisted-flow] 09:30:15 203.0.113.45 -> 10.20.2.21:3389/tcp
internet -> plant_ctrl ไม่อยู่ใน allow-list
ควรถูกกันโดย: G4 (ห้ามอินเทอร์เน็ตเข้าโรงงาน)
[unlisted-flow] 10:05:09 192.168.10.31 -> 10.20.1.30:445/tcp
office -> plant_sup ไม่อยู่ใน allow-list
ควรถูกกันโดย: G2 (ห้ามออฟฟิศเข้าโซน SCADA โดยตรง (รวม SMB 445))
[unlisted-flow] 10:06:00 10.20.2.13 -> 172.16.50.10:1883/tcp
plant_ctrl -> dmz ไม่อยู่ใน allow-list
ควรถูกกันโดย: DEFAULT-DROP (ไม่มีกฎอนุญาตที่ตรง)
[unlisted-flow] 10:08:00 192.168.99.9 -> 10.20.1.10:4840/tcp
unknown -> plant_sup ไม่อยู่ใน allow-list
ควรถูกกันโดย: DEFAULT-DROP (ไม่มีกฎอนุญาตที่ตรง)Reading the result item by item:
- Of 13 connections, 12 passed the firewall. It found 6 violations: 1 rule that is too broad and 5 connections not on the list.
- fw-99 opens any-any, so everything can get through. The checker recommends deleting it and using default drop with specific rules.
- The office laptop 192.168.10.77 talks Modbus to plc-02, which matches guard G1. The attempt that the firewall already blocked (10:07) is not counted.
- A machine from the internet, 203.0.113.45, connected by RDP to the HMI successfully. G4 should have blocked it.
- SMB 445 from the office to the engineering machine should have been blocked by G2. This is a path ransomware uses to spread easily.
- plc-03 connects out to the broker by MQTT on port 1883 (unencrypted). No guard matches, so it points to default drop, which is the reason to close everything by default. This path should be moved to the gateway.
- The source 192.168.99.9 is in no zone at all. It connected to SCADA on port 4840 and hit default drop. You need to find out what machine it is.
Test suite
policy.test.ts has 5 cases. Running node --test policy.test.ts gives 5 passes. They cover the CIDR calculation, valid paths not being flagged, Modbus from the office being flagged by G1, a wrong port or destination being flagged, traffic that was already dropped not being counted, any-any being flagged, and the generated nft containing policy drop, log and every rule code.
test("allowed flows pass, office Modbus is a violation caught by G1", () => {
assert.equal(checkConnections(p, [c("10.20.1.10", "10.20.2.11", 502)]).length, 0);
const f = checkConnections(p, [c("192.168.10.77", "10.20.2.12", 502)]);
assert.equal(f.length, 1);
assert.match(f[0].catchedBy, /^G1/);
});What else to consider in real use
- Real logs: export from the firewall or a flow collector as CSV or JSON, then convert to the Conn format. Read large files as a stream, line by line, and do not load the whole file.
- Inventory: keep devices in a database with an owner and a last-checked date, not in a JSON file nobody maintains.
- IP parsing: the checker accepts only IPv4. The example does not support IPv6.
- Encryption: MQTT should use TLS, and OPC UA has its own security modes. Both are outside the scope of port filtering.
- Old machines that do not support new settings may need a device placed in front of them (see the article on collecting data from legacy machines).
Practices when working in a real plant
- Change window: work while the machines are stopped under the production plan, with the system owner on site.
- Watch period first: log only, or use a mirror port, for a while. See whether any forgotten paths exist, then switch to blocking.
- Do not cut operators out: test that the HMI and control stations still work after every change.
- Emergency procedure: write a rollback method (for example, restore the old ruleset or switch to temporary pass-through mode) that the night shift can read and carry out, and test it.
- One zone at a time: start with the risky zones you already understand. Do not change the whole plant at once.
- Keep policy.json where there is an edit history and an approver.
Hypothetical examples: applying this to the three businesses
A plant that has just started sending machine data to reports
Start with one edge gateway that reads from the machines and sends data out by MQTT on port 8883 to a broker in the DMZ. The office reads reports from the broker or the destination database and does not connect to a PLC. (For the differences between OPC UA, MQTT and Modbus, see the article on the roles of these protocols.)
A plant with vendors who regularly connect remotely
Close RDP from the internet completely. Let vendors in through a jump host in the DMZ with individual accounts, time-limited access and logged sessions. Each vendor can reach only their own machines.
An office that looks after several plants
Use the same policy.json as a template for each site and change only the IPs and the device list. Run the checker on each site's log regularly to catch rules that were quietly added.
Common mistakes, and a checklist
- Writing rules before surveying the devices, then closing a path a machine depends on and stopping the line.
- Drawing zones on paper but leaving an any-any rule in place. The split then has no effect.
- Setting up VLANs with no firewall or ACL between them. Traffic between VLANs still passes through the router as before.
- Opening a whole zone instead of naming the destination devices.
- Connecting remotely straight to the HMI or PLC instead of through a jump host.
- Changing rules in the daytime with no change window and no rollback plan.
- Forgetting to update the policy when a new machine is added, so the new machine cannot connect and someone opens things wide instead.
- Survey the real devices and paths, and compare them with the existing diagram.
- Define zones, subnets and VLANs, with a DMZ between the plant and the office.
- Write allowed paths as data, naming the source and destination devices.
- No direct path from the office to a PLC. Remote access goes through a jump host with multi-step authentication.
- Run the checker against the log regularly. Fix violations, or update the list with a stated reason.
- Watch before blocking, work in a change window, and have a rollback plan.
- Set an owner for the policy, an approver and a review cycle.
Limits of the example: all data and IPs are made up. There is no IPv6, NAT, ICMP, DNS or NTP. No input chain rules were generated, and no rules were applied to any device. The checker looks only at source, destination, protocol and port, and does not inspect protocol content. Segmentation reduces risk but does not make a system fully safe. Use this as a learning example, not as a design for a real plant.
References
- CISA AA22-265A: Control System Defense: Know the Opponent (firewall และ DMZ, จุดรีโมต, VPN, jump box) (accessed 2026-11-21)
- NIST SP 800-82 Rev. 3: Guide to Operational Technology (OT) Security (Sept 2023) (accessed 2026-11-21)
- CISA: ICS Recommended Practices (รายการเอกสาร Defense-in-Depth, Remote Access) (accessed 2026-11-21)
- ISA: ISA/IEC 62443 series of standards (accessed 2026-11-21)
- nftables wiki: Quick reference (tables, chains, policy, log) (accessed 2026-11-21)
- nftables wiki: Simple ruleset for a server (policy drop, ct state) (accessed 2026-11-21)
- IANA: Service Name and Transport Protocol Port Number Registry (502 mbap, 4840 opcua-tcp, 8883 secure-mqtt) (accessed 2026-11-21)




