Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
otfabricPublic

About

Siemens S7comm CLI for PLC discovery, identification, memory read/write, block inspection, diagnostics, rack/slot probing, and PCAP decoding over ISO-on-TCP.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

s7commctl

Go Go Reference License CI Codecov Release

A professional Siemens S7 communication CLI for ISO-on-TCP (port 102), implemented in pure Go.

Install

curl -fsSL https://get.otfabric.io/s7commctl | sh
irm https://get.otfabric.io/s7commctl.ps1 | iex

Linux (amd64, arm64, armv7), macOS (Intel, Apple silicon) and Windows (amd64, arm64). The installer verifies the release's SHA-256 checksum, installs per user without sudo (~/.local/bin, Windows %LOCALAPPDATA%\OTFabric\bin), and upgrades in place when run again. Pin a version with OTF_VERSION=x.y.z; for CI, containers and device images use OTF_UNMANAGED_INSTALL=<dir>; all options: otfabric/install. For offline machines, the archives and checksums are on Releases.

Shell completion

Enum flags (e.g. --area, --format, --type, --confirm, --profile) complete with their allowed values, pcap-decode --file with .pcap files.

# bash (needs the bash-completion package)
mkdir -p ~/.local/share/bash-completion/completions
s7commctl completion bash > ~/.local/share/bash-completion/completions/s7commctl

# zsh: a directory on your fpath, then restart the shell
mkdir -p ~/.zsh/completions && s7commctl completion zsh > ~/.zsh/completions/_s7commctl
# and once in ~/.zshrc:  fpath=(~/.zsh/completions $fpath); autoload -U compinit && compinit

# fish
mkdir -p ~/.config/fish/completions && s7commctl completion fish > ~/.config/fish/completions/s7commctl.fish
# PowerShell: add this line to your profile ($PROFILE)
s7commctl completion powershell | Out-String | Invoke-Expression

Table of contents

What it does

s7commctl provides a practical operator and engineering toolset for:

  • Discovery of reachable S7 devices on a subnet
  • Device identification using SZL queries
  • Memory reads and writes (with safety controls)
  • Block listing, block metadata, and block upload
  • Diagnostics (CPU state, protection level, diagnostic buffer)
  • Fingerprinting of negotiated connection capabilities

Requirements implementation status

Current status:

  • Implemented
    • Discovery workflow with TCP/102 probing, rack/slot probing, negotiated PDU/TSAP reporting
    • Identify command using SZL-backed device metadata (CPU/order/module/firmware where exposed)
    • Read for DB, I, Q, M, T, C and extended areas (DATA_RECORD, S7200AO, IEC_COUNTER_200, IEC_TIMER_200); on T and C, --offset is the timer or counter number and --size counts elements of two bytes
    • Typed reads of BOOL, INT, DINT, REAL, STRING; typed writes of INT, DINT, REAL, STRING (current length and characters, within the STRING's declared maximum) and BOOL (one bit, --bit required)
    • Write safety model: explicit --dangerous, a confirmation prompt that names the target and the value, optional --force
    • Block management: list, DB listing, block info, block upload (OB/DB/FB/FC/SFB/SFC support path)
    • Diagnostics: CPU state, protection level, diagnostic buffer
    • Fingerprinting: CPU generation heuristic, PDU, AMQ calling/called, TSAP/rack/slot detection
    • TSAP strategy: manual TSAP, auto rack/slot, brute rack/slot probing
    • Safety controls: public exposure warning, rate limit option, configurable timeout
    • Output modes: human/table, JSON, quiet, hex dump
    • Advanced commands: sniff, pcap-decode, replay scaffold, periodic record
  • Partial
    • Discovery CPU type extraction is not guaranteed on every target/model

Protocol stack:

  • TCP (port 102)
  • TPKT (RFC1006)
  • COTP (ISO 8073)
  • S7comm

For an introduction to S7comm concepts and how the CLI maps onto them, see PROTOCOL.md. For read-only command examples against a single host, see EXAMPLES.md.

Repository layout

  • cmd/s7commctl: Cobra CLI commands
  • internal/app/config: CLI flag/env configuration
  • internal/app/validate: input validation and typed parsing
  • internal/app/output: renderers for json/table/text/hex output
  • main.go: CLI entrypoint
  • go.mod: tool module with dependency on otfabric/go-s7comm

Library code is consumed from the separate otfabric/go-s7comm module.

Requirements

  • Go 1.26+
  • Network connectivity to S7 targets on TCP/102

The library dependency github.com/otfabric/go-s7comm is a regular versioned module requirement in go.mod, which names the version; no local replace or sibling checkout is needed.

Build

make build

Binary output:

  • bin/s7commctl

Quality targets

The project includes a full quality gate target:

make quality

This runs:

  • formatting (fmt), then staticcheck and golangci-lint
  • vet
  • tests
  • coverage

Quality targets execute for this module (.).

Other useful targets:

make fmt
make test
make vet
make lint
make build

Usage

s7commctl --help

Every command and flag is listed in docs/commands.md.

Command tree

s7commctl
├── discover
├── identify
├── read
├── write
├── blocks
├── list
│   ├── blocks
│   ├── db
│   └── areas
├── block
│   ├── info
│   └── upload
├── diagnostic
├── fingerprint
├── probe
│   └── rackslot
├── scan
│   └── read-ranges
├── compare
│   └── read
├── profile
├── record
├── sniff
├── pcap-decode
├── replay
├── completion
└── version

Exit codes

Exit codes follow the organisation table and are listed, with the mapping from older versions, in docs/exitcodes.md: 0 success, 1 a completed operation that reports a non-success, 2 usage, 3 invalid input, 4 connection, 5 timeout, 6 protocol, 9 permission, 10 internal, 130 interrupted.

Note: Cobra is configured so that usage/help is not printed on runtime failures (only on validation errors).

Timeouts

On the commands that connect to one PLC (identify, read, write, blocks, list blocks, list db, block info, block upload, diagnostic, fingerprint, scan read-ranges, record), --timeout (milliseconds, default 5000, S7COMMCTL_TIMEOUT) bounds connecting (TCP, COTP and S7 setup). Each request after it, sending one request and receiving its answer, has a bound of its own, which --request-timeout (milliseconds, S7COMMCTL_REQUEST_TIMEOUT, since v0.12.0) sets. A command of several requests (identify, a read or write larger than the PDU, a block list or upload of several packets) bounds each of them; the pauses of --rate-limit-ms are not requests.

--request-timeout Each request is bounded by
not set (the default) --timeout, as in v0.11.0; nothing when --timeout is 0 or negative
0 nothing: the command waits for the answer until the connection fails or it is interrupted
above 0 that value, whatever --timeout is
negative nothing is sent: a usage error (exit 2) before connecting
  • A request without an answer in time ends the command with exit 5 (timeout) and an error that ends in context deadline exceeded, as a timeout while connecting does, whichever of the two flags set the bound. A read reports status timeout (exit 0, or 1 with --strict-read), and record counts the sample as failed.
  • The connection ends with that request. A write whose answer comes too late may have been carried out by the PLC.
  • --timeout 0, or a negative value, keeps 5 s for connecting. --timeout 0 alone also sets no bound per request, as before v0.11.0; --timeout 2000 --request-timeout 0 bounds connecting by 2 s and sets no bound per request.
  • scan read-ranges bounds each probe read by --timeout in any case (0: 5 s), as before v0.12.0: a smaller --request-timeout ends a probe read earlier, a larger one or 0 does not lengthen it.

profile applies --timeout to each probe and to connecting, and --request-timeout to each request of identify and the block list, with the same rules. It bounds the whole run by twice --timeout (0: 10 s), and that bound applies to the requests too: a --request-timeout above it does not lengthen the run. discover, probe rackslot and compare read have a --timeout of their own, per host, attempt or candidate, and no --request-timeout (docs/commands.md).

Common examples

1. Discover devices

s7commctl discover --cidr 192.168.1.0/24 --format json

Advanced rack/slot probing:

s7commctl discover --cidr 192.168.1.0/24 --rack-min 0 --rack-max 3 --slot-min 0 --slot-max 5

--profile sets the range: quick (rack 0, slot 1-2), standard (rack 0-1, slot 0-3, the default) or full (rack 0-3, slot 0-5). A bound set with --rack-min, --rack-max, --slot-min, --slot-max or their environment variables overrides the profile for that bound only. An empty range, or a rack or slot S7 cannot address, is a usage error.

For script-friendly output (one IP per line), use --quiet or --format quiet; both are supported intentionally.

When the range holds publicly routable addresses, discover prints a warning on stderr (also with --quiet) and scans anyway; --no-exposure-warning (or S7COMMCTL_NO_EXPOSURE_WARNING) suppresses it in authorized environments. The rule is the one of the other commands' target warning: RFC 1918 private, loopback, link-local and IPv6 unique-local addresses are not public.

2. Determine valid rack/slot values

Probe a target for accepted rack/slot combinations (setup accepted = valid):

s7commctl probe rackslot --ip 192.168.1.10 --format table

Strictly confirm combinations using a benign follow-up query (only valid-query counts as valid):

s7commctl probe rackslot --ip 192.168.1.10 --strict

Use a specific confirmation strategy:

s7commctl probe rackslot --ip 192.168.1.10 --confirm szl
s7commctl probe rackslot --ip 192.168.1.10 --confirm cpu-state
s7commctl probe rackslot --ip 192.168.1.10 --confirm any

Retry inconclusive candidates:

s7commctl probe rackslot --ip 192.168.1.10 --strict --retries 3 --retry-delay-ms 200

Stop on first confirmed valid (strict mode):

s7commctl probe rackslot --ip 192.168.1.10 --strict --first-confirmed

Custom rack/slot range and JSON output:

s7commctl probe rackslot --ip 192.168.1.10 --rack-min 0 --rack-max 3 --slot-min 0 --slot-max 7 --format json

Use --summary-only to print only counts, one recommended connection tuple, and interpretation (no table and no full list of combinations). With many candidates, default table output collapses to summary + examples + one-line total (use --show-all for the full list). Interpretation uses “Suggested default tuple” when rack/slot is not discriminated. In strict mode, status is shown as setup-ok (setup accepted, no query) or query-confirmed (setup + follow-up OK). Use --repeat N and --interval-ms to run the probe N times and see variance (e.g. “Setup accepted: 255–256 across 3 runs” and “Results varied across runs; endpoint may be rate-sensitive or unstable”). Use --no-exposure-warning (or env S7COMMCTL_NO_EXPOSURE_WARNING) to suppress the public routable IP warning. Probe JSON uses the same target/request/result envelope as other commands, with snake_case keys in result (setup_accepted, confirmed_by_query, candidates, valid, etc.).

  • valid-connect: setup communication succeeded; follow-up query not attempted or failed.
  • valid-query: setup succeeded and a benign follow-up query (SZL, CPU state, etc.) also succeeded.

Exit code: 0 if at least one valid rack/slot found; 1 if none; >1 for usage or runtime errors.

3. Scan readable ranges

Discover which address ranges in an area return readable data (read-only):

s7commctl scan read-ranges --ip 192.168.1.10 --area I --start 0 --end 256 --probe-size 8
s7commctl scan read-ranges --ip 192.168.1.10 --area DB --db 1 --start 0 --end 1024 --probe-size 32 --format json

Output: consolidated readable/empty/failed/inconclusive spans and optional per-probe table.

4. Compare read across rack/slot candidates

Run the same read on multiple rack/slot pairs and see if results are identical (rack/slot-insensitive):

s7commctl compare read --ip 192.168.1.10 --area DB --db 1 --offset 0 --size 32 --candidates 0/0,0/1,0/2

--timeout bounds each candidate's connect and, separately, its read, so a PLC that goes silent after setup times out instead of blocking.

Table output includes a SameAsBaseline column (baseline/yes/no). Use --repeat and --interval-ms for multiple runs when data may change (e.g. Q area).

5. Profile (capabilities summary)

Summarize setup support, rack/slot, identify, and block list in one run:

s7commctl profile --ip 192.168.1.10
s7commctl profile --ip 192.168.1.10 --format json

6. Identify a PLC

s7commctl identify --ip 192.168.1.10 --rack 0 --slot 1 --format json

Instead of --rack/--slot, device commands can auto-detect rack/slot with --auto-rack-slot (add --brute-rack-slot to try rack 0-3 and slot 0-5), or use explicit TSAPs with --local-tsap and --remote-tsap (decimal or 0x hex; both must be set together). Precedence: explicit TSAP, then auto rack/slot, then manual rack/slot.

s7commctl identify --ip 192.168.1.10 --auto-rack-slot
s7commctl identify --ip 192.168.1.10 --local-tsap 0x0100 --remote-tsap 0x0102

7. Read memory

Read 16 bytes from DB1 offset 0:

s7commctl read --ip 192.168.1.10 --area DB --db 1 --offset 0 --size 16 --format hex

Output includes result status (success, short-read, empty-read, rejected, etc.), requested/returned length, and warnings. Use --strict-read to fail the command when the result is not success.

Read markers and decode as INT values (with --format json, the result includes a decoded array of typed values):

s7commctl read --ip 192.168.1.10 --area M --offset 100 --size 8 --type int

8. Write memory safely

Write requires explicit dangerous mode. Without force, a confirmation prompt on stderr names what is written and where: the length, type and value, the address (DB1.DBB0), area, DB, offset (and bit), the IP and port, and the rack and slot or TSAPs. Values can come from S7COMMCTL_* variables, so read it before you type yes.

s7commctl write --ip 192.168.1.10 --area DB --db 1 --offset 0 --type int --value 123 --dangerous
  • --type bool --bit N (N 0-7) writes one bit, the bit address offset·8+N: --area Q --offset 0 --bit 3 sets Q0.3 and leaves the other seven bits of QB0 unchanged. The success line names the bit (DB1.DBX4.3, Q0.3).
  • --type bool without --bit is a usage error (exit 2) before the prompt and before connecting. To write a whole byte, use --type raw with one octet (--value 01); there is no --type byte.
  • --type string first reads byte 0 of the STRING at --offset, the maximum length the PLC program declares, then writes the current length (byte 1) and the characters from --offset+1 and leaves byte 0 unchanged. A value longer than that maximum is refused with exit 2 and nothing is written; a value longer than 254 octets (an S7 STRING's limit) is refused with exit 2 before the prompt and before connecting. When byte 0 cannot be read, the write stops with that error and its exit code (4 when the connection is lost, 6 when the PLC refuses the read) and nothing is written.
  • Byte writes are labelled as bytes in the success line: DB1.DBB0, MB100, QB4.

Non-interactive (automation):

s7commctl write --ip 192.168.1.10 --area DB --db 1 --offset 0 --type int --value 123 --dangerous --force

9. List blocks

s7commctl list blocks --ip 192.168.1.10 --format table
s7commctl list db --ip 192.168.1.10 --format json

The top-level blocks command is an alias for list blocks (same behavior).

With --format json, list blocks and diagnostic print a structured error envelope (target, request, error with code and message) to stdout on failure.

10. Block metadata and upload

s7commctl block info --ip 192.168.1.10 --type DB --number 1 --format json
s7commctl block upload --ip 192.168.1.10 --type DB --number 1 --format json

11. Diagnostics

s7commctl diagnostic --ip 192.168.1.10 --format table

Includes:

  • CPU state
  • protection level
  • diagnostic buffer

12. Fingerprint

s7commctl fingerprint --ip 192.168.1.10 --format json

13. Record periodic reads

Record DB snapshots every second to JSONL:

s7commctl record --ip 192.168.1.10 --area DB --db 1 --offset 0 --size 8 --every-ms 1000 --count 60 --output samples.jsonl

Hex-line output mode:

s7commctl record --ip 192.168.1.10 --area M --offset 100 --size 4 --format hex --output samples.hex

A sample fails when its status is not success; its line is written like any other. The summary reads Recorded N samples (M failed) to <file>, and the command exits 1 when a sample failed. Nothing reconnects: after --max-failures consecutive samples that failed with transport-error or timeout (default 5; 0 never stops), record stops, prints the summary, says on stderr that the connection was lost and exits 4 (transport) or 5 (timeout), the code of the last sample. An interrupt (Ctrl-C) ends it with 0 and no summary.

14. Passive sniff decode

Listen for raw TPKT streams on the --listen address and decode frames (single-client mode: the first client that connects, one connection). The default 127.0.0.1:15102 accepts local clients only; --listen :15102 listens on every interface, without authentication, for a feed from another host. See SECURITY.md.

s7commctl sniff --format jsonl

15. Offline pcap decode

Best-effort decode of S7-over-TCP frames from a pcap capture (no full TCP stream reassembly: no sequence numbers, retransmissions or reordering). Packets are decoded as they are read, one at a time, so memory follows the largest packet rather than the file. Each packet's TCP payload ends where its IPv4 total length says (Ethernet padding and trailers are not stream data); IP fragments are skipped. Frames decoded before a damaged packet are printed before the error:

s7commctl pcap-decode --file capture.pcap --port 102 --format text

16. Replay server scaffold

Run a deterministic replay endpoint with scripted response frames (hex TPKT, one per line). Single-client mode: the first client that connects, one TCP connection; one response per scripted line until the connection closes. The default 127.0.0.1:1102 accepts local clients only; --listen :1102 listens on every interface, without authentication, for a client on another host. An interrupt during --delay-ms ends the command at once with exit 130.

s7commctl replay --script replay.hex --format jsonl

Reaching the PLC: proxy and source address

Every command that connects to a PLC (identify, read, write, list, block, blocks, diagnostic, fingerprint, scan, record, probe rackslot, compare read, profile and discover) accepts two flags for how the TCP connection is opened:

  • --proxy socks5://host:port connects through a SOCKS5 proxy (RFC 1928, no authentication), for example an SSH jump host into the plant network (ssh -D 1080 jumphost). socks5h:// sends host names to the proxy to resolve. Proxy credentials are not supported.
  • --source-addr <ip> connects from that local address, on a host with several networks (an OT and an office interface, say).

With both, the connection to the proxy is made from the source address.

ssh -N -D 1080 engineer@jumphost &
s7commctl identify --ip 10.20.0.15 --proxy socks5://127.0.0.1:1080
s7commctl discover --cidr 10.20.0.0/24 --proxy socks5://127.0.0.1:1080
s7commctl read --ip 192.168.0.10 --source-addr 192.168.0.2 --area DB --db 1 --size 4

An invalid value is a usage error (exit 2). A proxy that refuses the connection is a connection failure; the error names the proxy and its reply, for example socks5: connection not allowed by ruleset.

Configuration via environment variables

Most command flags support S7COMMCTL_* environment variables, for example:

  • S7COMMCTL_IP
  • S7COMMCTL_PORT
  • S7COMMCTL_RACK
  • S7COMMCTL_SLOT
  • S7COMMCTL_TIMEOUT
  • S7COMMCTL_REQUEST_TIMEOUT (--request-timeout)
  • S7COMMCTL_AUTO_RACK_SLOT (--auto-rack-slot)
  • S7COMMCTL_BRUTE_RACK_SLOT (--brute-rack-slot)
  • S7COMMCTL_LOCAL_TSAP (--local-tsap)
  • S7COMMCTL_REMOTE_TSAP (--remote-tsap)
  • S7COMMCTL_PROXY (--proxy)
  • S7COMMCTL_SOURCE_ADDR (--source-addr)

Example:

export S7COMMCTL_IP=192.168.1.10
export S7COMMCTL_RACK=0
export S7COMMCTL_SLOT=1
s7commctl identify

Safety model

  • Read operations are default-safe
  • Write operations require --dangerous
  • Interactive confirmation is required unless --force is set; the prompt names the target, the address and the value
  • --type bool writes one bit and requires --bit; --type string reads the STRING's declared maximum first and refuses a longer value
  • Text the PLC supplies (CPU type, order number, module name, firmware) is printed with non-printable characters escaped as \xNN in text, table and --quiet output, so the output shows them rather than passing them on; JSON escapes them as JSON does
  • fingerprint and diagnostic report a protection level they could not read as unknown (null in JSON, with protection_error), never as "No Protection"
  • sniff and replay listen on 127.0.0.1 unless --listen names another address
  • Limits and the sniff/replay listeners: SECURITY.md

Always validate addressing and scope in a non-production or controlled maintenance window before performing writes.

Testing

Run all tests:

go test ./...

Current tests focus on:

  • command wiring/smoke coverage
  • config/env flag loading
  • input parsing and validation
  • output formatting
  • write safety confirmation helpers
  • pcap/replay/frame parsing helpers

Note: low-level protocol codec coverage is primarily maintained in the otfabric/go-s7comm library module.

CI

Every pull request runs .github/workflows/pr.yml, which calls:

  • ci.yml, unless the change is documentation only: the organisation's shared go-ci.yml (lint, static analysis, tests with the race detector on Go 1.26 and 1.27, a total coverage gate, fuzzing, govulncheck) and a per-package coverage floor (make coverage-pkg-check)
  • docs.yml: docsync (the documents against the code) and the engineering policy check

and gates them in one required check. docs.yml also runs on every push to main. make check runs the same checks locally. Releases are built by release.yml (the shared go-binary-release.yml).

Output schema conventions (JSON)

Commands that operate on a single target use a consistent envelope when --format json is set:

  • target: ip, port (connection endpoint only).
  • request: includes connection_mode (rack_slot | auto_rack_slot | explicit_tsap) plus mode-specific fields (rack/slot or local_tsap/remote_tsap) and command-specific params (e.g. area, offset, type, number). For read, request has connection (when present) and address (area, db, offset, size). For compare read, request holds the read params and candidates.
  • result: operation outcome (device info, fingerprint, blocks, read data, etc.). Effective/detected rack/slot appear in result when relevant (e.g. fingerprint).

Diagnostic and list blocks print the same envelope with an error object (code, message) instead of result when they fail; other commands print errors on stderr and nothing on stdout (docs/json-output.md). Discover intentionally returns a raw array of discovered devices (one object per device); it is a multi-result query, not a single-target envelope. List blocks returns an array of blocks; single-target commands use the envelope above. Write request may include value_truncated: true when the value is long; the value field is then a 128-character preview. With --bit the request has bit; result.written counts the octets written, or 1 for a bit write.

Notes and limitations

  • Some PLC families expose different SZL field layouts; identify/fingerprint values can vary by model/firmware.
  • Block upload behavior is dependent on PLC capabilities and protection levels.
  • Replay is a scaffold framework for deterministic test workflows and is not a full PLC simulator.

License

This project is licensed under the MIT License. See LICENSE.

For contributing and security reporting, see CONTRIBUTING.md and SECURITY.md.

About

Siemens S7comm CLI for PLC discovery, identification, memory read/write, block inspection, diagnostics, rack/slot probing, and PCAP decoding over ISO-on-TCP.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages