Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3183,6 +3183,7 @@ and `[standing]` need a restart.
nodkey broker [--config FILE]
nodkey broker reload [--config FILE] [--timeout DURATION]
nodkey broker check [--config FILE] [--files DIR] [--credentials DIR]
nodkey broker config-diff [--short] [--max-chars N] OLD NEW
nodkey run [--secret VAR=NAME]... [--grant-token FILE] [--reason TEXT] [--mask | --no-mask] -- COMMAND [ARGS...]
nodkey ssh-agent [--socket PATH]
nodkey ssh-grant --key NAME --user USER --host NAME... --for DURATION [--reason TEXT]
Expand Down Expand Up @@ -3342,6 +3343,47 @@ of the output is cleaned with `claim.Line`, so text from the config
cannot add a line or change the terminal. It exits 0 when the config
passed, 1 with the reason when it did not, and 64 on wrong usage.

`nodkey broker config-diff OLD NEW` lists the changes from one config to
another by what they mean (issue #174), such as for the owner's
confirmation of a config change from git (#102). OLD and NEW are each a
config file, or a directory with `broker.toml` and `known_hosts` (as
`--files`). For a file, `known_hosts` is read from the directory of the
file, by its base name, never from the path in the config: two configs
that name one path would both read the live file, and a new host key
would not show. Both are read with the parser of the start
(`config.ReadBrokerFiles`); no other file is read, also no credential,
and no root or network is needed. `config.Diff` compares the two parsed
configs, so comments, order and spaces are no change, and a list of
clients or hosts is a set. Each change is one line, sorted by group
(the top keys and sections, clients, stores, secrets, SSH keys,
`known_hosts`) and name. A line that starts with `⚠` widens access or
weakens a control: a new client, secret, key, store or host; a new
client of a secret or a key; `ask` towards `never`; a longer `window`;
wider `hours`; a higher or no `max_per_day`; `notify` off (these three
are compared only between two `never` rules; a move to `never` shows
them on its line); more hosts,
or every host, for a key; `preapprove` or `standing` turned on; a new
`[standing]` or a higher limit in it or in `[preapprove]`; fewer
`warn_days`; any change of the approver, the notice chat, the channel,
the store's program, server or files, the item of a secret, the file of
a key, `listen`, `tls_key`, `audit_log`, the `known_hosts` path, the
`[standing]` summary time, or `[updates] check` turned off; a longer
timeout; a new host key. Any other change is a plain line only when the
code knows it narrows access. A field of the config that the code does
not compare by name is still compared (`unknown` in
`internal/config/diff.go`), and its change is marked as "a change that
config-diff does not know". A test fails when a field is in neither
list. Text from a config is quoted and each line cleaned with
`claim.Line`.

`--short` fits one Telegram message: at most `--max-chars` characters,
counted in UTF-16 code units as Telegram counts them (default 3500, from 200 to 100000). It puts the lines that widen first,
then the others, and cuts with "and N more". When the lines that widen
do not all fit, it gives one line instead: how many there are, and that
the full list must be read. It exits 0 when the configs mean the same, 1
when they differ, 2 when a config cannot be read or is not valid, and 64
on wrong usage.

The broker stops on SIGTERM or SIGINT, also during the start, when the polling
stops for good (section 7), when its server fails, and when a write to
stderr fails (a log line or an audit anchor), such as after the reader
Expand Down
9 changes: 9 additions & 0 deletions THREAT-MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -1498,6 +1498,15 @@ a check that needs a credential; the reload then keeps the old config.
The check is no part of what the broker trusts: the broker checks every
config again when it loads it.

`nodkey broker config-diff` (issue #174) shows the owner what a config
change means, before it is applied. Its risk is a change that widens
access but is shown as harmless. So it marks each change that it does
not know as narrowing, and a field of the config that it does not
compare by name is still compared and marked; a test fails when a field
is in neither list. The short form never drops a line that widens: when
they do not all fit, it says how many there are. It reads no credential.
It is no control of the broker: it only helps a person to decide.

## 7. Assumptions

- The broker host is patched, has no agent on it, and only the owner has
Expand Down
7 changes: 6 additions & 1 deletion cmd/nodkey/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ var errPanicked = errors.New("it panicked; the panic value is not logged")
const brokerUsage = `Usage: nodkey broker [--config FILE]
nodkey broker reload [--config FILE] [--timeout DURATION]
nodkey broker check [--config FILE] [--files DIR] [--credentials DIR]
nodkey broker config-diff [--short] [--max-chars N] OLD NEW

Run the broker: the daemon that holds the SSH keys and the access to the
secret stores. It asks the approver on Telegram before it hands out a
Expand All @@ -120,7 +121,8 @@ of the audit log. SIGTERM or SIGINT stops it. So does a failed write to
stderr, such as after its reader is gone: it stops with exit code 1.
SIGHUP reloads the config without a restart; see "nodkey broker reload
--help". To check a config without a start, see "nodkey broker check
--help".
--help". To list the changes between two configs by what they mean, see
"nodkey broker config-diff --help".

Exit codes: 0 stopped by SIGTERM or SIGINT, 1 any other error, 64 wrong
usage, 76 Telegram reports a polling conflict: the bot token may be
Expand All @@ -137,6 +139,9 @@ func runBroker(args []string, stdout, stderr io.Writer) int {
if len(args) > 0 && args[0] == "check" {
return runBrokerCheck(args[1:], stdout, stderr)
}
if len(args) > 0 && args[0] == "config-diff" {
return runConfigDiff(args[1:], stdout, stderr)
}
// A broken stderr must not end the broker with SIGPIPE in the middle
// of a line: the write fails instead, and the broker stops in its
// order (issue #73).
Expand Down
176 changes: 176 additions & 0 deletions cmd/nodkey/configdiff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package main

import (
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"unicode/utf16"

"github.com/code6x/nodkey/internal/claim"
"github.com/code6x/nodkey/internal/config"
"github.com/code6x/nodkey/internal/doctor"
)

const configDiffUsage = `Usage: nodkey broker config-diff [--short] [--max-chars N] OLD NEW

List the changes from the broker config OLD to NEW by what they mean:
who gets which secret or SSH key, and with or without a tap. Comments,
order and spaces are not changes. Each change that widens access or
weakens a control starts with a warning sign (⚠). So does each change
that config-diff does not know as one that narrows access.

OLD and NEW are each a config file, with the known_hosts that it uses
next to it (by the base name of its path in the config), or a directory
with broker.toml and known_hosts (as "nodkey broker check --files DIR"). It reads no
credential, needs no root, and uses no network.

--short print a short form that fits one Telegram message: the
changes that widen access first, then the rest, cut with
"and N more"
--max-chars N the most characters of the short form (default 3500)

Exit codes: 0 the configs mean the same, 1 they differ, 2 a file cannot
be read or is not a valid config, 64 wrong usage.
`

// exitDiffUnreadable is the exit code of nodkey broker config-diff when
// a config cannot be read.
const exitDiffUnreadable = 2

// runConfigDiff runs nodkey broker config-diff (issue #174).
func runConfigDiff(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("nodkey broker config-diff", flag.ContinueOnError)
fs.SetOutput(io.Discard)
short := fs.Bool("short", false, "the short form")
maxChars := fs.Int("max-chars", 3500, "the most characters of the short form")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
_, _ = io.WriteString(stdout, configDiffUsage)
return exitOK
}
return parseErrorCode(stderr, "broker config-diff", err)
}
if fs.NArg() != 2 {
return usageFail(stderr, "broker config-diff", "give OLD and NEW, each a config file or a directory, "+
"after the options")
}
if *maxChars < minShortChars || *maxChars > 100000 {
return usageFail(stderr, "broker config-diff", fmt.Sprintf("--max-chars must be from %d to 100000", minShortChars))
}
// ${CREDENTIALS_DIRECTORY} stands for the directory of the unit. No
// file in it is read; only the paths are compared.
if err := os.Setenv("CREDENTIALS_DIRECTORY", "/run/credentials/"+doctor.Unit); err != nil {
_, _ = fmt.Fprintf(stderr, "nodkey broker config-diff: cannot set CREDENTIALS_DIRECTORY: %s\n", err)
return exitDiffUnreadable
}
var cfgs [2]*config.Broker
for i, arg := range fs.Args() {
cfg, err := readDiffArg(arg)
if err != nil {
_, _ = fmt.Fprintf(stderr, "nodkey broker config-diff: %s: %s; %s\n", [2]string{"OLD", "NEW"}[i],
claim.Line(err.Error(), checkLineMax), claim.Line(diffArgHint(arg), checkLineMax))
return exitDiffUnreadable
}
cfgs[i] = cfg
}
changes := config.Diff(cfgs[0], cfgs[1])
if len(changes) == 0 {
_, _ = io.WriteString(stdout, "no change\n")
return exitOK
}
lines := make([]string, len(changes))
widens := make([]bool, len(changes))
for i, c := range changes {
c.Text = claim.Line(c.Text, checkLineMax)
lines[i], widens[i] = c.String(), c.Widens
}
if *short {
lines = shortForm(lines, widens, *maxChars)
}
_, _ = io.WriteString(stdout, strings.Join(lines, "\n")+"\n")
return exitFailure
}

// readDiffArg reads a config for config-diff: a file, or a directory
// with broker.toml and known_hosts. It uses the parser of the start
// (config.ReadBrokerFiles), without the checks of the other files.
func readDiffArg(arg string) (*config.Broker, error) {
fi, err := os.Stat(arg)
if err != nil {
return nil, err // a *fs.PathError names the path
}
if fi.IsDir() {
return config.ReadBrokerFiles(filepath.Join(arg, "broker.toml"), arg)
}
// known_hosts comes from the directory of the file, not from the path
// in the config: two configs that name the same path would otherwise
// both read the live file, and a new host key would not show.
return config.ReadBrokerFiles(arg, filepath.Dir(arg))
}

// diffArgHint says how to check the config arg that cannot be read.
func diffArgHint(arg string) string {
fi, err := os.Stat(arg)
switch {
case err != nil:
return "give a config file, or a directory with broker.toml and known_hosts, that exists"
case fi.IsDir():
return fmt.Sprintf("check it with nodkey broker check --files %q (docs/setup.md section 7)", arg)
}
return fmt.Sprintf("check it with nodkey broker check --config %q --files %q (docs/setup.md section 7)",
arg, filepath.Dir(arg))
}

// minShortChars is the smallest --max-chars: room for the line that says
// how many changes widen access.
const minShortChars = 200

// shortForm cuts lines to at most maxChars characters, with the lines
// that widen access first. When it cuts, the last line says how many
// lines are left out. When the lines that widen do not all fit, it gives
// none of them: one line says how many there are, and that the full list
// must be read.
func shortForm(lines []string, widens []bool, maxChars int) []string {
var wide, rest []string
for i, l := range lines {
if widens[i] {
wide = append(wide, l)
} else {
rest = append(rest, l)
}
}
all := append(append([]string(nil), wide...), rest...)
if size(all) <= maxChars {
return all
}
more := func(n int) string {
return fmt.Sprintf("and %d more; read the full list with nodkey broker config-diff OLD NEW", n)
}
if size(append(append([]string(nil), wide...), more(len(rest)))) > maxChars {
return []string{fmt.Sprintf("⚠ %d changes widen access, and they do not fit here; read the full "+
"list with nodkey broker config-diff OLD NEW (%d changes in all)", len(wide), len(lines))}
}
out := append([]string(nil), wide...)
for i, l := range rest {
next := append(append([]string(nil), out...), l, more(len(rest)-i-1))
if size(next) > maxChars {
return append(out, more(len(rest)-i))
}
out = append(out, l)
}
return out // not reached: all lines did not fit
}

// size is the number of characters of lines joined with line breaks, as
// Telegram counts them: in UTF-16 code units.
func size(lines []string) int {
n := 0
for _, l := range lines {
n += len(utf16.Encode([]rune(l))) + 1
}
return max(n-1, 0)
}
Loading
Loading