diff --git a/.changes/PRODENG-3922.md b/.changes/PRODENG-3922.md new file mode 100644 index 000000000..c4138bfdd --- /dev/null +++ b/.changes/PRODENG-3922.md @@ -0,0 +1,5 @@ +**The log file no longer records Trace and Debug output unless you ask for it.** Launchpad writes a log for every run to `~/.mirantis-launchpad/cluster//*.log`. Until now that file received every record at every level, including Trace, whatever flags were passed. It now receives Info and above by default; pass `--debug` to include Debug records, or `--trace` to include both. Terminal output is unchanged. + +The reason for the change is what those records contained. Trace and Debug carry the commands launchpad runs on each host and their output, and several of those carried credentials that redaction was failing to mask — so the values were not merely shown once on a terminal, they were written to a file on every run and kept. The masking gaps are fixed alongside this, but a persistent file holding every Trace record is a standing exposure on its own, and nothing was asking for it. + +If you collect launchpad logs for support or for an incident review, add `--debug` to the run, or `--trace` for the fullest output. diff --git a/pkg/config/config.go b/pkg/config/config.go index 380b03384..8e3eefa9a 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -6,7 +6,6 @@ import ( "io" "os" "path/filepath" - "regexp" "strings" "github.com/Mirantis/launchpad/pkg/config/migration" @@ -30,6 +29,7 @@ import ( _ "github.com/Mirantis/launchpad/pkg/config/migration/v1beta3" "github.com/Mirantis/launchpad/pkg/product" "github.com/Mirantis/launchpad/pkg/product/mke" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/a8m/envsubst" "github.com/k0sproject/rig/v2/cmd" log "github.com/sirupsen/logrus" @@ -83,8 +83,7 @@ func ProductFromYAML(data []byte) (product.Product, error) { //nolint:ireturn cfg := string(plain) if !cmd.DisableRedact { - re := regexp.MustCompile(`(username|password)([:= ]) ?\S+`) - cfg = re.ReplaceAllString(cfg, "$1$2[REDACTED]") + cfg = redactConfigDump(plain) } log.Debugf("loaded configuration:\n%s", cfg) @@ -105,6 +104,32 @@ func ProductFromYAML(data []byte) (product.Product, error) { //nolint:ireturn } } +// redactConfigDump masks credentials in the configuration before it is +// written to the debug log, which persists to disk. +// +// A configuration that fails to parse is still dumped, because a debug dump +// of a broken configuration is exactly when the output is wanted. It gets +// redact.Text instead of redact.YAML: the same key set and the same +// environment-variable fragments, applied line by line rather than over a +// parsed structure. +// +// The difference is stated in the log line rather than left for the reader +// to infer. redact.Text cannot see a credential that is not on the same +// line as its key -- a YAML block scalar holding a private key is the case +// that matters -- so the output is masked on a best-effort basis and an +// operator deciding whether to attach it to a ticket needs to know which of +// the two they are looking at. +func redactConfigDump(plain []byte) string { + masked, err := redact.YAML(plain) + if err == nil { + return string(masked) + } + + log.Warnf("configuration could not be parsed for redaction (%s); the dump below is masked line by line on a best-effort basis and may still contain credentials that span lines", err) + + return string(redact.Text(plain)) +} + var errUnknownConfigKind = errors.New("unknown configuration kind") // Init returns an example cluster configuration. diff --git a/pkg/config/redact_dump_test.go b/pkg/config/redact_dump_test.go new file mode 100644 index 000000000..5c52eaa49 --- /dev/null +++ b/pkg/config/redact_dump_test.go @@ -0,0 +1,68 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// The regex this replaced was case sensitive and matched neither the +// schema's camelCase keys nor the inline data fields, so a configuration +// dumped to the log carried the admin password in clear. +func TestRedactConfigDumpMasksSchemaKeys(t *testing.T) { + dump := redactConfigDump([]byte(`apiVersion: launchpad.mirantis.com/mke/v1.6 +kind: mke +spec: + hosts: + - winRM: + address: 10.0.0.1 + password: fake-host-password + role: manager + environment: + REGISTRY_TOKEN: fake-registry-token + mke: + adminUsername: fake-admin-user + adminPassword: fake-admin-password + keyData: fake-key-material +`)) + + for _, secret := range []string{ + "fake-host-password", + "fake-registry-token", + "fake-admin-user", + "fake-admin-password", + "fake-key-material", + } { + require.NotContainsf(t, dump, secret, "the config dump leaked %q:\n%s", secret, dump) + } + + require.Contains(t, dump, "10.0.0.1", "non-credential configuration must survive, or the dump is useless") +} + +// A configuration that cannot be parsed is still dumped, because a debug +// dump of a broken configuration is exactly when the output is wanted. The +// masking it gets is line oriented rather than structural, but it covers +// the same key set, so camelCase schema keys and credential-named +// environment variables are masked there too. +func TestRedactConfigDumpFallsBackOnUnparseableInput(t *testing.T) { + dump := redactConfigDump([]byte( + "spec:\n hosts:\n - broken\n\tpassword: fake-host-password\n" + + "\tadminPassword: fake-admin-password\n" + + "\tREGISTRY_TOKEN: fake-registry-token\n")) + + for _, secret := range []string{"fake-host-password", "fake-admin-password", "fake-registry-token"} { + require.NotContainsf(t, dump, secret, "the fallback left %q in an unparseable config dump:\n%s", secret, dump) + } +} + +// The fallback's real limit, and the reason the log line calls it +// best-effort: it works a line at a time, so a credential in a block scalar +// is not masked. The parsed path has no such gap. This pins the boundary so +// that nobody reads the two as equivalent. +func TestRedactConfigDumpFallbackCannotSeeBlockScalars(t *testing.T) { + dump := redactConfigDump([]byte( + "spec:\n mke:\n - broken\n\tkeyData: |\n\t fake-key-line-one\n\t fake-key-line-two\n")) + + require.Contains(t, dump, "fake-key-line-one", + "if this now masks, the fallback gained multi-line coverage and the log line's wording should be revisited") +} diff --git a/pkg/configurer/linux.go b/pkg/configurer/linux.go index c9cc471dd..71f5ead93 100644 --- a/pkg/configurer/linux.go +++ b/pkg/configurer/linux.go @@ -13,6 +13,7 @@ import ( "github.com/Mirantis/launchpad/pkg/constant" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" "github.com/Mirantis/launchpad/pkg/util/iputil" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/k0sproject/rig/v2/cmd" rigos "github.com/k0sproject/rig/v2/os" "github.com/k0sproject/rig/v2/remotefs" @@ -417,17 +418,28 @@ func (c LinuxConfigurer) AuthorizeDocker(h Host) error { // AuthenticateDocker performs a docker login on the host. func (c LinuxConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo string) error { - dc := c.DockerCmd() - loginCmd := dc.Raw("login -u").Arg(user).Raw("--password-stdin").Arg(imageRepo).String() - // The username reaches the command line quoted; the password only goes in - // over stdin. Patterns are built from both forms so redaction matches - // whichever one is logged. - if err := h.Exec(loginCmd, - cmd.StdinString(pass), - cmd.Redact(regexp.QuoteMeta(dc.Quote(user))), - cmd.Redact(regexp.QuoteMeta(user)), - cmd.Redact(regexp.QuoteMeta(pass)), - ); err != nil { + dockerCmd := c.DockerCmd() + loginCmd := dockerCmd.Raw("login -u").Arg(user).Raw("--password-stdin").Arg(imageRepo).String() + // The username reaches the command line quoted; the password only goes + // in over stdin. Both forms are listed because rig matches redactions + // literally -- cmd/execoptions.go RedactString is strings.ReplaceAll -- + // so a redaction has to be the exact text that appears in the log, and + // the quoting changes that text. regexp.QuoteMeta must not be applied: + // it escapes the value into a spelling that never occurs, which fails + // silently for any value containing a regex metacharacter. + // + // Longest first: rig replaces each value in turn, so a username that is + // a prefix of the password would otherwise be substituted first and + // leave the rest of the password in the log. + values := redact.ByLengthDesc(dockerCmd.Quote(user), user, pass) + opts := make([]cmd.ExecOption, 0, len(values)+1) + opts = append(opts, cmd.StdinString(pass)) + + for _, value := range values { + opts = append(opts, cmd.Redact(value)) + } + + if err := h.Exec(loginCmd, opts...); err != nil { return fmt.Errorf("failed to login to the docker registry: %w", err) } return nil diff --git a/pkg/configurer/redaction_semantics_test.go b/pkg/configurer/redaction_semantics_test.go new file mode 100644 index 000000000..23a122675 --- /dev/null +++ b/pkg/configurer/redaction_semantics_test.go @@ -0,0 +1,58 @@ +package configurer_test + +import ( + "regexp" + "testing" + + rigcmd "github.com/k0sproject/rig/v2/cmd" + "github.com/stretchr/testify/require" +) + +// TestRigRedactionIsLiteral pins how rig treats the values passed to +// cmd.Redact, at the version go.mod resolves to. +// +// Launchpad's redaction sites depend on two properties that are not visible +// from the call site and that both plausible readings of the API get wrong in +// opposite directions: +// +// - the values are matched literally, not as regular expressions, so +// wrapping a credential in regexp.QuoteMeta produces a spelling that +// never appears in the output. That failure is invisible in testing, +// because QuoteMeta is the identity function for alphanumerics: only a +// credential containing a regex metacharacter exposes it. +// - repeated cmd.Redact options compose rather than overwrite, so a call +// site may list the raw and the shell-quoted form of the same value. +// +// Neither property is safe to assume from reading the API: rig's v1 Redact +// compiled a regexp, so the opposite was once true. This branch was written +// against a fork of rig and these tests passed there; they pass unchanged +// against upstream v2.2.1, which launchpad now builds on (#707). If a future +// bump changes the semantics, this fails rather than the redaction silently +// doing nothing. +func TestRigRedactionIsLiteral(t *testing.T) { + t.Parallel() + + const password = `p$ss.w*rd` + + opts := rigcmd.Build(rigcmd.Redact(password)) + require.Equal(t, "login -p "+rigcmd.DefaultRedactMask, opts.RedactString("login -p "+password), + "a credential containing regex metacharacters must be matched literally") + + // The same value escaped for a regex matcher is not what appears in the + // command, so it redacts nothing. This is the defect the production + // sites had. + escaped := rigcmd.Build(rigcmd.Redact(regexp.QuoteMeta(password))) + require.Equal(t, "login -p "+password, escaped.RedactString("login -p "+password), + "regexp.QuoteMeta must not be applied to a value handed to cmd.Redact") +} + +func TestRigRedactionsCompose(t *testing.T) { + t.Parallel() + + opts := rigcmd.Build(rigcmd.Redact("alice"), rigcmd.Redact("hunter2")) + + got := opts.RedactString("login -u alice -p hunter2") + + require.NotContains(t, got, "alice", "an earlier cmd.Redact must not be discarded by a later one") + require.NotContains(t, got, "hunter2") +} diff --git a/pkg/configurer/windows.go b/pkg/configurer/windows.go index b49e1a303..43d045904 100644 --- a/pkg/configurer/windows.go +++ b/pkg/configurer/windows.go @@ -14,6 +14,7 @@ import ( "github.com/Mirantis/launchpad/pkg/constant" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" "github.com/Mirantis/launchpad/pkg/util/iputil" + "github.com/Mirantis/launchpad/pkg/util/redact" "github.com/avast/retry-go" "github.com/hashicorp/go-version" "github.com/k0sproject/rig/v2/cmd" @@ -423,16 +424,26 @@ func (c WindowsConfigurer) CheckPrivilege(h Host) error { // AuthenticateDocker performs a docker login on the host. func (c WindowsConfigurer) AuthenticateDocker(h Host, user, pass, imageRepo string) error { // the --pasword-stdin seems to hang in windows - dc := c.DockerCmd() - loginCmd := dc.Raw("login -u").Arg(user).Raw("-p").Arg(pass).Arg(imageRepo).String() - // The command line holds the quoted forms, so patterns built from the raw - // values would not match once quoting alters them. - redactions := []cmd.ExecOption{ - cmd.Redact(regexp.QuoteMeta(dc.Quote(pass))), - cmd.Redact(regexp.QuoteMeta(dc.Quote(user))), - cmd.Redact(regexp.QuoteMeta(pass)), - cmd.Redact(regexp.QuoteMeta(user)), - cmd.AllowWinStderr(), + dockerCmd := c.DockerCmd() + loginCmd := dockerCmd.Raw("login -u").Arg(user).Raw("-p").Arg(pass).Arg(imageRepo).String() + // The command line holds the quoted forms, so the raw values alone + // would not match once quoting alters them; both forms are listed. + // rig matches redactions literally (cmd/execoptions.go RedactString is + // strings.ReplaceAll), so each value must be the exact text that + // appears in the log. regexp.QuoteMeta must not be applied: it escapes + // the value into a spelling that never occurs, and because QuoteMeta is + // the identity function for alphanumerics the failure is invisible + // until a password contains a metacharacter. + // + // Longest first: rig replaces each value in turn, so a username that is + // a prefix of the password would otherwise be substituted first and + // leave the rest of the password in the log. + values := redact.ByLengthDesc(dockerCmd.Quote(pass), dockerCmd.Quote(user), pass, user) + redactions := make([]cmd.ExecOption, 0, len(values)+1) + redactions = append(redactions, cmd.AllowWinStderr()) + + for _, value := range values { + redactions = append(redactions, cmd.Redact(value)) } if err := h.Exec(loginCmd, redactions...); err != nil { return fmt.Errorf("failed to login to docker registry: %w", err) diff --git a/pkg/log/file_hook_test.go b/pkg/log/file_hook_test.go new file mode 100644 index 000000000..47c3f9356 --- /dev/null +++ b/pkg/log/file_hook_test.go @@ -0,0 +1,73 @@ +package log_test + +import ( + "os" + "path/filepath" + "testing" + + mcclog "github.com/Mirantis/launchpad/pkg/log" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/require" +) + +// logThrough writes one record at each level through a logger carrying only +// the file hook, and returns what reached the file. +func logThrough(t *testing.T, message string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "launchpad.log") + + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) + require.NoError(t, err) + + logger := logrus.New() + logger.SetLevel(logrus.TraceLevel) + logger.SetOutput(os.NewFile(0, os.DevNull)) + logger.AddHook(mcclog.NewFileHook(file)) + + logger.Trace(message) + logger.Debug(message) + logger.Info("install started") + + require.NoError(t, file.Close()) + + contents, err := os.ReadFile(path) + require.NoError(t, err) + + return string(contents) +} + +// The log file is written for every run and kept on disk, so a credential in +// a Trace record outlives the terminal it would have scrolled past. Trace and +// Debug records reach it only when the operator asked for them. +func TestFileHookPersistsTraceOnlyWhenRequested(t *testing.T) { + const credential = "fake-admin-password" + + t.Run("default", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = false, false + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "docker login -p "+credential) + + require.NotContains(t, got, credential, "a trace record reached the log file without --debug or --trace") + require.Contains(t, got, "install started", "the file must still carry the records it is read for") + }) + + t.Run("debug", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = true, false + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "debug record") + + require.Contains(t, got, "debug record") + }) + + t.Run("trace", func(t *testing.T) { + mcclog.Debug, mcclog.Trace = true, true + t.Cleanup(func() { mcclog.Debug, mcclog.Trace = false, false }) + + got := logThrough(t, "trace record") + + require.Contains(t, got, "trace record") + }) +} diff --git a/pkg/log/formatter_hook.go b/pkg/log/formatter_hook.go index 05b5e05e8..c8b654a1a 100644 --- a/pkg/log/formatter_hook.go +++ b/pkg/log/formatter_hook.go @@ -67,17 +67,41 @@ func NewStdoutHook() *FormatterWriterHook { return stdoutHook } -// NewFileHook creates logrus hook for logging all levels to file. +// NewFileHook creates a logrus hook for logging to file. +// +// The file is persistent, so the levels it receives are not log.AllLevels. +// Trace and Debug records carry remote command lines and their output, and +// the file is written for every run regardless of flags, so an unredacted +// value in a Trace record outlives the terminal it would otherwise have +// scrolled past. Trace is written only with --trace and Debug only with +// --debug; without either, the file holds Info and above, which is what it +// is read for. See PRODENG-3922. func NewFileHook(logFile *os.File) *FormatterWriterHook { fileFormatter := &log.TextFormatter{ DisableColors: true, FullTimestamp: true, TimestampFormat: time.RFC822, } + + levels := []log.Level{ + log.PanicLevel, + log.FatalLevel, + log.ErrorLevel, + log.WarnLevel, + log.InfoLevel, + } + + switch { + case Trace: + levels = append(levels, log.DebugLevel, log.TraceLevel) + case Debug: + levels = append(levels, log.DebugLevel) + } + fileHook := &FormatterWriterHook{ Writer: logFile, Formatter: fileFormatter, - LogLevels: log.AllLevels, + LogLevels: levels, } return fileHook diff --git a/pkg/mke/mke.go b/pkg/mke/mke.go index 51fe64e8e..7e49965e6 100644 --- a/pkg/mke/mke.go +++ b/pkg/mke/mke.go @@ -160,7 +160,13 @@ func GetTLSConfigFrom(manager *mkeconfig.Host, imageRepo, mkeVersion string) (*t if manager.Configurer.SELinuxEnabled(manager) { runFlags.Add("--security-opt label=disable") } - output, err := manager.ExecOutput(manager.Configurer.DockerCmd().Raw("run").Raw(runFlags.Join()).Arg(fmt.Sprintf("%s/ucp:%s", imageRepo, mkeVersion)).Raw("dump-certs --ca").String(), rigcmd.Redact(`[A-Za-z0-9+/=_\-]{64}`)) + // The CA PEM is the command's output and is not known here, so it + // cannot be given to rigcmd.Redact, which matches literally. The + // previous `[A-Za-z0-9+/=_\-]{64}` was a regex handed to that literal + // matcher: it looked for that pattern as a literal string, matched + // nothing, and the certificate was logged in full. The output is + // returned to the caller, so hiding it from the log costs nothing. + output, err := manager.ExecOutput(manager.Configurer.DockerCmd().Raw("run").Raw(runFlags.Join()).Arg(fmt.Sprintf("%s/ucp:%s", imageRepo, mkeVersion)).Raw("dump-certs --ca").String(), rigcmd.HideOutput()) if err != nil { return nil, fmt.Errorf("%w: error while exec-ing into the container: %w", errGetTLSConfig, err) } diff --git a/pkg/product/mke/phase/init_swarm.go b/pkg/product/mke/phase/init_swarm.go index 8e26d8e2c..fc7300752 100644 --- a/pkg/product/mke/phase/init_swarm.go +++ b/pkg/product/mke/phase/init_swarm.go @@ -26,7 +26,16 @@ func (p *InitSwarm) Run() error { if !swarm.IsSwarmNode(swarmLeader) { log.Infof("%s: initializing swarm", swarmLeader) - err := swarmLeader.Exec(swarmLeader.Configurer.DockerCmd().Raw("swarm init").Arg(fmt.Sprintf("--advertise-addr=%s", swarmLeader.SwarmAddress())).Raw(p.Config.Spec.MCR.SwarmInstallFlags.Join()).String(), cmd.Redact(`--token \S+`)) + // The worker join token is printed by "swarm init" itself, in the + // "docker swarm join --token ..." line of its output, so the value + // is not known here and cannot be given to cmd.Redact, which + // matches literally. The previous `--token \S+` pattern was a + // regex handed to that literal matcher and never matched anything, + // leaving the token in the log of every cluster initialisation. + // The output carries nothing else of use -- the tokens are read + // back with "swarm join-token" when they are needed -- so it is + // kept out of the log entirely. + err := swarmLeader.Exec(swarmLeader.Configurer.DockerCmd().Raw("swarm init").Arg(fmt.Sprintf("--advertise-addr=%s", swarmLeader.SwarmAddress())).Raw(p.Config.Spec.MCR.SwarmInstallFlags.Join()).String(), cmd.HideOutput()) if err != nil { return fmt.Errorf("failed to initialize swarm: %w", err) } diff --git a/pkg/product/mke/phase/msr_redactions.go b/pkg/product/mke/phase/msr_redactions.go new file mode 100644 index 000000000..845a786ed --- /dev/null +++ b/pkg/product/mke/phase/msr_redactions.go @@ -0,0 +1,85 @@ +package phase + +import ( + commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + "github.com/Mirantis/launchpad/pkg/util/redact" + "github.com/k0sproject/rig/v2/sh/shellescape" +) + +// msrCredentialFlags are the MSR bootstrapper flags whose values are +// credentials and which launchpad puts on the command line. +var msrCredentialFlags = []string{"--ucp-username", "--ucp-password"} + +// msrCredentialRedactions returns the literal strings to keep out of the log +// for an MSR bootstrapper invocation, longest first. +// +// Three spellings of the same credential can reach the log and each has to +// be registered separately, because rig matches literally: +// +// - the rendered form, which is what BuildMKEFlags wrote into the flag +// list and what appears in the command line. BuildMKEFlags shell-quotes +// it, so for a password containing a quote this is not the password. +// - the shell-decoded form, which is the password itself. It reaches the +// log if the bootstrapper echoes it back in its own output. +// - the two-element form, where a flag and its value are separate entries +// in the list. Flags.Join concatenates them into a working command, but +// Flags.Get returns only the flag, so the value has to be read from the +// following element or it is never registered at all. +// +// Ordering matters as much as coverage: rig replaces each value in turn, so +// a username that is a prefix of the password must not be substituted +// first. redact.ByLengthDesc removes that dependence on order. +func msrCredentialRedactions(flags commonconfig.Flags) []string { + var values []string + + for _, name := range msrCredentialFlags { + for _, rendered := range renderedFlagValues(flags, name) { + values = append(values, rendered) + + if decoded, err := shellescape.Unquote(rendered); err == nil && decoded != rendered { + values = append(values, decoded) + } + } + } + + return redact.ByLengthDesc(values...) +} + +// renderedFlagValues returns every value the named flag carries in the list, +// covering both "--flag value" or "--flag=value" in one element and a bare +// "--flag" whose value is the next element. +func renderedFlagValues(flags commonconfig.Flags, name string) []string { + var rendered []string + + for i, flag := range flags { + if flag == name { + if i+1 < len(flags) && !isFlagToken(flags[i+1]) { + rendered = append(rendered, flags[i+1]) + } + + continue + } + + if !isFlagWithValue(flag, name) { + continue + } + + if value := flag[len(name)+1:]; value != "" { + rendered = append(rendered, value) + } + } + + return rendered +} + +func isFlagWithValue(flag, name string) bool { + if len(flag) <= len(name) || flag[:len(name)] != name { + return false + } + + return flag[len(name)] == '=' || flag[len(name)] == ' ' +} + +func isFlagToken(value string) bool { + return len(value) > 0 && value[0] == '-' +} diff --git a/pkg/product/mke/phase/msr_redactions_test.go b/pkg/product/mke/phase/msr_redactions_test.go new file mode 100644 index 000000000..b302a5e81 --- /dev/null +++ b/pkg/product/mke/phase/msr_redactions_test.go @@ -0,0 +1,65 @@ +package phase + +import ( + "testing" + + commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + rigcmd "github.com/k0sproject/rig/v2/cmd" + "github.com/stretchr/testify/require" +) + +// mask applies the values the way rig does, through the real code path. +func mask(values []string, rendered string) string { + opts := make([]rigcmd.ExecOption, 0, len(values)) + for _, value := range values { + opts = append(opts, rigcmd.Redact(value)) + } + + return rigcmd.Build(opts...).RedactString(rendered) +} + +// BuildMKEFlags shell-quotes the credential, so the command line holds the +// quoted spelling while the bootstrapper's own output may echo the raw one. +// Both have to be registered, because rig matches literally. +func TestMSRCredentialRedactionsCoverQuotedAndRawForms(t *testing.T) { + const password = `p@ss'w0rd` + + flags := commonconfig.Flags{`--ucp-username 'admin'`, `--ucp-password 'p@ss'"'"'w0rd'`} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr install "+flags.Join()), "w0rd", + "the rendered command still shows the password") + require.NotContains(t, mask(values, "authentication failed for "+password), "w0rd", + "the raw password still shows where the bootstrapper echoes it") +} + +// Flags.Join concatenates the list, so a flag and its value in separate +// elements form a working command. Flags.Get returns only the flag, so the +// value has to be read from the next element or it is never redacted. +func TestMSRCredentialRedactionsCoverTwoElementForm(t *testing.T) { + flags := commonconfig.Flags{"--ucp-password", "split-secret", "--ucp-node", "host-1"} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr upgrade "+flags.Join()), "split-secret") +} + +// rig replaces each registered value in turn, so a username that is a +// prefix of the password must not be substituted first: doing so destroys +// the longer match and leaves the rest of the password in the log. +func TestMSRCredentialRedactionsOrderLongestFirst(t *testing.T) { + flags := commonconfig.Flags{"--ucp-username admin", "--ucp-password admin!s3cr3t"} + + values := msrCredentialRedactions(flags) + + require.NotContains(t, mask(values, "dtr install "+flags.Join()), "s3cr3t") +} + +// A flag that carries no value registers nothing: an empty redaction would +// match at every position and blank the whole output. +func TestMSRCredentialRedactionsIgnoreValuelessFlags(t *testing.T) { + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-password", "--ucp-node host-1"})) + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-password="})) + require.Empty(t, msrCredentialRedactions(commonconfig.Flags{"--ucp-node host-1"})) +} diff --git a/pkg/product/mke/phase/upgrade_msr.go b/pkg/product/mke/phase/upgrade_msr.go index 3969b85d6..1105fa34b 100644 --- a/pkg/product/mke/phase/upgrade_msr.go +++ b/pkg/product/mke/phase/upgrade_msr.go @@ -7,6 +7,7 @@ import ( "github.com/Mirantis/launchpad/pkg/msr" "github.com/Mirantis/launchpad/pkg/phase" commonconfig "github.com/Mirantis/launchpad/pkg/product/common/config" + "github.com/k0sproject/rig/v2/cmd" "github.com/k0sproject/rig/v2/sh/shellescape" log "github.com/sirupsen/logrus" ) @@ -50,7 +51,16 @@ func (p *UpgradeMSR) Run() error { } upgradeFlags.MergeOverwrite(p.Config.Spec.MSR.UpgradeFlags) - if _, err := msr.Bootstrap("upgrade", *p.Config, msr.BootstrapOptions{OperationFlags: upgradeFlags, CleanupDisabled: p.CleanupDisabled()}); err != nil { + // BuildMKEFlags puts --ucp-username and --ucp-password on the command + // line, so the values are redacted out of the log in both the form + // BuildMKEFlags writes and the raw form. PRODENG-3923 removes them from + // the command line entirely, after which these are no-ops. + execOpts := make([]cmd.ExecOption, 0, len(msrCredentialRedactions(upgradeFlags))) + for _, value := range msrCredentialRedactions(upgradeFlags) { + execOpts = append(execOpts, cmd.Redact(value)) + } + + if _, err := msr.Bootstrap("upgrade", *p.Config, msr.BootstrapOptions{OperationFlags: upgradeFlags, CleanupDisabled: p.CleanupDisabled(), ExecOptions: execOpts}); err != nil { return fmt.Errorf("%s: failed to run MSR upgrader: %w", h, err) } diff --git a/pkg/util/redact/values.go b/pkg/util/redact/values.go new file mode 100644 index 000000000..a9cc97dc5 --- /dev/null +++ b/pkg/util/redact/values.go @@ -0,0 +1,75 @@ +package redact + +import ( + "fmt" + "regexp" + "sort" + "strings" +) + +// ByLengthDesc orders redaction values longest first and drops empty ones. +// +// rig replaces each registered value in turn with strings.ReplaceAll, so a +// value that is a prefix of another destroys the longer match before it is +// tried: with the username "admin" and the password "admin!s3cr3t" +// registered in that order, the password is rewritten to "[REDACTED]!s3cr3t" +// and the distinctive part of it survives in the log. Registering the +// longest value first removes the dependence on registration order. +// +// An empty value is dropped because it would otherwise match at every +// position; rig skips empty matches too, but a caller should not rely on +// that. +func ByLengthDesc(values ...string) []string { + ordered := make([]string, 0, len(values)) + + for _, value := range values { + if value != "" { + ordered = append(ordered, value) + } + } + + sort.SliceStable(ordered, func(i, j int) bool { + return len(ordered[i]) > len(ordered[j]) + }) + + return ordered +} + +// fallbackPattern matches "" on one line, +// case insensitively, for every key in the sensitive set. It is built from +// the same key set as the structured redaction so the two cannot drift. +var fallbackPattern = buildFallbackPattern() + +func buildFallbackPattern() *regexp.Regexp { + keys := make([]string, 0, len(sensitiveKeys)) + for key := range sensitiveKeys { + keys = append(keys, regexp.QuoteMeta(key)) + } + + sort.Strings(keys) + + // Also catch the environment-variable spellings, which are matched by + // fragment in the structured path and cannot be enumerated here. + fragments := make([]string, 0, len(envSecretFragments)) + for _, fragment := range envSecretFragments { + fragments = append(fragments, `[A-Za-z0-9_]*`+regexp.QuoteMeta(fragment)+`[A-Za-z0-9_]*`) + } + + return regexp.MustCompile(`(?im)^(\s*-?\s*(?:` + strings.Join(keys, "|") + "|" + strings.Join(fragments, "|") + `)\s*[:=]\s*).+$`) +} + +// Text masks credentials in a document that could not be parsed. +// +// This is a best-effort fallback for YAML that fails to load: it is line +// oriented and key driven, so it cannot see a credential that is not on the +// same line as its key, and it masks whatever follows the separator without +// understanding the value. Callers that have a parseable document must use +// YAML, which walks the structure and knows where the credential-bearing +// keys actually are. +// +// It covers the same key set and the same environment-variable fragments as +// the structured path, case insensitively, so a configuration that fails to +// parse does not silently lose coverage the parsed one has. +func Text(doc []byte) []byte { + return fallbackPattern.ReplaceAll(doc, []byte(fmt.Sprintf("${1}%s", Placeholder))) +}