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
5 changes: 5 additions & 0 deletions .changes/PRODENG-3922.md
Original file line number Diff line number Diff line change
@@ -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/<name>/*.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.
31 changes: 28 additions & 3 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"io"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/Mirantis/launchpad/pkg/config/migration"
Expand All @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down
68 changes: 68 additions & 0 deletions pkg/config/redact_dump_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
34 changes: 23 additions & 11 deletions pkg/configurer/linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
58 changes: 58 additions & 0 deletions pkg/configurer/redaction_semantics_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
31 changes: 21 additions & 10 deletions pkg/configurer/windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
73 changes: 73 additions & 0 deletions pkg/log/file_hook_test.go
Original file line number Diff line number Diff line change
@@ -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")
})
}
Loading
Loading