PLC logic: IL emulation
A boiler room control controller (PLC) is managed over Modbus/TCP. After an incident you were given the PLC program (plc_program.il, IEC 61131-3 Instruction List) and the traffic (modbus.pcap) of three computers (an HMI, an engineering workstation and a historian) with the PLC, both in plc.zip. Before the recording ended, the sniffer was disconnected: the final values of the PLC output registers HR100..HR107 were never read anywhere. Recover them by emulating the PLC.
PLC memory (everything is 0 at the start): coils %MX0..%MX15 (Modbus coil address n), holding registers %MW0..%MW127 (HR address n), internal bits %VX0..7, internal words %VW0..15 (retained between scans), timers T0..T3. All words are 16-bit unsigned (excess bits are discarded).
Instructions: LD/LDN x (CR = x / logical NOT x), ST x (for a bit CR≠0, for a word CR), STN, S/R x (if CR≠0, sets the bit to 1/0), AND/OR/XOR (bitwise, 16 bits; ANDN/ORN/XORN — with the logical NOT of the operand: 0 → 1, non-zero → 0), ADD/SUB/MUL/DIV/MOD (wrapped to 16 bits; division by zero/MOD → 0), SHL/SHR n, GT/GE/LT/LE/EQ/NE x (CR = 1 or 0, unsigned), JMP/JMPC/JMPCN LBL (forward only; JMPC — CR≠0, JMPCN — CR=0), TON Tn, PT (input = CR: if CR≠0 the counter of Tn is increased by 1 (not exceeding PT), otherwise 0; the result is CR = counter ≥ PT). Operand: %XXn, a decimal number or 16#HEX. Comments (* ... *). The program runs once from top to bottom on each scan; bit operands are read as 0/1.
Timing model. After each successful write (FC05, FC06, FC16) is accepted, the PLC performs exactly one scan: first the write is applied to memory, then the program runs. Writes whose response is an exception (funksiya | 0x80) do not change memory and do not trigger a scan; reads (FC03) do not scan either. FC16 is a single write (one scan). The order of writes is by the time of the request packets (combined across the three connections). Modbus/TCP: MBAP (TID, PID=0, length, unit) + PDU; a request and response are paired by TID. The traffic contains TCP retransmissions: duplicate segments must not be counted twice.
Task: apply all the writes to the program and find the final values of HR100..HR107 (eight 16-bit words). If you write the low byte of each word in turn as 2-digit lowercase hex (the high byte is ignored), you get 16 hex characters: the flag is BAYROQ{PLC_MANTIQ_<16 hex>}. The intermediate reads (HR100..107) in the pcap can be used to check your emulator.