From a919f406ce5c2a6fee3a359daa744083ea549d9b Mon Sep 17 00:00:00 2001 From: bartvanbos Date: Tue, 1 Dec 2026 00:19:18 +0100 Subject: [PATCH] feat: allow-list flags for go-profinet's allow-list; exit code 12 policy_denied (v0.23.0) Expose go-profinet v0.28.0's controller.Allowlist and the dcp.SetAllowlist the controller derives from it (engineering policy 1.7, SEC-R02; maintainer decision 14 of 2026-11-30): --allow-operation (operation classes), --allow-read-index / --allow-write-index (record index ranges), --allow-dcp-block (DCP Set blocks), --allow-list-file (JSON) and --allow-nothing. No flag: no allow-list, unchanged behaviour. An empty list allows nothing and only --allow-nothing makes one. A refusal (profinet.ErrNotAllowed) exits 12 with kind and code policy_denied; the JSON error adds reason, operation, record or block, and target. Co-Authored-By: Claude Opus 5.5 --- README.md | 55 ++++ RELEASE.md | 48 ++++ SECURITY.md | 4 + cmd/allow.go | 505 +++++++++++++++++++++++++++++++++ cmd/allow_test.go | 425 +++++++++++++++++++++++++++ cmd/ar.go | 2 +- cmd/common.go | 10 +- cmd/lldp.go | 2 +- cmd/records.go | 4 +- cmd/roadmap.go | 2 +- cmd/root.go | 14 +- docs/exitcodes.md | 10 +- docs/json-output.md | 2 +- e2e/e2e_test.go | 44 +++ internal/errs/errs.go | 52 +++- internal/errs/errs_test.go | 1 + internal/runner/runner.go | 35 ++- internal/runner/runner_test.go | 21 ++ scripts/examples.sh | 2 + 19 files changed, 1222 insertions(+), 16 deletions(-) create mode 100644 cmd/allow.go create mode 100644 cmd/allow_test.go diff --git a/README.md b/README.md index 867f245..4f8f489 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,60 @@ Every command has `--help`. A device is selected by `--station NAME` (resolved w | `--timeout` | `PROFINETCTL_TIMEOUT` | `5s` | time limit of one request | | `--pcap FILE` | | | record every frame sent and received (open it with Wireshark) | | `--debug` | | | go-profinet's diagnostics on stderr, and the causes of an error | +| `--allow-operation OP`, `--allow-read-index`, `--allow-write-index`, `--allow-dcp-block`, `--allow-list-file FILE`, `--allow-nothing` | | | restrict what profinetctl may send: see [Allow-list](#allow-list) | + +### Allow-list + +The `--allow-*` flags restrict what profinetctl may send, with go-profinet's own allow-list (`controller.Allowlist`, and for the DCP Sets `dcp.SetAllowlist`; go-profinet's [SECURITY.md](https://github.com/otfabric/go-profinet/blob/main/SECURITY.md), "What a controller may send"). It is a local measure, checked before anything is sent: it authenticates nobody and decides nothing about the device; it keeps a script or an operator from sending what they should not. Without any of these flags there is no allow-list, and profinetctl sends what it sent before. + +| Flag | Meaning | +|------|---------| +| `--allow-operation OP` | the classes of operation allowed (repeatable, or comma-separated), as go-profinet names them: `connect` (the Connect of an AR: an IOCAR or a device access AR), `read` (a record in an AR), `read-implicit` (a record without an AR), `write` (each record write), `prm-begin`, `prm-end` (the end of a parameterization), `other-control` (any other Control but Release), `dcp-set` (a DCP Set) | +| `--allow-read-index I` | restricts `read` and `read-implicit` to this record index or range `FIRST-LAST` (decimal or `0x` hex, repeatable); without it, every index of an allowed read | +| `--allow-write-index I` | restricts `write` likewise | +| `--allow-dcp-block BLOCK` | restricts `dcp-set` to this block (repeatable): go-profinet's name of it, case-insensitive (`Device/NameOfStation`, `IP/Parameter`, `IP/FullSuite`, `Control/Signal`, `Control/ResetToFactory`, `DHCP/61`, ...), or `OPTION/SUBOPTION` in numbers (`2/2`); without it, every block of an allowed Set | +| `--allow-list-file FILE` | the allow-list as a JSON file with the same fields, instead of the flags above: `{"operations": ["read-implicit", "dcp-set"], "read_indexes": [{"first": "0xAFF0", "last": "0xAFFF"}], "write_indexes": [{"first": 16}], "dcp_blocks": ["Device/NameOfStation"]}`; an index is a number or a string as the flags take it, `last` defaults to `first`, an unknown field is an error | +| `--allow-nothing` | an allow-list that allows nothing: every request it covers is refused | + +- **An empty allow-list allows nothing** (go-profinet's rule). Only `--allow-nothing` makes one, and it takes no other allow-list flag. A file that names no operation is refused (exit 3), and so is an index range or a DCP block whose operation the list does not allow (`--allow-read-index` without `read` or `read-implicit`: exit 2, in a file exit 3): a mistake cannot turn into a list that allows nothing, or into an empty list that allows everything. +- **A refusal** exits `12` with kind and code `policy_denied`; nothing was sent. With `--format json` the error object names the `operation`, the `record` (`api`, `slot`, `subslot`, `index`) of a read or a write or the DCP `block`, and the `target` (`station`, `mac`, `ip`) ([docs/exitcodes.md](docs/exitcodes.md), [docs/json-output.md](docs/json-output.md)). A command whose result has several parts (`device info`, `status`, I&M1–4 of `im read`, `topology`, `topology check`) reports a refused part as a part that failed (exit 7). A refused re-parameterization (`connect --reparam`) is reported in its `reparameterized` event, and the AR runs on. +- **Not covered**, so always sent: DCP Identify and Get (`discover`, `identify`, `name get`, `ip get`, finding a device by `--station`), LLDP, the transaction brackets of a DCP Set (Control/Start and Control/Stop), Release (`disconnect`, the end of an AR), and what belongs to an AR once its Connect was allowed: the answer to ApplicationReady, alarm acknowledgements and the cyclic frames. +- **The AR commands** (`connect`, `ar`, `iocr`, `io`, `alarms`, and `record write` and `im write` with `--gsdml` or `--model`) are checked before anything is sent: their Connect, the write of each parameter record, PrmEnd and, with `--assign-ip`, the DCP Set of `IP/Parameter`. One of them refused, and no AR is attempted. + +What the commands send: + +| Command | Needs | +|---------|-------| +| `name set` | `dcp-set` of `Device/NameOfStation` | +| `ip set` | `dcp-set` of `IP/Parameter` | +| `signal` | `dcp-set` of `Control/Signal` | +| `reset` | `dcp-set` of `Control/ResetToFactory` | +| `record read`, `im read`, `diagnostics`, `device info`, `status`, `mrp status`, `topology`, `topology check` | `read-implicit` of their records | +| `record write`, `im write` | `connect` and `write` (a device access AR); with `--gsdml` or `--model` also `prm-end` | +| `connect`, `ar`, `iocr`, `io`, `alarms` | `connect`, `write` (the parameter records), `prm-end`; `--assign-ip`: `dcp-set` of `IP/Parameter`; `--reparam`: `prm-begin` as well | + +```console +$ sudo profinetctl -i eth0 record read -s io-rack-1 --index 0xAFF0 --allow-operation read-implicit --allow-read-index 0xF000-0xF0FF +error: read 0/0/0x0001 index 0xAFF0: controller: read-implicit 0/0/0x0001 index 0xAFF0: profinet: not allowed by the local allow-list; nothing was sent +$ echo $? +12 +$ sudo profinetctl -i eth0 signal -s io-rack-1 --allow-nothing -o json +{ + "error": { + "kind": "policy_denied", + "code": "policy_denied", + "message": "DCP Signal: dcp: set Control/Signal: profinet: not allowed by the local allow-list; nothing was sent", + "reason": "policy_denied", + "operation": "dcp-set", + "block": "Control/Signal", + "target": { + "station": "io-rack-1", + "mac": "00:0e:cf:12:34:56", + "ip": "192.168.0.10" + } + } +} +``` ## Connecting as IO-Controller @@ -198,6 +252,7 @@ $ sudo profinetctl -i eth0 connect -s io-rack-1 --gsdml device.xml --plug 3=0x30 | 9 | permission: the host denies raw Ethernet access | | 10 | output or internal error | | 11 | not found: no device answers to the station name | +| 12 | policy denied: the allow-list (`--allow-*`) refused a request; nothing was sent | | 130 | interrupted (Ctrl-C) before a result | Details in [docs/exitcodes.md](docs/exitcodes.md). diff --git a/RELEASE.md b/RELEASE.md index be78b03..ff0cb0a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -23,6 +23,54 @@ ending with a `---` line and no `---` line inside a section --- +## v0.23.0 + +**Date:** 2026-12-01 +**Previous release:** v0.22.3 + +profinetctl exposes go-profinet's allow-list (engineering policy 1.7, +SEC-R02): what profinetctl may send, checked before anything is sent. +Still built on go-profinet v0.28.0. Without the new flags nothing +changes: there is no allow-list, and the commands send what they sent +before. + +### Added + +- **Allow-list flags** (global): `--allow-operation` (go-profinet's + operation classes `connect`, `read`, `read-implicit`, `write`, + `prm-begin`, `prm-end`, `other-control`, `dcp-set`; repeatable), + `--allow-read-index` and `--allow-write-index` (record index ranges + `FIRST-LAST`), `--allow-dcp-block` (DCP Set blocks such as + `Device/NameOfStation`), `--allow-list-file` (the same as a JSON file) + and `--allow-nothing`. They set `controller.Allowlist` on the + controller of the AR commands and on the record clients, and the + `dcp.SetAllowlist` go-profinet's controller derives from it on the DCP + requester of `name set`, `ip set`, `signal` and `reset`. DCP Identify + and Get, LLDP, Release and what belongs to an established AR are not + covered (go-profinet SECURITY.md, "What a controller may send"); the + README's "Allow-list" section lists what each command needs. +- **An empty allow-list allows nothing**, as in go-profinet, and only + `--allow-nothing` gives one: an `--allow-list-file` without operations + is refused (exit 3), and so is an index range or a DCP block whose + operation the list does not allow (exit 2 with the flags, 3 in a file). + +### Exit codes and JSON output + +- **New exit code `12`** (kind and code `policy_denied`): the allow-list + refused a request; nothing of it was sent, and an AR command attempted + no AR. The JSON error object adds `"reason": "policy_denied"`, + `operation`, `record` (`api`, `slot`, `subslot`, `index`) or `block`, + and `target` (`station`, `mac`, `ip`). A command whose result has + several parts (`device info`, `status`, I&M1–4 of `im read`, + `topology`, `topology check`) reports a refused part as a part that + failed (exit 7). The other codes are unchanged (docs/exitcodes.md, + docs/json-output.md). +- A malformed allow-list flag or file is invalid input (exit 3: + `invalid_input`, `input_file_open_failed`); a combination the flags + exclude is a usage error (exit 2: `invalid_flag_combination`). + +--- + ## v0.22.3 **Date:** 2026-11-30 diff --git a/SECURITY.md b/SECURITY.md index 4e9f02c..8d08897 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -45,6 +45,10 @@ Read-only commands (`discover`, `identify`, `name get`, `ip get`, `record read`, A command that names a device with `--station` acts only on a device whose answer carries that station name. When more than 4096 devices answer the DCP Identify of that lookup, the station cannot be told apart: the command sends nothing more and exits 6 (`duplicate_station_name`). Above 4096 answers, `discover` and `topology` show the devices of the first 4096, marked truncated (exit code 7). `topology` reads only the devices whose IP address lies in a subnet of the interface (`--read-any-address` reads the others too), and its reads end after 2 × `--timeout`. +### Restricting what profinetctl sends + +The `--allow-*` flags (README, "Allow-list") give profinetctl go-profinet's allow-list: the operation classes, record index ranges and DCP Set blocks it may send. A request outside it is refused before it is sent (exit code 12). It is a local restriction of the tool, for a script or an operator that should only read, or only name devices: it authenticates nobody, does not protect a device from anyone else on the network, and does not cover DCP Identify and Get, LLDP, Release or the cyclic data of an AR it allowed. Without the flags there is no allow-list. + ### Privileges profinetctl needs raw Ethernet access (root, CAP_NET_RAW, `/dev/bpf*` or Npcap). Prefer granting the capability to the binary (`setcap cap_net_raw,cap_net_admin+ep`) over running it as root, and do not grant it on shared hosts. diff --git a/cmd/allow.go b/cmd/allow.go new file mode 100644 index 0000000..553df77 --- /dev/null +++ b/cmd/allow.go @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT + +package cmd + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/otfabric/go-profinet/controller" + "github.com/otfabric/go-profinet/dcp" + "github.com/otfabric/go-profinet/ethernet" + "github.com/otfabric/go-profinet/pnio" + "github.com/otfabric/go-profinet/rpc" + + "github.com/otfabric/profinetctl/internal/errs" +) + +// The allow-list of an invocation is go-profinet's: controller.Allowlist +// for what the controller and the record clients send (operation classes, +// record index ranges, DCP Set blocks) and, derived from it as go-profinet's +// controller derives it, dcp.SetAllowlist for the DCP Sets of the commands +// that set a name or an address, flash the LED or reset. profinetctl adds no +// rule of its own: it only builds the list from the command line. + +// allowFlags are the flags of the allow-list. +type allowFlags struct { + operations []string + readIndexes []string + writeIndexes []string + dcpBlocks []string + nothing bool + file string +} + +// The names of the allow-list flags. +const ( + flagAllowOperation = "allow-operation" + flagAllowReadIndex = "allow-read-index" + flagAllowWriteIndex = "allow-write-index" + flagAllowDCPBlock = "allow-dcp-block" + flagAllowNothing = "allow-nothing" + flagAllowListFile = "allow-list-file" +) + +func addAllowFlags(pf *pflag.FlagSet, f *allowFlags) { + pf.StringArrayVar(&f.operations, flagAllowOperation, nil, "Send only these classes of operation: "+strings.Join(operationNames(), ", ")+" (repeatable, or comma-separated)") + pf.StringArrayVar(&f.readIndexes, flagAllowReadIndex, nil, "Restrict read and read-implicit to this record index or range FIRST-LAST, e.g. 0xAFF0-0xAFFF (repeatable)") + pf.StringArrayVar(&f.writeIndexes, flagAllowWriteIndex, nil, "Restrict write to this record index or range FIRST-LAST (repeatable)") + pf.StringArrayVar(&f.dcpBlocks, flagAllowDCPBlock, nil, "Restrict dcp-set to this DCP block, e.g. Device/NameOfStation, IP/Parameter or OPTION/SUBOPTION (repeatable)") + pf.BoolVar(&f.nothing, flagAllowNothing, false, "Use an allow-list that allows nothing: every request it covers is refused") + pf.StringVar(&f.file, flagAllowListFile, "", "Read the allow-list from this JSON file") +} + +// operations are the classes of operation an allow-list names, in +// go-profinet's order. +var operations = []controller.Operation{ + controller.OpConnect, controller.OpRead, controller.OpReadImplicit, controller.OpWrite, + controller.OpPrmBegin, controller.OpPrmEnd, controller.OpOtherControl, controller.OpDCPSet, +} + +// operationNames are go-profinet's names of the operations. +func operationNames() []string { + out := make([]string, len(operations)) + for i, o := range operations { + out[i] = o.String() + } + return out +} + +// parseOperation returns the operation go-profinet names s. +func parseOperation(s string) (controller.Operation, error) { + v := strings.ToLower(strings.TrimSpace(s)) + for _, o := range operations { + if o.String() == v { + return o, nil + } + } + return 0, fmt.Errorf("unknown operation %q (one of %s)", s, strings.Join(operationNames(), ", ")) +} + +// parseIndex parses a record index: decimal or 0x hex, 0 to 0xFFFF. +func parseIndex(s string) (pnio.Index, error) { + v, err := strconv.ParseUint(strings.TrimSpace(s), 0, 16) + if err != nil { + return 0, fmt.Errorf("record index %q: a number from 0 to 0xFFFF", s) + } + return pnio.Index(v), nil +} + +// parseIndexRange parses INDEX or FIRST-LAST. +func parseIndexRange(s string) (controller.IndexRange, error) { + first, last, isRange := strings.Cut(s, "-") + f, err := parseIndex(first) + if err != nil { + return controller.IndexRange{}, err + } + l := f + if isRange { + if l, err = parseIndex(last); err != nil { + return controller.IndexRange{}, err + } + } + if f > l { + return controller.IndexRange{}, fmt.Errorf("record index range %q: the first index is after the last", s) + } + return controller.IndexRange{First: f, Last: l}, nil +} + +// namedBlocks are the DCP blocks go-profinet names, by their name. +var namedBlocks = []dcp.BlockID{ + dcp.IPMAC, dcp.IPParameter, dcp.IPFullSuite, + dcp.DeviceVendor, dcp.DeviceName, dcp.DeviceID, dcp.DeviceRole, dcp.DeviceOpts, dcp.DeviceAlias, + dcp.DeviceInst, dcp.DeviceOEMID, dcp.DeviceGW, dcp.DeviceRSI, + dcp.DHCPClientID, dcp.DHCPControl, + dcp.CtrlStart, dcp.CtrlStop, dcp.CtrlSignal, dcp.CtrlResponse, dcp.CtrlFactory, dcp.CtrlReset, + dcp.Initiative, +} + +// optionNames are the DCP options go-profinet names in its block names. +var optionNames = map[string]dcp.Option{ + "ip": dcp.OptionIP, "device": dcp.OptionDeviceProperties, "dhcp": dcp.OptionDHCP, "control": dcp.OptionControl, +} + +// parseBlock parses a DCP block: go-profinet's name of it +// ("Device/NameOfStation", case-insensitive), or OPTION/SUBOPTION with +// numbers (decimal or 0x hex) or an option name ("DHCP/12"). +func parseBlock(s string) (dcp.BlockID, error) { + v := strings.TrimSpace(s) + for _, b := range namedBlocks { + if strings.EqualFold(b.String(), v) { + return b, nil + } + } + opt, sub, ok := strings.Cut(v, "/") + if ok { + o, known := optionNames[strings.ToLower(opt)] + if !known { + n, err := strconv.ParseUint(opt, 0, 8) + o, known = dcp.Option(n), err == nil + } + n, err := strconv.ParseUint(sub, 0, 8) + if known && err == nil { + return dcp.NewBlockID(o, uint8(n)), nil + } + } + return 0, fmt.Errorf("DCP block %q: a name such as Device/NameOfStation, IP/Parameter, Control/Signal, or OPTION/SUBOPTION", s) +} + +// splitValues splits the values of a repeatable flag at commas. +func splitValues(vs []string) []string { + var out []string + for _, v := range vs { + for p := range strings.SplitSeq(v, ",") { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + } + return out +} + +// allowFile is the JSON form of an allow-list (--allow-list-file): the +// fields of go-profinet's controller.Allowlist. +type allowFile struct { + Operations []string `json:"operations"` + ReadIndexes []fileRange `json:"read_indexes"` + WriteIndexes []fileRange `json:"write_indexes"` + DCPBlocks []string `json:"dcp_blocks"` +} + +// fileRange is an IndexRange of the file; Last defaults to First. +type fileRange struct { + First *fileIndex `json:"first"` + Last *fileIndex `json:"last"` +} + +// fileIndex is a record index of the file: a number, or a string as the +// flags take it ("0xAFF0"). +type fileIndex pnio.Index + +func (i *fileIndex) UnmarshalJSON(b []byte) error { + var n uint16 + if err := json.Unmarshal(b, &n); err == nil { + *i = fileIndex(n) + return nil + } + var s string + if err := json.Unmarshal(b, &s); err != nil { + return fmt.Errorf("record index %s: a number from 0 to 65535 or a string such as \"0xAFF0\"", b) + } + v, err := parseIndex(s) + *i = fileIndex(v) + return err +} + +// ranges converts the ranges of the file. +func ranges(rs []fileRange, field string) ([]controller.IndexRange, error) { + out := make([]controller.IndexRange, 0, len(rs)) + for n, r := range rs { + if r.First == nil { + return nil, fmt.Errorf("%s[%d]: no \"first\"", field, n) + } + last := r.First + if r.Last != nil { + last = r.Last + } + if *r.First > *last { + return nil, fmt.Errorf("%s[%d]: the first index is after the last", field, n) + } + out = append(out, controller.IndexRange{First: pnio.Index(*r.First), Last: pnio.Index(*last)}) + } + return out, nil +} + +// listFlags returns the flags of the lists that were given. +func (f *allowFlags) listFlags() []string { + var out []string + for _, x := range []struct { + name string + vs []string + }{{flagAllowOperation, f.operations}, {flagAllowReadIndex, f.readIndexes}, {flagAllowWriteIndex, f.writeIndexes}, {flagAllowDCPBlock, f.dcpBlocks}} { + if len(x.vs) > 0 { + out = append(out, "--"+x.name) + } + } + return out +} + +// build returns the allow-list of the flags: nil without any (profinetctl +// sends what it sent before). It sends nothing; every error is a usage +// error or invalid input. +func (f *allowFlags) build() (*controller.Allowlist, error) { + lists := f.listFlags() + switch { + case f.nothing && (f.file != "" || len(lists) > 0): + return nil, errs.New(errs.KindUsage, errs.CodeInvalidFlagCombination, + fmt.Sprintf("--%s cannot be combined with another allow-list flag", flagAllowNothing), nil) + case f.nothing: + return &controller.Allowlist{}, nil + case f.file != "" && len(lists) > 0: + return nil, errs.New(errs.KindUsage, errs.CodeInvalidFlagCombination, + fmt.Sprintf("--%s cannot be combined with %s: put the whole allow-list in the file", flagAllowListFile, strings.Join(lists, ", ")), nil) + case f.file != "": + return readAllowFile(f.file) + case len(lists) == 0: + return nil, nil + } + l := &controller.Allowlist{} + for _, s := range splitValues(f.operations) { + o, err := parseOperation(s) + if err != nil { + return nil, errs.InvalidInput(errs.CodeInvalidInput, "--"+flagAllowOperation+": "+err.Error(), err) + } + l.Operations = append(l.Operations, o) + } + for _, x := range []struct { + name string + vs []string + dst *[]controller.IndexRange + }{{flagAllowReadIndex, f.readIndexes, &l.ReadIndexes}, {flagAllowWriteIndex, f.writeIndexes, &l.WriteIndexes}} { + for _, s := range splitValues(x.vs) { + r, err := parseIndexRange(s) + if err != nil { + return nil, errs.InvalidInput(errs.CodeInvalidInput, "--"+x.name+": "+err.Error(), err) + } + *x.dst = append(*x.dst, r) + } + } + for _, s := range splitValues(f.dcpBlocks) { + b, err := parseBlock(s) + if err != nil { + return nil, errs.InvalidInput(errs.CodeInvalidInput, "--"+flagAllowDCPBlock+": "+err.Error(), err) + } + l.DCPBlocks = append(l.DCPBlocks, b) + } + if err := narrowsAllowed(l); err != nil { + return nil, errs.New(errs.KindUsage, errs.CodeInvalidFlagCombination, + err.Error()+": give --"+flagAllowOperation+" with it (--"+flagAllowNothing+" allows nothing)", nil) + } + return l, nil +} + +// narrowsAllowed refuses a restriction of an operation the list does not +// allow: it would restrict nothing, and the list would allow nothing of +// what it seems to allow. +func narrowsAllowed(l *controller.Allowlist) error { + has := func(ops ...controller.Operation) bool { + for _, o := range ops { + for _, x := range l.Operations { + if x == o { + return true + } + } + } + return false + } + switch { + case len(l.ReadIndexes) > 0 && !has(controller.OpRead, controller.OpReadImplicit): + return errors.New("read index ranges restrict read and read-implicit, which the allow-list does not allow") + case len(l.WriteIndexes) > 0 && !has(controller.OpWrite): + return errors.New("write index ranges restrict write, which the allow-list does not allow") + case len(l.DCPBlocks) > 0 && !has(controller.OpDCPSet): + return errors.New("DCP blocks restrict dcp-set, which the allow-list does not allow") + } + return nil +} + +// readAllowFile reads the allow-list of --allow-list-file. +func readAllowFile(path string) (*controller.Allowlist, error) { + b, err := readInputFile(path) + if err != nil { + return nil, errs.InvalidInput(errs.CodeInputFileOpenFailed, fmt.Sprintf("--%s: %v", flagAllowListFile, err), err) + } + bad := func(err error) error { + return errs.InvalidInput(errs.CodeInvalidInput, fmt.Sprintf("--%s %s: %v", flagAllowListFile, path, err), err) + } + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + var f allowFile + if err := dec.Decode(&f); err != nil { + return nil, bad(err) + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return nil, bad(errors.New("data after the allow-list")) + } + l := &controller.Allowlist{} + for _, s := range f.Operations { + o, err := parseOperation(s) + if err != nil { + return nil, bad(err) + } + l.Operations = append(l.Operations, o) + } + if l.ReadIndexes, err = ranges(f.ReadIndexes, "read_indexes"); err != nil { + return nil, bad(err) + } + if l.WriteIndexes, err = ranges(f.WriteIndexes, "write_indexes"); err != nil { + return nil, bad(err) + } + for _, s := range f.DCPBlocks { + b, err := parseBlock(s) + if err != nil { + return nil, bad(err) + } + l.DCPBlocks = append(l.DCPBlocks, b) + } + if err := narrowsAllowed(l); err != nil { + return nil, bad(err) + } + if len(l.Operations) == 0 { + return nil, bad(fmt.Errorf("no operation: an allow-list that allows nothing is --%s, not a file", flagAllowNothing)) + } + return l, nil +} + +// policy is the allow-list of an invocation and the last refusal it +// reported, for the target of the error. +type policy struct { + list *controller.Allowlist + mu sync.Mutex + last *errs.PolicyTarget + // resolved is the device the command resolved (station name, MAC, + // IP address), the target of a refusal that reported none. + resolved errs.PolicyTarget +} + +// setList sets the allow-list of the invocation, with its refusals +// recorded. +func (p *policy) setList(l *controller.Allowlist) { + if l != nil { + l.Refused = p.refused + } + p.list = l +} + +// refused records the target of a refusal of the controller or of a +// record client. +func (p *policy) refused(r controller.Refusal) { + t := errs.PolicyTarget{Station: r.Station} + if r.MAC != (ethernet.MAC{}) { + t.MAC = r.MAC.String() + } + if u, ok := r.Addr.(*net.UDPAddr); ok && u != nil { + t.IP = u.IP.String() + } + p.mu.Lock() + p.last = &t + p.mu.Unlock() +} + +// dcpRefused records the target of a refusal of the DCP requester. +func (p *policy) dcpRefused(r dcp.SetRefusal) { + p.refused(controller.Refusal{Op: controller.OpDCPSet, MAC: r.Dst, Block: r.Block, Err: r.Err}) +} + +// resolve records the device a command resolved. +func (p *policy) resolve(id dcp.Identity) { + t := errs.PolicyTarget{Station: id.NameOfStation, MAC: id.MAC.String()} + if id.IP.Addr.IsValid() && !id.IP.Addr.IsUnspecified() { + t.IP = id.IP.Addr.String() + } + p.mu.Lock() + p.resolved = t + p.mu.Unlock() +} + +// dcpList is the SetAllowlist of the DCP requester for the allow-list, as +// go-profinet's controller derives it: nil (every block) when dcp-set is +// allowed without blocks, the blocks when it is allowed with blocks, and +// no Set when it is not allowed. +func (p *policy) dcpList() *dcp.SetAllowlist { + l := p.list + if l == nil { + return nil + } + for _, o := range l.Operations { + if o == controller.OpDCPSet && len(l.DCPBlocks) == 0 { + return nil + } + } + s := &dcp.SetAllowlist{Refused: p.dcpRefused} + for _, o := range l.Operations { + if o == controller.OpDCPSet { + s.Blocks = append(s.Blocks, l.DCPBlocks...) + break + } + } + return s +} + +// recordClient returns a record client with the allow-list. go-profinet +// refuses only an allow-list with an unknown operation or a range whose +// first index is after its last, which build never makes. +func (p *policy) recordClient(a *app, cli *rpc.Client, addr net.Addr, object rpc.UUID) *controller.RecordClient { + rc, err := controller.NewRecordClientWith(cli, addr, object, controller.RecordClientOptions{Allowed: p.list, Logger: a.logger()}) + if err != nil { + panic(fmt.Sprintf("profinetctl: allow-list: %v", err)) + } + return rc +} + +// complete fills the target of a policy_denied error: the device of the +// refusal, else the device the command resolved. +func (p *policy) complete(err error) error { + e, ok := errs.As(err) + if !ok || e.Policy == nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + t := &e.Policy.Target + for _, src := range []*errs.PolicyTarget{p.last, &p.resolved} { + if src == nil { + continue + } + if t.Station == "" { + t.Station = src.Station + } + if t.MAC == "" { + t.MAC = src.MAC + } + if t.IP == "" { + t.IP = src.IP + } + } + return err +} + +// wrapPolicy completes the policy_denied errors of every command of root. +func (p *policy) wrapPolicy(root *cobra.Command) { + for _, c := range root.Commands() { + p.wrapPolicy(c) + } + if run := root.RunE; run != nil { + root.RunE = func(c *cobra.Command, args []string) error { return p.complete(run(c, args)) } + } +} + +// policyDenied is the typed error of a request the allow-list refused. +func policyDenied(msg string, err error) *errs.Error { + pol := &errs.Policy{} + if ce, ok := errors.AsType[*controller.NotAllowedError](err); ok { + pol.Operation = ce.Op.String() + if ce.Op == controller.OpRead || ce.Op == controller.OpReadImplicit || ce.Op == controller.OpWrite { + r := ce.Record + pol.Record = &errs.PolicyRecord{API: r.API, Slot: r.Slot, Subslot: r.Subslot, Index: uint16(r.Index)} + } + } + if de, ok := errors.AsType[*dcp.NotAllowedError](err); ok { + pol.Operation, pol.Block = controller.OpDCPSet.String(), de.Block.String() + } + e := errs.New(errs.KindPolicyDenied, errs.CodePolicyDenied, msg+"; nothing was sent", err) + e.Policy = pol + return e +} diff --git a/cmd/allow_test.go b/cmd/allow_test.go new file mode 100644 index 0000000..92ee66b --- /dev/null +++ b/cmd/allow_test.go @@ -0,0 +1,425 @@ +// SPDX-License-Identifier: MIT + +package cmd + +import ( + "encoding/json" + "errors" + "fmt" + "net" + "slices" + "strings" + "testing" + + "github.com/otfabric/go-profinet/controller" + "github.com/otfabric/go-profinet/dcp" + "github.com/otfabric/go-profinet/ethernet" + "github.com/otfabric/go-profinet/rpc" + + "github.com/otfabric/profinetctl/internal/errs" +) + +func TestParseOperation(t *testing.T) { + t.Parallel() + for _, o := range operations { + for _, s := range []string{o.String(), " " + strings.ToUpper(o.String()) + " "} { + if got, err := parseOperation(s); err != nil || got != o { + t.Fatalf("%q: %v %v", s, got, err) + } + } + } + if _, err := parseOperation("release"); err == nil || !strings.Contains(err.Error(), "connect, read, read-implicit") { + t.Fatalf("release: %v", err) + } +} + +func TestParseIndexRange(t *testing.T) { + t.Parallel() + for s, want := range map[string]controller.IndexRange{ + "0xAFF0": {First: 0xAFF0, Last: 0xAFF0}, + "16": {First: 16, Last: 16}, + "0xAFF0-0xAFFF": {First: 0xAFF0, Last: 0xAFFF}, + " 1 - 0xFFFF ": {First: 1, Last: 0xFFFF}, + "0-0": {}, + } { + if got, err := parseIndexRange(s); err != nil || got != want { + t.Fatalf("%q: %+v %v", s, got, err) + } + } + for _, s := range []string{"", "x", "0x10000", "-1", "1-", "2-1", "0xAFFF-0xAFF0", "1-2-3"} { + if _, err := parseIndexRange(s); err == nil { + t.Fatalf("%q accepted", s) + } + } +} + +func TestParseBlock(t *testing.T) { + t.Parallel() + for _, b := range namedBlocks { + if got, err := parseBlock(strings.ToLower(b.String())); err != nil || got != b { + t.Fatalf("%s: %v %v", b, got, err) + } + } + for s, want := range map[string]dcp.BlockID{ + "2/2": dcp.DeviceName, + "0x01/0x2": dcp.IPParameter, + "DHCP/12": dcp.DHCPHostName, + "dhcp/61": dcp.DHCPClientID, + "ip/3": dcp.IPFullSuite, + "Device/2": dcp.DeviceName, + "Control/6": dcp.CtrlReset, + "7/1": dcp.NewBlockID(dcp.OptionNMEDomain, 1), + } { + if got, err := parseBlock(s); err != nil || got != want { + t.Fatalf("%q: %v %v", s, got, err) + } + } + for _, s := range []string{"", "Device", "Name", "Foo/1", "2/256", "256/1", "2/x", "All"} { + if _, err := parseBlock(s); err == nil { + t.Fatalf("%q accepted", s) + } + } +} + +func TestSplitValues(t *testing.T) { + t.Parallel() + if got := splitValues([]string{"read, write", "", " ,connect"}); !slices.Equal(got, []string{"read", "write", "connect"}) { + t.Fatalf("%q", got) + } +} + +// kindCode returns the kind and code of a typed error. +func kindCode(t *testing.T, err error) string { + t.Helper() + e, ok := errs.As(err) + if !ok { + t.Fatalf("untyped error %v", err) + } + return string(e.Kind) + "/" + e.Code +} + +func TestAllowFlagsBuild(t *testing.T) { + t.Parallel() + if l, err := (&allowFlags{}).build(); l != nil || err != nil { + t.Fatalf("no flags: %+v %v", l, err) + } + l, err := (&allowFlags{nothing: true}).build() + if err != nil || l == nil || len(l.Operations) != 0 { + t.Fatalf("nothing: %+v %v", l, err) + } + l, err = (&allowFlags{ + operations: []string{"read-implicit,write", "dcp-set"}, + readIndexes: []string{"0xAFF0-0xAFFF", "0xF000"}, + writeIndexes: []string{"0x10"}, + dcpBlocks: []string{"Device/NameOfStation,IP/Parameter"}, + }).build() + if err != nil || !slices.Equal(l.Operations, []controller.Operation{controller.OpReadImplicit, controller.OpWrite, controller.OpDCPSet}) || + !slices.Equal(l.ReadIndexes, []controller.IndexRange{{First: 0xAFF0, Last: 0xAFFF}, {First: 0xF000, Last: 0xF000}}) || + !slices.Equal(l.WriteIndexes, []controller.IndexRange{{First: 0x10, Last: 0x10}}) || + !slices.Equal(l.DCPBlocks, []dcp.BlockID{dcp.DeviceName, dcp.IPParameter}) { + t.Fatalf("lists: %+v %v", l, err) + } + for _, c := range []struct { + f allowFlags + want string + }{ + {allowFlags{nothing: true, operations: []string{"read"}}, "usage/invalid_flag_combination"}, + {allowFlags{nothing: true, file: "x.json"}, "usage/invalid_flag_combination"}, + {allowFlags{file: "x.json", operations: []string{"read"}}, "usage/invalid_flag_combination"}, + {allowFlags{readIndexes: []string{"1"}}, "usage/invalid_flag_combination"}, + {allowFlags{operations: []string{"write"}, readIndexes: []string{"1"}}, "usage/invalid_flag_combination"}, + {allowFlags{operations: []string{"read"}, writeIndexes: []string{"1"}}, "usage/invalid_flag_combination"}, + {allowFlags{operations: []string{"write"}, dcpBlocks: []string{"IP/Parameter"}}, "usage/invalid_flag_combination"}, + {allowFlags{operations: []string{"nope"}}, "invalid_input/invalid_input"}, + {allowFlags{operations: []string{"read"}, readIndexes: []string{"2-1"}}, "invalid_input/invalid_input"}, + {allowFlags{operations: []string{"write"}, writeIndexes: []string{"x"}}, "invalid_input/invalid_input"}, + {allowFlags{operations: []string{"dcp-set"}, dcpBlocks: []string{"x"}}, "invalid_input/invalid_input"}, + } { + if _, err := c.f.build(); err == nil || kindCode(t, err) != c.want { + t.Fatalf("%+v: %v, want %s", c.f, err, c.want) + } + } + // A read range with read alone is enough. + if _, err := (&allowFlags{operations: []string{"read"}, readIndexes: []string{"1"}}).build(); err != nil { + t.Fatal(err) + } +} + +func TestReadAllowFile(t *testing.T) { + t.Parallel() + file := func(s string) string { return writeFile(t, "allow.json", []byte(s)) } + l, err := (&allowFlags{file: file(`{ + "operations": ["read", "read-implicit", "write", "dcp-set"], + "read_indexes": [{"first": "0xAFF0", "last": "0xAFFF"}, {"first": 61440}], + "write_indexes": [{"first": 16, "last": "0x20"}], + "dcp_blocks": ["Device/NameOfStation", "1/2"] + }`)}).build() + if err != nil || len(l.Operations) != 4 || + !slices.Equal(l.ReadIndexes, []controller.IndexRange{{First: 0xAFF0, Last: 0xAFFF}, {First: 0xF000, Last: 0xF000}}) || + !slices.Equal(l.WriteIndexes, []controller.IndexRange{{First: 0x10, Last: 0x20}}) || + !slices.Equal(l.DCPBlocks, []dcp.BlockID{dcp.DeviceName, dcp.IPParameter}) { + t.Fatalf("file: %+v %v", l, err) + } + if _, err := (&allowFlags{file: file(`{"operations":["connect"]}` + "\n")}).build(); err != nil { + t.Fatalf("trailing newline: %v", err) + } + if _, err := (&allowFlags{file: t.TempDir() + "/none.json"}).build(); err == nil || kindCode(t, err) != "invalid_input/input_file_open_failed" { + t.Fatalf("missing file: %v", err) + } + for _, s := range []string{ + ``, + `[`, + `{"operations": ["read"], "extra": 1}`, + `{"operations": ["read"]} {}`, + `{"operations": ["nope"]}`, + `{"operations": []}`, + `{}`, + `{"operations": ["read"], "read_indexes": [{"last": 1}]}`, + `{"operations": ["read"], "read_indexes": [{"first": 2, "last": 1}]}`, + `{"operations": ["read"], "read_indexes": [{"first": "x"}]}`, + `{"operations": ["read"], "read_indexes": [{"first": 70000}]}`, + `{"operations": ["read"], "read_indexes": [{"first": true}]}`, + `{"operations": ["write"], "write_indexes": [{"first": -1}]}`, + `{"operations": ["write"], "write_indexes": [{"first": 2, "last": 1}]}`, + `{"operations": ["write"], "read_indexes": [{"first": 1}]}`, + `{"operations": ["dcp-set"], "dcp_blocks": ["nope"]}`, + `{"operations": ["read"], "dcp_blocks": ["IP/Parameter"]}`, + } { + if _, err := (&allowFlags{file: file(s)}).build(); err == nil || kindCode(t, err) != "invalid_input/invalid_input" { + t.Fatalf("%s: %v", s, err) + } + } + if _, err := (&allowFlags{file: file(`{"operations": []}`)}).build(); !strings.Contains(err.Error(), "--allow-nothing") { + t.Fatalf("empty list: %v", err) + } +} + +func TestPolicyDCPList(t *testing.T) { + t.Parallel() + var p policy + if p.dcpList() != nil { + t.Fatal("no list: a DCP list") + } + p.setList(&controller.Allowlist{Operations: []controller.Operation{controller.OpRead, controller.OpDCPSet}}) + if p.dcpList() != nil { + t.Fatal("dcp-set without blocks: restricted") + } + p.setList(&controller.Allowlist{Operations: []controller.Operation{controller.OpDCPSet}, DCPBlocks: []dcp.BlockID{dcp.DeviceName}}) + if s := p.dcpList(); s == nil || !slices.Equal(s.Blocks, []dcp.BlockID{dcp.DeviceName}) || s.Refused == nil { + t.Fatalf("blocks: %+v", s) + } + p.setList(&controller.Allowlist{Operations: []controller.Operation{controller.OpRead}}) + if s := p.dcpList(); s == nil || len(s.Blocks) != 0 { + t.Fatalf("no dcp-set: %+v", s) + } + p.setList(nil) + if p.list != nil { + t.Fatal("nil list kept") + } +} + +func TestPolicyComplete(t *testing.T) { + t.Parallel() + var p policy + plain := errors.New("plain") + if p.complete(plain) != plain || p.complete(nil) != nil { + t.Fatal("not a policy error changed") + } + other := errs.New(errs.KindTimeout, errs.CodeRequestTimeout, "t", nil) + if p.complete(other) != other || other.Policy != nil { + t.Fatal("other kind changed") + } + mac := ethernet.MAC{2, 0, 0, 0, 0, 9} + p.resolve(dcp.Identity{NameOfStation: "dev-a", MAC: mac}) + e := policyDenied("x", &controller.NotAllowedError{Op: controller.OpConnect}) + _ = p.complete(e) + if e.Policy.Target != (errs.PolicyTarget{Station: "dev-a", MAC: mac.String()}) { + t.Fatalf("resolved: %+v", e.Policy.Target) + } + p.refused(controller.Refusal{Op: controller.OpRead, Addr: &net.UDPAddr{IP: net.IPv4(192, 168, 0, 7), Port: rpc.Port}}) + e = policyDenied("x", &controller.NotAllowedError{Op: controller.OpRead, Record: controller.Record{Slot: 1, Subslot: 2, Index: 3}}) + _ = p.complete(e) + if e.Policy.Target != (errs.PolicyTarget{Station: "dev-a", MAC: mac.String(), IP: "192.168.0.7"}) || + *e.Policy.Record != (errs.PolicyRecord{Slot: 1, Subslot: 2, Index: 3}) || e.Policy.Operation != "read" { + t.Fatalf("refusal: %+v %+v", e.Policy, e.Policy.Record) + } + other2 := ethernet.MAC{2, 0, 0, 0, 0, 8} + p.dcpRefused(dcp.SetRefusal{Dst: other2, Block: dcp.DeviceName}) + e = policyDenied("x", fmt.Errorf("w: %w", &dcp.NotAllowedError{Block: dcp.DeviceName})) + e.Policy.Target.Station = "given" + _ = p.complete(e) + if e.Policy.Target != (errs.PolicyTarget{Station: "given", MAC: other2.String()}) { + t.Fatalf("dcp: %+v", e.Policy.Target) + } + if e.Policy.Operation != "dcp-set" || e.Policy.Block != "Device/NameOfStation" || e.Policy.Record != nil { + t.Fatalf("dcp: %+v", e.Policy) + } + if !strings.HasSuffix(e.Message, "; nothing was sent") || e.Kind != errs.KindPolicyDenied || e.Code != errs.CodePolicyDenied { + t.Fatalf("error %+v", e) + } +} + +func TestPolicyRecordClientRefusesAnInvalidList(t *testing.T) { + t.Parallel() + p := policy{list: &controller.Allowlist{Operations: []controller.Operation{99}}} + defer func() { + if r := recover(); r == nil || !strings.Contains(fmt.Sprint(r), "allow-list") { + t.Fatalf("recovered %v", r) + } + }() + p.recordClient(&app{}, nil, nil, rpc.NilUUID) +} + +// policyError is the JSON error of a refusal. +type policyError struct { + Error struct { + Kind, Code, Message, Reason, Operation, Block string + Record *struct{ API, Slot, Subslot, Index int } + Target *struct{ Station, MAC, IP string } + } +} + +// refused runs profinetctl, which must exit 12, and decodes its JSON error. +func (n *testNet) refused(args ...string) policyError { + n.t.Helper() + out, errOut, code := n.run(append(args, "--format", "json")...) + if code != errs.ExitPolicyDenied { + n.t.Fatalf("profinetctl %s: exit %d, want 12\nstdout: %s\nstderr: %s", strings.Join(args, " "), code, out, errOut) + } + var e policyError + if err := json.Unmarshal([]byte(out), &e); err != nil { + n.t.Fatalf("%v\n%s", err, out) + } + if e.Error.Kind != "policy_denied" || e.Error.Code != "policy_denied" || e.Error.Reason != "policy_denied" { + n.t.Fatalf("error %+v", e.Error) + } + return e +} + +func TestAllowListRefusesRecords(t *testing.T) { + t.Parallel() + n := newTestNet(t) + d := n.device("dev-a", "192.168.0.10") + base := []string{"-i", "pn0", "record", "read", "-s", "dev-a"} + e := n.refused(append(base, "--index", "0xAFF0", "--allow-operation", "read-implicit", "--allow-read-index", "0xF000-0xF0FF")...) + if e.Error.Operation != "read-implicit" || e.Error.Record == nil || e.Error.Record.Index != 0xAFF0 || e.Error.Record.Subslot != 1 || + e.Error.Target == nil || e.Error.Target.Station != "dev-a" || e.Error.Target.MAC != d.mac.String() || e.Error.Target.IP != "192.168.0.10" { + t.Fatalf("record read: %+v %+v %+v", e.Error, e.Error.Record, e.Error.Target) + } + // Inside the range, and without index ranges: read. + n.ok(append(base, "--index", "0xF000", "--allow-operation", "read-implicit", "--allow-read-index", "0xF000-0xF0FF")...) + n.ok(append(base, "--index", "0xAFF0", "--allow-operation", "read-implicit")...) + n.ok(append(base, "--index", "0xAFF0", "--allow-list-file", writeFile(t, "a.json", []byte(`{"operations":["read-implicit"],"read_indexes":[{"first":"0xAFF0"}]}`)))...) + // I&M0 refused: the fatal error keeps the refusal. + e = n.refused("-i", "pn0", "im", "read", "-s", "dev-a", "--allow-operation", "read") + if e.Error.Operation != "read-implicit" || e.Error.Record == nil || e.Error.Record.Index != 0xAFF0 || !strings.HasPrefix(e.Error.Message, "I&M0: ") { + t.Fatalf("im read: %+v", e.Error) + } + // A write in a device access AR needs its Connect; nothing reaches the device. + write := []string{"-i", "pn0", "record", "write", "-s", "dev-a", "--slot", "2", "--subslot", "1", "--index", "0x10", "--data", "0003"} + if e = n.refused(append(write, "--allow-operation", "write")...); e.Error.Operation != "connect" { + t.Fatalf("record write: %+v", e.Error) + } + if e = n.refused(append(write, "--allow-operation", "connect,write", "--allow-write-index", "0x11-0x20")...); e.Error.Operation != "write" || e.Error.Record.Index != 0x10 || e.Error.Record.Slot != 2 { + t.Fatalf("record write range: %+v", e.Error) + } + if w := d.h.recordWrites(); len(w) != 0 { + t.Fatalf("the device stored %v", w) + } + n.ok(append(write, "--allow-operation", "connect", "--allow-operation", "write", "--allow-write-index", "0x10")...) + if w := d.h.recordWrites(); len(w) != 1 { + t.Fatalf("the device stored %v", w) + } + // Text: one error line, exit 12. + out, errOut, code := n.run(append(base, "--index", "0xAFF0", "--allow-nothing")...) + if code != 12 || out != "" || !strings.HasPrefix(errOut, "error: read 0/0/0x0001 index 0xAFF0: ") || !strings.HasSuffix(errOut, "; nothing was sent\n") { + t.Fatalf("text: %d %q %q", code, out, errOut) + } +} + +func TestAllowListRefusesDCPSets(t *testing.T) { + t.Parallel() + n := newTestNet(t) + d := n.device("dev-a", "192.168.0.10") + e := n.refused("-i", "pn0", "signal", "-s", "dev-a", "--allow-nothing") + if e.Error.Operation != "dcp-set" || e.Error.Block != "Control/Signal" || e.Error.Target.MAC != d.mac.String() || e.Error.Target.Station != "dev-a" { + t.Fatalf("signal: %+v %+v", e.Error, e.Error.Target) + } + e = n.refused("-i", "pn0", "name", "set", "renamed", "--mac", d.mac.String(), "--allow-operation", "dcp-set", "--allow-dcp-block", "Control/Signal") + if e.Error.Block != "Device/NameOfStation" { + t.Fatalf("name set: %+v", e.Error) + } + // Identify and Get are not covered. + n.ok("-i", "pn0", "name", "get", "-s", "dev-a", "--allow-nothing") + n.ok("-i", "pn0", "discover", "--wait", "200ms", "--allow-nothing") + d.h.mu.Lock() + signals := d.h.signals + d.h.mu.Unlock() + if signals != 0 { + t.Fatalf("%d signals reached the device", signals) + } + n.ok("-i", "pn0", "signal", "-s", "dev-a", "--allow-operation", "dcp-set", "--allow-dcp-block", "Control/Signal") + n.ok("-i", "pn0", "signal", "-s", "dev-a", "--allow-operation", "dcp-set") + d.h.mu.Lock() + signals = d.h.signals + d.h.mu.Unlock() + if signals != 2 { + t.Fatalf("%d signals, want 2", signals) + } +} + +func TestAllowListRefusesTheAR(t *testing.T) { + t.Parallel() + n := newTestNet(t) + d := n.device("dev-a", "192.168.0.10") + gf := gsdmlFile(t) + e := n.refused("-i", "pn0", "ar", "-s", "dev-a", "--gsdml", gf, "--allow-operation", "read") + if e.Error.Operation != "connect" || e.Error.Target == nil || e.Error.Target.Station != "dev-a" || e.Error.Target.MAC != d.mac.String() { + t.Fatalf("ar: %+v %+v", e.Error, e.Error.Target) + } + e = n.refused("-i", "pn0", "connect", "-s", "dev-a", "--gsdml", gf, "--param", "2:1:0x10:0003", "--duration", "200ms", + "--allow-operation", "connect,write,prm-end", "--allow-write-index", "0x11") + if e.Error.Operation != "write" || e.Error.Record == nil || e.Error.Record.Index != 0x10 { + t.Fatalf("connect: %+v", e.Error) + } + e = n.refused("-i", "pn0", "connect", "-s", "dev-a", "--gsdml", gf, "--duration", "200ms", "--assign-ip", "192.168.0.10/24", + "--allow-operation", "connect,write,prm-end") + if e.Error.Operation != "dcp-set" || e.Error.Block != "IP/Parameter" { + t.Fatalf("assign-ip: %+v", e.Error) + } + out := n.ok("-i", "pn0", "connect", "-s", "dev-a", "--gsdml", gf, "--duration", "300ms", "--allow-operation", "connect,write,prm-end") + if !strings.Contains(out, "summary") { + t.Fatalf("connect:\n%s", out) + } +} + +func TestAllowListPartialResults(t *testing.T) { + t.Parallel() + n := newTestNet(t) + n.device("dev-a", "192.168.0.10") + n.device("dev-b", "192.168.0.11") + // A refused part of a result with several parts is a failed part. + out, _, code := n.run("-i", "pn0", "topology", "--wait", "200ms", "--lldp-wait", "0s", "--allow-nothing", "-o", "json") + if code != 7 || !strings.Contains(out, "not allowed") { + t.Fatalf("topology: %d\n%s", code, out) + } + out, _, code = n.run("-i", "pn0", "topology", "check", "--link", "dev-a/port-001=dev-b/port-001", "--allow-nothing", "-o", "json") + if code != 7 || !strings.Contains(out, "unverified") { + t.Fatalf("topology check: %d\n%s", code, out) + } +} + +// TestAllowFlagValidationBeforeSending: allow-list flags are checked +// before the interface is opened (eth9 does not exist). +func TestAllowFlagValidationBeforeSending(t *testing.T) { + t.Parallel() + n := newTestNet(t) + sig := []string{"-i", "eth9", "signal", "-s", "dev-a"} + n.fails(3, "invalid_input", append(sig, "--allow-operation", "release")...) + n.fails(3, "invalid_input", append(sig, "--allow-operation", "read", "--allow-read-index", "0x10000")...) + n.fails(2, "invalid_flag_combination", append(sig, "--allow-read-index", "1")...) + n.fails(2, "invalid_flag_combination", append(sig, "--allow-nothing", "--allow-operation", "read")...) + n.fails(3, "input_file_open_failed", append(sig, "--allow-list-file", t.TempDir()+"/none.json")...) + n.fails(3, "invalid_input", append(sig, "--allow-list-file", writeFile(t, "e.json", []byte(`{}`)))...) + n.fails(3, "interface_open_failed", append(sig, "--allow-nothing")...) +} diff --git a/cmd/ar.go b/cmd/ar.go index 3a20906..b648168 100644 --- a/cmd/ar.go +++ b/cmd/ar.go @@ -580,7 +580,7 @@ func (a *app) establish(ctx context.Context, o *arOptions, p *parsedAR) (*arSess ctrl, err := controller.New(controller.Config{ Mux: s.link.Mux, ListenPacket: s.link.ListenPacket, RPCPort: o.rpcPort, StationName: o.controllerName, VendorID: toolVendorID, DeviceID: toolDeviceID, Instance: 1, - DCP: dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3}, Logger: a.logger(), + DCP: dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3}, Logger: a.logger(), Allowed: a.policy.list, }) if err != nil { s.link.Close() diff --git a/cmd/common.go b/cmd/common.go index 2fe3db4..9a0c0b8 100644 --- a/cmd/common.go +++ b/cmd/common.go @@ -44,6 +44,10 @@ func classify(what string, err error) error { var se *pnio.StatusError var de *dcp.SetError switch { + case errors.Is(err, profinet.ErrNotAllowed): + // Before ErrInvalidConfig: a device whose startup the allow-list + // refuses is not added, with an error that matches both. + return policyDenied(msg, err) case errors.As(err, &se): return errs.New(errs.KindRefused, errs.CodePNIOError, msg, err) case errors.As(err, &de): @@ -129,7 +133,7 @@ func (a *app) open() (*session, error) { if err != nil { return nil, err } - c, err := dcp.NewClient(l.Mux, dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3, Logger: a.logger()}) + c, err := dcp.NewClient(l.Mux, dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3, Logger: a.logger(), Allowed: a.policy.dcpList()}) if err != nil { l.Close() return nil, classify("dcp", err) @@ -214,6 +218,7 @@ func (s *session) resolve(ctx context.Context, t *target) (dcp.Identity, error) if err != nil { return id, classify("DCP Get of "+t.describe(), err) } + s.a.policy.resolve(id) return id, nil } cctx, cancel := context.WithTimeout(ctx, t.wait+s.a.timeout) @@ -239,6 +244,7 @@ func (s *session) resolve(ctx context.Context, t *target) (dcp.Identity, error) } return dcp.Identity{}, errs.New(errs.KindNotFound, errs.CodeDeviceNotFound, msg, nil) case 1: + s.a.policy.resolve(ids[0]) return ids[0], nil default: var macs []string @@ -296,7 +302,7 @@ func (a *app) openRPC(ctx context.Context, t *target) (*rpcSession, error) { } cli := rpc.NewClient(conn, true, rpc.ClientOptions{Timeout: a.timeout, Logger: a.logger()}) addr := &net.UDPAddr{IP: ip.AsSlice(), Port: rpc.Port} - rc := controller.NewRecordClient(cli, addr, pnio.ObjectUUID(max(id.Instance, 1), id.DeviceID, id.VendorID)) + rc := a.policy.recordClient(a, cli, addr, pnio.ObjectUUID(max(id.Instance, 1), id.DeviceID, id.VendorID)) return &rpcSession{session: s, id: id, cli: cli, rc: rc}, nil } diff --git a/cmd/lldp.go b/cmd/lldp.go index 12a3f8b..1374fee 100644 --- a/cmd/lldp.go +++ b/cmd/lldp.go @@ -436,7 +436,7 @@ the first 4096 answers, marked truncated, and the exit code is 7.`, continue } addr := &net.UDPAddr{IP: id.IP.Addr.AsSlice(), Port: rpc.Port} - nodes[i].rc = controller.NewRecordClient(cli, addr, pnio.ObjectUUID(max(id.Instance, 1), id.DeviceID, id.VendorID)) + nodes[i].rc = a.policy.recordClient(a, cli, addr, pnio.ObjectUUID(max(id.Instance, 1), id.DeviceID, id.VendorID)) nwg.Add(1) go func(n *topoNode) { defer nwg.Done() diff --git a/cmd/records.go b/cmd/records.go index 6b71f44..eb68b62 100644 --- a/cmd/records.go +++ b/cmd/records.go @@ -591,7 +591,9 @@ func newIMCmd(a *app) *cobra.Command { // code: a timeout is 5, a malformed answer a // protocol error. readIM classifies every failure // of I&M0 (classify returns an *errs.Error). - return nil, errs.New(first.err.Kind, first.err.Code, "I&M0: "+first.Error, first.err) + e := errs.New(first.err.Kind, first.err.Code, "I&M0: "+first.Error, first.err) + e.Policy = first.err.Policy + return nil, e } for i := 1; i <= 4; i++ { for _, sup := range first.IM0.Supported { diff --git a/cmd/roadmap.go b/cmd/roadmap.go index e7b7ef2..81b9817 100644 --- a/cmd/roadmap.go +++ b/cmd/roadmap.go @@ -352,7 +352,7 @@ that could not be read). --expect reads a JSON list of {"a":{"station","port"}, ctrl, err := controller.New(controller.Config{ Mux: s.link.Mux, ListenPacket: s.link.ListenPacket, StationName: "profinetctl", VendorID: toolVendorID, DeviceID: toolDeviceID, Instance: 1, - DCP: dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3}, Logger: a.logger(), + DCP: dcp.ClientOptions{Timeout: a.timeout / 4, Retries: 3}, Logger: a.logger(), Allowed: a.policy.list, }) if err != nil { return nil, classify("controller", err) diff --git a/cmd/root.go b/cmd/root.go index f2212f4..2fb7f12 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -46,6 +46,9 @@ type app struct { debug bool pcapFile string stderr io.Writer + // allow are the allow-list flags, policy the allow-list they give. + allow allowFlags + policy policy } // NewRootCmd builds the command tree on a backend. Every call returns a fresh tree. @@ -63,7 +66,9 @@ application relationship (AR) as IO-Controller to monitor cyclic IO data and ala Commands that change a device (name set, ip set, reset, record write, connect with outputs) only do what the command line says. reset requires --confirm with the -target's station name or MAC address. +target's station name or MAC address. The --allow-* flags restrict what profinetctl +may send with go-profinet's allow-list (operation classes, record index ranges, DCP +Set blocks); a request outside it is refused before it is sent (exit code 12). Results go to stdout as text, a table or JSON (--format); diagnostics go to stderr. Raw Ethernet access needs privileges: root or CAP_NET_RAW on Linux, access to @@ -78,6 +83,11 @@ Raw Ethernet access needs privileges: root or CAP_NET_RAW on Linux, access to if a.timeout <= 0 { return errs.InvalidInput(errs.CodeInvalidInput, "--timeout must be positive", nil) } + l, err := a.allow.build() + if err != nil { + return err + } + a.policy.setList(l) return checkDurations(c) }, } @@ -87,6 +97,7 @@ Raw Ethernet access needs privileges: root or CAP_NET_RAW on Linux, access to pf.DurationVar(&a.timeout, "timeout", envDuration(EnvTimeout, 5*time.Second), "Time limit of one request to a device (env "+EnvTimeout+")") pf.BoolVar(&a.debug, "debug", false, "Log go-profinet's diagnostics to stderr and show the causes of an error") pf.StringVar(&a.pcapFile, "pcap", "", "Record every frame sent and received to this pcap file") + addAllowFlags(pf, &a.allow) _ = clihelp.RegisterEnumFlagCompletionWithDescriptions(root, "format", format.ValueDescriptions()) _ = root.RegisterFlagCompletionFunc("interface", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { ifs, _ := b.Interfaces() @@ -126,6 +137,7 @@ Raw Ethernet access needs privileges: root or CAP_NET_RAW on Linux, access to newVersionCmd(a), ) registerCompletions(root) + a.policy.wrapPolicy(root) return root } diff --git a/docs/exitcodes.md b/docs/exitcodes.md index 9c723df..8991143 100644 --- a/docs/exitcodes.md +++ b/docs/exitcodes.md @@ -5,8 +5,8 @@ | Code | Meaning | |------|---------| | 0 | Success | -| 2 | Usage (`usage`): unknown command or flag, a missing required flag, `--param-value` or `--param-defaults` without `--gsdml`, a `--param` of a record the parameter plan writes, no device selected (`--station` or `--mac`), both selections, a missing `--confirm` for `reset` or one that names another device, `diagnostics --api` without `--slot` or `--subslot` | -| 3 | Invalid input (`invalid_input`): a flag value, environment variable, GSDML file or model that does not make sense, a `--param-value` the file does not allow (no such record or field, a field that is not Changeable, a value outside its AllowedValues or ValueItem, a field given twice) or a parameter plan an AR command cannot write, or a GSDML file with content go-profinet does not support (`unsupported_gsdml`) (a negative duration, a zero cycle factor, a send clock × reduction ratio above 65535, an address that is no host address, an input file above 16 MiB), an interface that does not exist. Nothing was sent | +| 2 | Usage (`usage`): unknown command or flag, a missing required flag, an allow-list flag combined with one it excludes (`--allow-nothing` with another, `--allow-list-file` with the list flags) or an index range or DCP block whose operation the allow-list does not allow (`invalid_flag_combination`), `--param-value` or `--param-defaults` without `--gsdml`, a `--param` of a record the parameter plan writes, no device selected (`--station` or `--mac`), both selections, a missing `--confirm` for `reset` or one that names another device, `diagnostics --api` without `--slot` or `--subslot` | +| 3 | Invalid input (`invalid_input`): a flag value, environment variable, GSDML file or model that does not make sense, a `--param-value` the file does not allow (no such record or field, a field that is not Changeable, a value outside its AllowedValues or ValueItem, a field given twice) or a parameter plan an AR command cannot write, or a GSDML file with content go-profinet does not support (`unsupported_gsdml`) (a negative duration, a zero cycle factor, a send clock × reduction ratio above 65535, an address that is no host address, an input file above 16 MiB), an interface that does not exist, an allow-list flag value go-profinet does not have (an unknown operation, a record index above 0xFFFF or a range whose first index is after its last, an unknown DCP block), an `--allow-list-file` that cannot be read (`input_file_open_failed`), is not one JSON object of the allow-list's fields, or names no operation. Nothing was sent | | 4 | Transport (`transport`): the interface cannot be opened, a socket cannot be bound or fails | | 5 | Timeout (`timeout`): the device did not answer a DCP request or an RPC call in time (`--timeout`), or an AR did not reach Running within `--connect-timeout` | | 6 | Refused or protocol error (`refused`, `protocol`): the device answered with a PNIO error status, refused a DCP Set with a block error, rejected the Connect, or answered with a malformed frame; more than one device answers to the station name, or more than 4096 devices answer the DCP Identify of a lookup by station name, so that the station cannot be told apart (`duplicate_station_name`; nothing is sent); a device has no IP address for RPC | @@ -15,6 +15,7 @@ | 9 | Permission (`permission`): the host denies raw Ethernet access: code `permission_denied` | | 10 | Output or internal (`output`, `internal`): the result could not be written, or something unexpected happened | | 11 | Not found (`not_found`, protocol-specific): no device answers to the station name (DCP Identify), no module with that ident number in the GSDML | +| 12 | Policy denied (`policy_denied`, protocol-specific): the allow-list of the invocation (`--allow-operation`, `--allow-read-index`, `--allow-write-index`, `--allow-dcp-block`, `--allow-list-file`, `--allow-nothing`) refused a request: go-profinet's `profinet.ErrNotAllowed` (`*controller.NotAllowedError`, `*dcp.NotAllowedError`). Nothing of that request was sent; for an AR command, no AR was attempted | | 130 | Interrupted (`interrupted`): Ctrl-C or SIGTERM before a one-shot command had its result | **Kind vs code:** `kind` drives the exit code; `code` in the JSON error object is stable for machines. Do not parse the human `message`. @@ -30,6 +31,7 @@ | `unsupported` | `unsupported` | | `permission` | `permission_denied` | | `not_found` | `device_not_found`, `invalid_input` (`gsdml submodules --module` with an unknown ident number) | +| `policy_denied` | `policy_denied` | | `interrupted` | `context_canceled` | | `output` | `table_render_failed`, `output_write_failed`, `output_file_write_failed` | | `internal` | `internal_unexpected` | @@ -44,8 +46,10 @@ Configurations (`--plug`, `--plug-submodule`, `gsdml config`): a `--plug` or `-- **Commands that change a device:** `name set`, `ip set`, `signal`, `reset`, `record write`, `im write`, `disconnect` and the commands that establish an AR validate their flags before sending; a rejected invocation exits `2` or `3` and has sent nothing. A refusal by the device exits `6`, a missing answer `5`; after a timeout a Set may or may not have been applied. When `im write` exits `7`, `failed` names the record that failed with the `kind` and `code` of its error, as a fatal error would have them (the table above maps the kind to its exit code); after `timeout` that record may or may not have been written. +**Allow-list:** without an `--allow-*` flag there is none, and nothing is refused. A refusal is fatal (`12`) for a command with one result; the JSON error object adds `reason` (`"policy_denied"`), `operation` (go-profinet's name: `connect`, `read`, `read-implicit`, `write`, `prm-begin`, `prm-end`, `other-control`, `dcp-set`), `record` (`api`, `slot`, `subslot`, `index`) of a read or a write, `block` of a DCP Set (`"Device/NameOfStation"`), and `target` (`station`, `mac`, `ip`, those known) ([json-output.md](json-output.md)). A command whose result has several parts (`device info`, `status`, I&M1–4 of `im read`, `topology`, `topology check`) reports a refused part as a part that failed, with exit code `7`; a refused `connect --reparam` is reported in its `reparameterized` event and does not change the exit code. An allow-list that allows nothing is `--allow-nothing`, never an empty file or a missing operation: those are refused before anything is sent (README, "Allow-list"). + **`--debug`:** logs go-profinet's diagnostics and, after a fatal error, the chain of causes (`cause: …` lines) on stderr. It does not change stdout or the exit code. -**Organisation table:** these codes follow the OT Fabric CLI exit-code table; `11` is specific to profinetctl. profinetctl does not use `1`: it keeps its organisation meaning. +**Organisation table:** these codes follow the OT Fabric CLI exit-code table; `11` and `12` are specific to profinetctl. profinetctl does not use `1`: it keeps its organisation meaning. **Format variable:** `PROFINETCTL_FORMAT` is the name to use; `PROFINETCTL_OUTPUT_FORMAT` stays accepted. When both are set, `PROFINETCTL_FORMAT` wins. diff --git a/docs/json-output.md b/docs/json-output.md index d590002..4f623de 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -12,7 +12,7 @@ These conventions are a **stable contract** for scripting. Field names are snake | Repeated rows | `devices`, `interfaces`, `entries`, `modules`, `submodules`, `neighbors`, `ports`, `links`, `inputs`, `outputs`: **arrays**, empty rather than null. Optional lists (`duplicate_names`, `options`, `module_diff`, `differences`, `blocks`, the `records` of a GSDML submodule) and optional values are **omitted** when empty | | Times in streams | `time`: local time of day with milliseconds (`"14:03:12.120"`) | | A failure inside a result | `error` (a string) on the entry that failed; `errors` (strings) on results with several parts; `failed` of `im write`: the record and its error (`kind`, `code`, `message`) | -| Fatal error | one object `{"error": {"kind", "code", "message"}}` on stdout, nothing else; see [exitcodes.md](exitcodes.md) | +| Fatal error | one object `{"error": {"kind", "code", "message"}}` on stdout, nothing else; see [exitcodes.md](exitcodes.md). A request the allow-list refused (kind and code `policy_denied`, exit 12) adds `"reason": "policy_denied"`, `operation` (`connect`, `read`, `read-implicit`, `write`, `prm-begin`, `prm-end`, `other-control`, `dcp-set`), `record` (`{"api", "slot", "subslot", "index"}`, for a read or a write), `block` (the DCP block of a Set, `"Device/NameOfStation"`) and `target` (`{"station", "mac", "ip"}`, those known); each is omitted when it does not apply | ## Results diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index 9bab41f..eb20720 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -70,3 +70,47 @@ func TestUnknownCommandIsAUsageError(t *testing.T) { t.Fatalf("output does not name the unknown command:\n%s", output) } } + +// The allow-list flags are checked before anything is opened: a malformed +// one is invalid input (3), a combination they exclude a usage error (2), +// both rendered as the JSON error with --format json (docs/exitcodes.md). +func TestAllowListFlagErrors(t *testing.T) { + dir := t.TempDir() + for _, c := range []struct { + args []string + code int + want string + }{ + {[]string{"--allow-operation", "release"}, 3, `"code": "invalid_input"`}, + {[]string{"--allow-operation", "read", "--allow-read-index", "0xAFFF-0xAFF0"}, 3, `"code": "invalid_input"`}, + {[]string{"--allow-operation", "dcp-set", "--allow-dcp-block", "Device/Nope"}, 3, `"code": "invalid_input"`}, + {[]string{"--allow-read-index", "0xAFF0"}, 2, `"code": "invalid_flag_combination"`}, + {[]string{"--allow-nothing", "--allow-operation", "read"}, 2, `"code": "invalid_flag_combination"`}, + {[]string{"--allow-list-file", dir + "/none.json"}, 3, `"code": "input_file_open_failed"`}, + } { + args := append([]string{"-i", "profinetctl-e2e-none", "signal", "-s", "dev-a", "-o", "json"}, c.args...) + output, code := run(t, args...) + if code != c.code || !strings.Contains(output, c.want) { + t.Fatalf("%v: exit %d, want %d with %s\n%s", c.args, code, c.code, c.want, output) + } + } + // A valid allow-list passes the check: the next step, opening the + // interface that does not exist, is what fails. + output, code := run(t, "-i", "profinetctl-e2e-none", "signal", "-s", "dev-a", "-o", "json", "--allow-nothing") + if code != 3 || !strings.Contains(output, `"code": "interface_open_failed"`) { + t.Fatalf("--allow-nothing: exit %d\n%s", code, output) + } +} + +// --help lists the allow-list flags and the exit code of a refusal. +func TestHelpNamesTheAllowList(t *testing.T) { + output, code := run(t, "--help") + if code != 0 { + t.Fatalf("exit %d\n%s", code, output) + } + for _, f := range []string{"--allow-operation", "--allow-read-index", "--allow-write-index", "--allow-dcp-block", "--allow-list-file", "--allow-nothing", "exit code 12"} { + if !strings.Contains(output, f) { + t.Fatalf("--help does not name %s:\n%s", f, output) + } + } +} diff --git a/internal/errs/errs.go b/internal/errs/errs.go index c84540c..41919d3 100644 --- a/internal/errs/errs.go +++ b/internal/errs/errs.go @@ -30,10 +30,13 @@ const ( // KindUnsupported is an operation the device does not support. KindUnsupported Kind = "unsupported" // KindPermission is a host that denies raw Ethernet access. - KindPermission Kind = "permission" - KindInterrupted Kind = "interrupted" - KindOutput Kind = "output" - KindInternal Kind = "internal" + KindPermission Kind = "permission" + // KindPolicyDenied is a request the allow-list of the invocation + // (--allow-*, --allow-list-file) refused before anything was sent. + KindPolicyDenied Kind = "policy_denied" + KindInterrupted Kind = "interrupted" + KindOutput Kind = "output" + KindInternal Kind = "internal" ) // Process exit codes (single mapping from Kind for fatals). @@ -49,6 +52,7 @@ const ( ExitPermission = 9 ExitInternal = 10 ExitNotFound = 11 + ExitPolicyDenied = 12 ExitInterrupted = 130 ) @@ -71,6 +75,8 @@ func ExitCodeForKind(k Kind) int { return ExitUnsupported case KindPermission: return ExitPermission + case KindPolicyDenied: + return ExitPolicyDenied case KindInterrupted: return ExitInterrupted case KindOutput, KindInternal: @@ -116,6 +122,10 @@ const ( CodeContextCanceled = "context_canceled" + // CodePolicyDenied is a request the allow-list refused: nothing was + // sent. + CodePolicyDenied = "policy_denied" + CodeJSONEncodeFailed = "json_encode_failed" CodeTableRenderFailed = "table_render_failed" CodeOutputWriteFailed = "output_write_failed" @@ -131,6 +141,40 @@ type Error struct { Code string Message string Cause error + // Policy describes the request an allow-list refused (KindPolicyDenied); + // nil otherwise. + Policy *Policy +} + +// Policy is the request an allow-list refused: the operation class, what +// it addressed and the device it was for. +type Policy struct { + // Operation is the class of the request, as go-profinet names it + // (connect, read, read-implicit, write, prm-begin, prm-end, + // other-control, dcp-set). + Operation string + // Record is the record of a read or a write; nil otherwise. + Record *PolicyRecord + // Block is the DCP block of a DCP Set ("Device/NameOfStation"). + Block string + // Target is the device the request was for. + Target PolicyTarget +} + +// PolicyRecord is the record of a refused read or write. +type PolicyRecord struct { + API uint32 + Slot uint16 + Subslot uint16 + Index uint16 +} + +// PolicyTarget is the device of a refused request; a field not known is +// empty. +type PolicyTarget struct { + Station string + MAC string + IP string } func (e *Error) Error() string { diff --git a/internal/errs/errs_test.go b/internal/errs/errs_test.go index aaf7a55..3257763 100644 --- a/internal/errs/errs_test.go +++ b/internal/errs/errs_test.go @@ -66,6 +66,7 @@ func TestExitCodes(t *testing.T) { KindNotFound: 11, KindUnsupported: 8, KindPermission: 9, + KindPolicyDenied: 12, KindInterrupted: 130, KindOutput: 10, KindInternal: 10, diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 9ef8c75..910bfa2 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -86,6 +86,29 @@ type ErrorInfo struct { Kind string `json:"kind"` Code string `json:"code"` Message string `json:"message"` + // Reason, Operation, Record, Block and Target are those of a request + // the allow-list refused (kind policy_denied); omitted otherwise. + Reason string `json:"reason,omitempty"` + Operation string `json:"operation,omitempty"` + Record *PolicyRecord `json:"record,omitempty"` + Block string `json:"block,omitempty"` + Target *PolicyTarget `json:"target,omitempty"` +} + +// PolicyRecord is the record of a refused read or write. +type PolicyRecord struct { + API uint32 `json:"api"` + Slot uint16 `json:"slot"` + Subslot uint16 `json:"subslot"` + Index uint16 `json:"index"` +} + +// PolicyTarget is the device of a refused request; unknown fields are +// omitted. +type PolicyTarget struct { + Station string `json:"station,omitempty"` + MAC string `json:"mac,omitempty"` + IP string `json:"ip,omitempty"` } // ErrorEnvelope is the top-level JSON document of a fatal error. @@ -100,7 +123,17 @@ func Info(err error) ErrorInfo { if msg == "" { msg = err.Error() } - return ErrorInfo{Kind: string(e.Kind), Code: e.Code, Message: msg} + info := ErrorInfo{Kind: string(e.Kind), Code: e.Code, Message: msg} + if p := e.Policy; p != nil { + info.Reason, info.Operation, info.Block = errs.CodePolicyDenied, p.Operation, p.Block + if r := p.Record; r != nil { + info.Record = &PolicyRecord{API: r.API, Slot: r.Slot, Subslot: r.Subslot, Index: r.Index} + } + if t := p.Target; t != (errs.PolicyTarget{}) { + info.Target = &PolicyTarget{Station: t.Station, MAC: t.MAC, IP: t.IP} + } + } + return info } return ErrorInfo{Kind: string(errs.KindInternal), Code: errs.CodeInternalUnexpected, Message: err.Error()} } diff --git a/internal/runner/runner_test.go b/internal/runner/runner_test.go index 7f104da..d6abcf5 100644 --- a/internal/runner/runner_test.go +++ b/internal/runner/runner_test.go @@ -73,6 +73,27 @@ func TestRenderFatal(t *testing.T) { } } +func TestInfoOfAPolicyRefusal(t *testing.T) { + e := errs.New(errs.KindPolicyDenied, errs.CodePolicyDenied, "refused", nil) + if i := Info(e); i.Reason != "" || i.Record != nil || i.Target != nil { + t.Fatalf("without a policy: %+v", i) + } + e.Policy = &errs.Policy{Operation: "write", Record: &errs.PolicyRecord{API: 1, Slot: 2, Subslot: 3, Index: 4}} + if i := Info(e); i.Reason != "policy_denied" || i.Operation != "write" || *i.Record != (PolicyRecord{API: 1, Slot: 2, Subslot: 3, Index: 4}) || i.Target != nil { + t.Fatalf("record: %+v", i) + } + e.Policy = &errs.Policy{Operation: "dcp-set", Block: "IP/Parameter", Target: errs.PolicyTarget{MAC: "02:00:00:00:00:01"}} + var out, errb bytes.Buffer + inv := &Invocation{} + inv.SetOutputFormat(format.FormatJSON) + if code := RenderFatal(inv, e, &out, &errb, false); code != errs.ExitPolicyDenied || + !strings.Contains(out.String(), `"block": "IP/Parameter"`) || !strings.Contains(out.String(), `"target": { + "mac": "02:00:00:00:00:01" + }`) || strings.Contains(out.String(), `"record"`) { + t.Fatalf("json: %d\n%s", code, out.String()) + } +} + func TestFormatArg(t *testing.T) { for _, c := range []struct { args []string diff --git a/scripts/examples.sh b/scripts/examples.sh index 1ce21bf..4d28c99 100755 --- a/scripts/examples.sh +++ b/scripts/examples.sh @@ -184,6 +184,8 @@ ex identify -s nobody --wait 500ms -o json ex reset -s otf-b ex reset -s otf-b --confirm otf-a ex reset -s otf-b --mode communication --confirm otf-b +ex record read -s otf-a --index 0xAFF0 --allow-operation read-implicit --allow-read-index 0xF000-0xF0FF +ex signal -s otf-a --allow-nothing -o json ex version mv "$OUT.tmp" "$OUT"