#!/usr/bin/env python3 """codesys_info.py - read-only interactive CODESYS V3 online-protocol info client. Talks the CmpBlkDrvTcp online protocol (runtime TCP 11740) to pull device information: it opens an unauthenticated channel and issues standard *read* service requests (e.g. CmpDevice identify), then dumps/parses the replies. READ-ONLY BY DESIGN. It never sends an out-of-order block and never sends a block larger than the granted communication buffer, so it cannot trigger the CmpChannelMgr overflow (CVE-2026-127148) or the in-order overflow. It is an inventory/diagnostic client, not an exploit. Usage: codesys_info.py HOST [--port 11740] # interactive REPL codesys_info.py HOST --identify # one-shot identify codesys_info.py HOST --svc GROUP SERVICE [HEXBODY] codesys_info.py HOST --probe # try identify framing variants REPL commands: open (re)open a channel, show handle/sizes id | identify send CmpDevice identify (group 1, service 1) svc G S [HEXBODY] send an arbitrary read service request probe try a few benign identify framings, report which replies listen [SECS] passively dump incoming frames quit | exit """ import argparse import socket import struct import sys import time import zlib BD_MAGIC = 0xE8170100 OPEN = 0xC3 PKT_BLK, PKT_ACK, PKT_STATUS = 0x01, 0x02, 0x03 META_REPLY = 0x83 L7_MAGIC = 0xCD55 IDENT_BODY_HEX = "01 0c 00 10 00 00 00 00 00 00 00 00 00 00" # tag(0x01, 12 zero-ish bytes) MAX_DATAGRAM = 512 def leb128(value): out = bytearray() while True: b = value & 0x7F value >>= 7 if value: out.append(b | 0x80) else: out.append(b) return bytes(out) def tag(tag_id, value): return leb128(tag_id) + leb128(len(value)) + value def services(group, service, session, body): return struct.pack("H", self.port) + socket.inet_aton(self.host) + struct.pack(">H", self.lport) + socket.inet_aton(self.lip) + b"\x00\x00" + payload) if len(dg) > MAX_DATAGRAM: raise ValueError("datagram %d exceeds %d (read-only cap)" % (len(dg), MAX_DATAGRAM)) self.sock.sendall(struct.pack(" 20 else b"" def open_channel(self, requested=0x001F4000): self._send(meta(OPEN, struct.pack("= 22: self.chan32 = struct.unpack_from(" self.granted - 64: raise RuntimeError("message too large for read-only single-block send") crc = zlib.crc32(msg) & 0xFFFFFFFF order = [layout] if layout else ([self.block_layout] if self.block_layout else ["B", "A"]) last = None for lay in order: self._send(self._first_block(1, msg, len(msg), crc, lay)) r = self._parse_reply(self._read_all(wait)) last = r if r["l7"] or r["data_frames"]: if self.block_layout is None: self.block_layout = lay r["layout"] = lay return r if self.open_channel() != 0: # re-open before trying the next layout break return last def _parse_reply(self, buf): result = {"status_frames": 0, "ack_frames": 0, "data_frames": 0, "l7": [], "raw": []} for dg in self._frames(buf): result["raw"].append(dg) pl = self._l4(dg) op = pl[0] if pl else None if op == PKT_STATUS: result["status_frames"] += 1 elif op == PKT_ACK: result["ack_frames"] += 1 elif op == PKT_BLK: result["data_frames"] += 1 k = dg.find(struct.pack("= 0: result["l7"].append(dg[k:]) return result def parse_device_info(l7_list): """Extract device name / vendor / project / version from a CmpDevice identify reply.""" import re raw = b"".join(l7_list) info = {"utf16": [], "ascii": [], "versions": []} seen = set() for mo in re.finditer(rb"(?:[\x20-\x7e]\x00){3,}", raw): txt = mo.group().decode("utf-16-le").strip() if txt and txt not in seen: seen.add(txt) info["utf16"].append(txt) for m in re.findall(rb"[\x20-\x7e]{5,}", raw): t = m.decode("latin1") if t not in info["ascii"]: info["ascii"].append(t) vers = set() for i in range(0, len(raw) - 3): d, c, b, a = raw[i], raw[i + 1], raw[i + 2], raw[i + 3] if a == 3 and b == 5 and c < 64 and 0 < d < 128: # 3.5.x.x version quad vers.add("%d.%d.%d.%d" % (a, b, c, d)) info["versions"] = sorted(vers) return info def show_reply(r, decode=False): print(" frames: data=%d ack=%d status=%d%s" % (r["data_frames"], r["ack_frames"], r["status_frames"], " layout=%s" % r.get("layout", "") if r.get("layout") else "")) if r["l7"]: if decode: info = parse_device_info(r["l7"]) print(" --- device info ---") if info["utf16"]: labels = ["node/device", "vendor", "project/app"] for i, s in enumerate(info["utf16"]): print(" %-12s: %s" % (labels[i] if i < len(labels) else "string", s)) if info["ascii"]: print(" %-12s: %s" % ("ids", ", ".join(info["ascii"]))) if info["versions"]: print(" %-12s: %s" % ("version", ", ".join(info["versions"]))) else: for l7 in r["l7"]: print(" L7 (%d B): %s" % (len(l7), l7[:160].hex())) ss = ascii_strings(l7) if ss: print(" strings:", ss) elif r["data_frames"] == 0: print(" (no L7 data reply - only channel keepalive/status)") def do_identify(cli, **kw): return cli.service(1, 1, bytes.fromhex(IDENT_BODY_HEX.replace(" ", "")), **kw) def probe(cli): """Try both BENIGN identify header layouts and report which this build speaks.""" for lay in ("B", "A"): if cli.open_channel() != 0: print("[layout %s] re-open failed" % lay) continue r = do_identify(cli, layout=lay) hit = r["data_frames"] > 0 or bool(r["l7"]) print("[layout %s] -> %s" % (lay, "REPLY" if hit else "keepalive only")) if hit: cli.block_layout = lay show_reply(r, decode=True) return True time.sleep(0.3) print("neither benign identify layout produced a data reply") return False def repl(cli): print("codesys_info interactive (read-only). type 'help'.") r = cli.open_channel() print("open: result=%s tok16=%s chan32=%s granted=%s addr_size=%s" % (r, hex(cli.tok16) if cli.tok16 else None, hex(cli.chan32) if cli.chan32 else None, cli.granted, cli.addr_size)) while True: try: line = input("codesys> ").strip() except (EOFError, KeyboardInterrupt): print() break if not line: continue parts = line.split() cmd = parts[0].lower() try: if cmd in ("quit", "exit"): break elif cmd == "help": print(__doc__) elif cmd == "open": r = cli.open_channel() print("open: result=%s tok16=%s chan32=%s granted=%s addr_size=%s" % (r, hex(cli.tok16), hex(cli.chan32), cli.granted, cli.addr_size)) elif cmd in ("id", "identify"): show_reply(do_identify(cli), decode=True) elif cmd == "svc": g, s = int(parts[1], 0), int(parts[2], 0) body = bytes.fromhex("".join(parts[3:])) if len(parts) > 3 else b"" show_reply(cli.service(g, s, body)) elif cmd == "probe": probe(cli) elif cmd == "listen": secs = float(parts[1]) if len(parts) > 1 else 2.0 show_reply(cli._parse_reply(cli._read_all(secs))) else: print("unknown command; 'help' for list") except Exception as e: print("error:", repr(e)) def main(): ap = argparse.ArgumentParser(description="read-only CODESYS V3 info client") ap.add_argument("host") ap.add_argument("--port", type=int, default=11740) ap.add_argument("--timeout", type=float, default=4.0) ap.add_argument("--identify", action="store_true") ap.add_argument("--probe", action="store_true") ap.add_argument("--svc", nargs="+", metavar="G S [HEX]") a = ap.parse_args() cli = Codesys(a.host, a.port, a.timeout) cli.connect() try: if a.identify: r = cli.open_channel() print("open result:", r, "tok16:", hex(cli.tok16) if cli.tok16 else None, "chan32:", hex(cli.chan32) if cli.chan32 else None, "granted:", cli.granted, "addr_size:", cli.addr_size) show_reply(do_identify(cli), decode=True) elif a.probe: cli.open_channel() probe(cli) elif a.svc: cli.open_channel() g, s = int(a.svc[0], 0), int(a.svc[1], 0) body = bytes.fromhex("".join(a.svc[2:])) if len(a.svc) > 2 else b"" show_reply(cli.service(g, s, body)) else: repl(cli) finally: cli.close() if __name__ == "__main__": main()