mirror of
https://github.com/restic/restic.git
synced 2026-12-04 15:44:46 +00:00
Merge pull request #22215 from MichaelEischer/better-debug-redact
Improve credentials redaction in debug log
This commit is contained in:
5 files changed
+163
-2
No files matched your search
+20
-2
@@ -17,6 +17,7 @@ import (
|
||||
"go.uber.org/automaxprocs/maxprocs"
|
||||
|
||||
"github.com/restic/restic/internal/backend/all"
|
||||
"github.com/restic/restic/internal/backend/location"
|
||||
"github.com/restic/restic/internal/debug"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/feature"
|
||||
@@ -178,6 +179,22 @@ func printExitError(globalOptions global.Options, code int, message string) {
|
||||
}
|
||||
}
|
||||
|
||||
// redactLoggedArgs heuristically hides repository passwords from the debug log.
|
||||
func redactLoggedArgs(args []string, registry *location.Registry) []string {
|
||||
redacted := make([]string, 0, len(args))
|
||||
for _, arg := range args {
|
||||
var cleaned string
|
||||
if flag, value, ok := strings.Cut(arg, "="); ok && strings.HasPrefix(flag, "-") {
|
||||
cleaned = flag + "=" + location.StripPassword(registry, value)
|
||||
} else {
|
||||
cleaned = location.StripPassword(registry, arg)
|
||||
}
|
||||
|
||||
redacted = append(redacted, cleaned)
|
||||
}
|
||||
return redacted
|
||||
}
|
||||
|
||||
func main() {
|
||||
tweakGoGC()
|
||||
// install custom global logger into a buffer, if an error occurs
|
||||
@@ -193,12 +210,13 @@ func main() {
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
debug.Log("main %#v", os.Args)
|
||||
backends := all.Backends()
|
||||
debug.Log("main %#v", redactLoggedArgs(os.Args, backends))
|
||||
debug.Log("restic %s compiled with %v on %v/%v",
|
||||
global.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
globalOptions := global.Options{
|
||||
Backends: all.Backends(),
|
||||
Backends: backends,
|
||||
}
|
||||
func() {
|
||||
term, cancel := termstatus.Setup(os.Stdin, os.Stdout, os.Stderr, globalOptions.Quiet)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/backend/all"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
)
|
||||
|
||||
func TestRedactLoggedArgs(t *testing.T) {
|
||||
registry := all.Backends()
|
||||
args := []string{
|
||||
"restic",
|
||||
"-r",
|
||||
"rest:https://user:secret@example.com/repo",
|
||||
"--repo=rest:https://user:secret@example.com/repo",
|
||||
"backup",
|
||||
"/srv/data",
|
||||
}
|
||||
copy := slices.Clone(args)
|
||||
got := redactLoggedArgs(args, registry)
|
||||
rtest.Equals(t, []string{
|
||||
"restic",
|
||||
"-r",
|
||||
"rest:https://user:***@example.com/repo/",
|
||||
"--repo=rest:https://user:***@example.com/repo/",
|
||||
"backup",
|
||||
"/srv/data",
|
||||
}, got)
|
||||
// ensure that the original arguments are not modified
|
||||
rtest.Equals(t, copy, args)
|
||||
}
|
||||
@@ -49,6 +49,9 @@ func ParseConfig(s string) (*Config, error) {
|
||||
// If the repository location cannot be parsed as a valid URL, it will be returned as is
|
||||
// (it's because this function is used for logging errors)
|
||||
func StripPassword(s string) string {
|
||||
if len(s) < 5 {
|
||||
return s
|
||||
}
|
||||
scheme := s[:5]
|
||||
s = prepareURL(s)
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/restic/restic/internal/errors"
|
||||
)
|
||||
@@ -67,6 +69,7 @@ func redactHeader(header http.Header) map[string][]string {
|
||||
"Authorization",
|
||||
"X-Auth-Token", // Swift headers
|
||||
"X-Auth-Key",
|
||||
"X-Amz-Security-Token", // Short-lived S3 tokens
|
||||
} {
|
||||
origHeader, hasHeader := header[hdr]
|
||||
if hasHeader {
|
||||
@@ -81,11 +84,48 @@ func restoreHeader(header http.Header, origHeaders map[string][]string) {
|
||||
maps.Copy(header, origHeaders)
|
||||
}
|
||||
|
||||
func secretQueryParam(key string) bool {
|
||||
switch strings.ToLower(key) {
|
||||
// "sig" contains the Azure SAS signature
|
||||
// "x-amz-signature" and "x-amz-security-token" could show up for
|
||||
// presigned s3 URLs although those aren't used at the moment
|
||||
case "sig", "x-amz-signature", "x-amz-security-token":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// redactRequestURL replaces secret query values. It assumes a well-formed query
|
||||
// string and as such does not preserve ordering and encoding.
|
||||
func redactRequestURL(u *url.URL) *url.URL {
|
||||
values := u.Query()
|
||||
changed := false
|
||||
for key, vals := range values {
|
||||
if !secretQueryParam(key) {
|
||||
continue
|
||||
}
|
||||
for i := range vals {
|
||||
vals[i] = "redacted"
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return u
|
||||
}
|
||||
clone := *u
|
||||
clone.RawQuery = values.Encode()
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (tr loggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
// save original auth and redact it
|
||||
origHeaders := redactHeader(req.Header)
|
||||
origURL := req.URL
|
||||
req.URL = redactRequestURL(req.URL)
|
||||
|
||||
trace, err := httputil.DumpRequestOut(req, false)
|
||||
req.URL = origURL
|
||||
if err != nil {
|
||||
Log("DumpRequestOut() error: %v\n", err)
|
||||
} else {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/test"
|
||||
@@ -12,12 +16,14 @@ func TestRedactHeader(t *testing.T) {
|
||||
"Authorization",
|
||||
"X-Auth-Token",
|
||||
"X-Auth-Key",
|
||||
"X-Amz-Security-Token",
|
||||
}
|
||||
|
||||
header := make(http.Header)
|
||||
header["Authorization"] = []string{"123"}
|
||||
header["X-Auth-Token"] = []string{"1234"}
|
||||
header["X-Auth-Key"] = []string{"12345"}
|
||||
header["X-Amz-Security-Token"] = []string{"session"}
|
||||
header["Host"] = []string{"my.host"}
|
||||
|
||||
origHeaders := redactHeader(header)
|
||||
@@ -31,6 +37,7 @@ func TestRedactHeader(t *testing.T) {
|
||||
test.Equals(t, "123", header["Authorization"][0])
|
||||
test.Equals(t, "1234", header["X-Auth-Token"][0])
|
||||
test.Equals(t, "12345", header["X-Auth-Key"][0])
|
||||
test.Equals(t, "session", header["X-Amz-Security-Token"][0])
|
||||
test.Equals(t, "my.host", header["Host"][0])
|
||||
|
||||
delete(header, "X-Auth-Key")
|
||||
@@ -42,3 +49,63 @@ func TestRedactHeader(t *testing.T) {
|
||||
_, hasHeader = header["X-Auth-Key"]
|
||||
test.Assert(t, !hasHeader, "Unexpected header: %v", header["X-Auth-Key"])
|
||||
}
|
||||
|
||||
func TestLoggingRoundTripperRedactsSecrets(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
oldLogger, oldEnabled := opts.logger, opts.isEnabled
|
||||
opts.logger = log.New(&buf, "", 0)
|
||||
opts.isEnabled = true
|
||||
t.Cleanup(func() {
|
||||
opts.logger = oldLogger
|
||||
opts.isEnabled = oldEnabled
|
||||
})
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "https://account.blob.core.windows.net/container?comp=list&sig=sas-secret&X-Amz-Signature=aws-secret&X-Amz-Security-Token=query-token", nil)
|
||||
test.OK(t, err)
|
||||
req.Header.Set("Authorization", "basic-secret")
|
||||
req.Header.Set("X-Amz-Security-Token", "header-token")
|
||||
|
||||
var sent *http.Request
|
||||
tr := loggingRoundTripper{RoundTripper: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = r.Clone(r.Context())
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{"X-Amz-Security-Token": []string{"response-token"}},
|
||||
Body: io.NopCloser(strings.NewReader("")),
|
||||
Request: r,
|
||||
}, nil
|
||||
})}
|
||||
|
||||
res, err := tr.RoundTrip(req)
|
||||
test.OK(t, err)
|
||||
defer func() {
|
||||
test.OK(t, res.Body.Close())
|
||||
}()
|
||||
test.Equals(t, "response-token", res.Header.Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "basic-secret", sent.Header.Get("Authorization"))
|
||||
test.Equals(t, "header-token", sent.Header.Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "sas-secret", sent.URL.Query().Get("sig"))
|
||||
test.Equals(t, "aws-secret", sent.URL.Query().Get("X-Amz-Signature"))
|
||||
test.Equals(t, "query-token", sent.URL.Query().Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "list", sent.URL.Query().Get("comp"))
|
||||
|
||||
logText := buf.String()
|
||||
for _, secret := range []string{"sas-secret", "aws-secret", "query-token", "header-token", "basic-secret", "response-token"} {
|
||||
test.Assert(t, !strings.Contains(logText, secret), "secret %q leaked into debug log: %s", secret, logText)
|
||||
}
|
||||
test.Assert(t, strings.Contains(logText, "sig=redacted"), "missing redacted sas: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Signature=redacted"), "missing redacted signature: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Security-Token=redacted"), "missing redacted query token: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "comp=list"), "ordinary query parameter was dropped: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Security-Token: **redacted**"), "missing redacted header: %s", logText)
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return f(r)
|
||||
}
|
||||
Reference in new issue
Block a user