diff --git a/cmd/app/app.go b/cmd/app/app.go index db376bac..e539dad1 100644 --- a/cmd/app/app.go +++ b/cmd/app/app.go @@ -3,6 +3,7 @@ package app import ( "context" "fmt" + "net" "net/http" logrusr "github.com/bombsimon/logrusr/v4" @@ -62,6 +63,12 @@ func NewCommand(ctx context.Context) *cobra.Command { log.Warnf("flag --test-all-containers=%t %s", opts.DefaultTestAll, defaultTestAllInfoMsg) + if a := opts.PprofBindAddress; a != "" && a != "0" { + if h, _, err := net.SplitHostPort(a); err != nil || (h != "localhost" && !net.ParseIP(h).IsLoopback()) { + log.Warnf("pprof is unauthenticated and bound to %q: bind it to loopback", a) + } + } + mgr, err := ctrl.NewManager(restConfig, ctrl.Options{ LeaderElection: false, Metrics: server.Options{ diff --git a/cmd/app/options.go b/cmd/app/options.go index 9d0b7f12..9aa5f0c4 100644 --- a/cmd/app/options.go +++ b/cmd/app/options.go @@ -123,7 +123,7 @@ func (o *Options) addAppFlags(fs *pflag.FlagSet) { fs.StringVarP(&o.PprofBindAddress, "pprof-serving-address", "", "", - "Address to serve pprof on for profiling.") + "Address to serve pprof on for profiling. pprof is unauthenticated: bind to loopback (e.g. 127.0.0.1:6060).") fs.BoolVar(&o.Client.FallbackAllowPrivateHosts, "fallback-allow-private-hosts", false, diff --git a/pkg/controller/checker/checker.go b/pkg/controller/checker/checker.go index 01d43c31..9514cfec 100644 --- a/pkg/controller/checker/checker.go +++ b/pkg/controller/checker/checker.go @@ -53,7 +53,7 @@ func (c *Checker) Container(ctx context.Context, log *logrus.Entry, if opts.ResolveSHAToTags { - if len(*opts.OverrideURL) > 0 { + if opts.OverrideURL != nil && len(*opts.OverrideURL) > 0 { imageURL = *opts.OverrideURL } resolvedTag, err := c.search.ResolveSHAToTag(ctx, imageURL, currentSHA) @@ -166,6 +166,10 @@ func (c *Checker) isLatestSemver(ctx context.Context, imageURL, currentSHA strin return nil, false, err } + // latestImage is shared through the search cache: work on a copy. + img := *latestImage + latestImage = &img + latestImageV := semver.Parse(latestImage.Tag) var isLatest bool diff --git a/pkg/controller/kube_controller.go b/pkg/controller/kube_controller.go index d93bdd3d..3ff726d1 100644 --- a/pkg/controller/kube_controller.go +++ b/pkg/controller/kube_controller.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "net/url" + "regexp" "slices" "strings" "time" @@ -163,7 +164,7 @@ func (s *ClusterVersionScheduler) getLatestVersionFromUpstream(channel string) ( return "", fmt.Errorf("unexpected content-type %s when fetching channel %s", resp.Header.Get("content-type"), channel) } - body, err := io.ReadAll(resp.Body) + body, err := io.ReadAll(io.LimitReader(resp.Body, 1024)) if err != nil { return "", fmt.Errorf("failed to read response body: %w", err) } @@ -176,14 +177,12 @@ func (s *ClusterVersionScheduler) getLatestVersionFromUpstream(channel string) ( return version, nil } +var channelRe = regexp.MustCompile(`^(latest|stable)-1\.\d{1,3}$`) + func isValidKubernetesChannel(channel string) bool { // Only allow official Kubernetes channels validChannels := []string{"stable", "latest"} // Allow latest-X.Y and stable-X.Y formats - if strings.HasPrefix(channel, "latest-1.") || strings.HasPrefix(channel, "stable-1.") { - return true - } - - return slices.Contains(validChannels, channel) + return slices.Contains(validChannels, channel) || channelRe.MatchString(channel) } diff --git a/pkg/controller/options/options.go b/pkg/controller/options/options.go index 20ae0798..266c8830 100644 --- a/pkg/controller/options/options.go +++ b/pkg/controller/options/options.go @@ -93,7 +93,13 @@ func (b *Builder) handleRegexOption(name string, opts *api.Options, setNonSha *b *setNonSha = true opts.MatchRegex = &matchRegex - regexMatcher, err := regexp.Compile(matchRegex) + var regexMatcher *regexp.Regexp + var err error + if len(matchRegex) > 1024 { + err = fmt.Errorf("regex longer than 1024 bytes") + } else { + regexMatcher, err = regexp.Compile(matchRegex) + } if err != nil { *errs = append(*errs, fmt.Sprintf("failed to compile regex at annotation %q: %s", api.MatchRegexAnnotationKey, err)) } else { diff --git a/pkg/controller/search/search.go b/pkg/controller/search/search.go index d5c8b1fb..62187adb 100644 --- a/pkg/controller/search/search.go +++ b/pkg/controller/search/search.go @@ -2,9 +2,10 @@ package search import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" - "hash/fnv" "time" "github.com/sirupsen/logrus" @@ -90,10 +91,11 @@ func calculateHashIndex(imageURL string, opts *api.Options) (string, error) { return "", fmt.Errorf("failed to marshal options: %s", err) } - hash := fnv.New32() - if _, err := hash.Write(append(optsJSON, []byte(imageURL)...)); err != nil { - return "", fmt.Errorf("failed to calculate search hash: %s", err) - } + // sha256 (not a 32-bit hash) so one pod cannot craft a colliding key to poison another pod's cached result. + // Length-prefix the URL so (opts, url) pairs cannot be shifted across the boundary. + h := sha256.New() + _, _ = fmt.Fprintf(h, "%d:%s", len(imageURL), imageURL) + h.Write(optsJSON) - return fmt.Sprintf("%d", hash.Sum32()), nil + return hex.EncodeToString(h.Sum(nil)), nil } diff --git a/pkg/leveledlogrus/logger.go b/pkg/leveledlogrus/logger.go index 91235c5d..2c75c8c1 100644 --- a/pkg/leveledlogrus/logger.go +++ b/pkg/leveledlogrus/logger.go @@ -1,25 +1,39 @@ // Creates a leveled logger compatible with hashicorp/go-retryablehttp package leveledlogger -import "github.com/sirupsen/logrus" +import ( + "strings" + + "github.com/sirupsen/logrus" +) + +// clean strips control characters so remote-controlled text cannot forge log lines. +func clean(s string) string { + return strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return ' ' + } + return r + }, s) +} type Logger struct { *logrus.Entry } func (l *Logger) Error(msg string, keysAndValues ...interface{}) { - l.fields(keysAndValues).Error(msg) + l.fields(keysAndValues).Error(clean(msg)) } func (l *Logger) Info(msg string, keysAndValues ...interface{}) { - l.fields(keysAndValues).Info(msg) + l.fields(keysAndValues).Info(clean(msg)) } func (l *Logger) Debug(msg string, keysAndValues ...interface{}) { - l.fields(keysAndValues).Debug(msg) + l.fields(keysAndValues).Debug(clean(msg)) } func (l *Logger) Warn(msg string, keysAndValues ...interface{}) { - l.fields(keysAndValues).Warn(msg) + l.fields(keysAndValues).Warn(clean(msg)) } func (l *Logger) fields(keysAndValues []interface{}) *logrus.Entry { diff --git a/pkg/metrics/roundtripper.go b/pkg/metrics/roundtripper.go index 152e4951..c3b3ef0b 100644 --- a/pkg/metrics/roundtripper.go +++ b/pkg/metrics/roundtripper.go @@ -7,6 +7,7 @@ import ( "net/http/httptrace" "net/url" "strings" + "sync" "time" "github.com/prometheus/client_golang/prometheus" @@ -17,6 +18,9 @@ import ( type RoundTripper struct { base http.RoundTripper + domainMu sync.Mutex + domains map[string]struct{} + clientInFlightGauge prometheus.Gauge clientCounter *prometheus.CounterVec histVec *prometheus.GaugeVec @@ -103,8 +107,28 @@ func extractDomain(req *http.Request) string { return host } +const maxDomainLabels = 100 + +// boundDomain caps distinct "domain" label values (hosts are pod-controlled) +// so a pod author cannot create unbounded metric series. +func (t *RoundTripper) boundDomain(d string) string { + t.domainMu.Lock() + defer t.domainMu.Unlock() + if t.domains == nil { + t.domains = map[string]struct{}{} + } + if _, ok := t.domains[d]; ok { + return d + } + if len(t.domains) >= maxDomainLabels { + return "other" + } + t.domains[d] = struct{}{} + return d +} + func (t *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - domain := extractDomain(req) + domain := t.boundDomain(extractDomain(req)) // Track request duration startTime := time.Now()