mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-06 23:23:23 +09:00
hack/values-injection renders every chart under packages/apps and packages/extra with generated values for each string field and map key its schema allows, including the charts its HelmReleases install, and fails when a value changes the structure of the output rather than only its content. Fields multiline by design are listed in hack/testdata/values-injection/allowlist.txt. It runs as values-injection-check, a prerequisite of unit-tests, and the Helm Charts conventions in docs/agents/overview.md gain the rule it enforces. Assisted-by: LLM Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
494 lines
13 KiB
Go
494 lines
13 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Finding types that prove an injection: a token the payload carries shows
|
|
// up as structure of its own.
|
|
var proven = map[string]bool{"doc-injection": true, "yaml-inject": true, "shell-injection": true,
|
|
"heredoc-inject": true, "embedded-inject": true, "tpl-eval": true, "namespace": true}
|
|
|
|
var shells = map[string]bool{"sh": true, "bash": true, "ash": true, "dash": true}
|
|
|
|
type finding struct {
|
|
typ string
|
|
source string
|
|
detail string
|
|
}
|
|
|
|
// A path into a decoded document is kept two ways: its elements, a string
|
|
// key or an int index, for reports, and a prefix-free encoding of them, for
|
|
// set and map keys.
|
|
func keyElem(k string) string { return "s" + strconv.Itoa(len(k)) + ":" + k }
|
|
func indexElem(i int) string { return "i" + strconv.Itoa(i) + ";" }
|
|
|
|
func joinPath(path []any) string {
|
|
parts := make([]string, len(path))
|
|
for i, e := range path {
|
|
parts[i] = fmt.Sprint(e)
|
|
}
|
|
return strings.Join(parts, ".")
|
|
}
|
|
|
|
// normKey is <X> for the payload's own token, <C> for a key carrying the
|
|
// canary, with what precedes it kept.
|
|
func normKey(k, c string) string {
|
|
lk := lower(k)
|
|
i := strings.Index(lk, c)
|
|
if i < 0 {
|
|
return k
|
|
}
|
|
if strings.HasPrefix(lk[i:], c+"x") {
|
|
return k[:i] + "<X>"
|
|
}
|
|
return k[:i] + "<C>"
|
|
}
|
|
|
|
func isMarked(k string) bool {
|
|
return strings.HasSuffix(k, "<X>") || strings.HasSuffix(k, "<C>")
|
|
}
|
|
|
|
// shapeEntry is one leaf of a document's shape: where a value is and its type,
|
|
// or an empty map or list.
|
|
type shapeEntry struct {
|
|
path []any
|
|
typ string
|
|
marked bool
|
|
}
|
|
|
|
// walkShape calls emit for every entry of obj's shape, keyed by path and type.
|
|
// path is reused between calls; emit copies it if it keeps it.
|
|
func walkShape(obj any, c, prefix string, path []any, marked bool, emit func(key string, e shapeEntry)) {
|
|
switch x := obj.(type) {
|
|
case map[string]any:
|
|
if len(x) == 0 {
|
|
emit(prefix+"t{}", shapeEntry{path, "{}", marked})
|
|
}
|
|
for _, k := range sortedKeys(x) {
|
|
nk := normKey(k, c)
|
|
walkShape(x[k], c, prefix+keyElem(nk), append(path, nk), marked || isMarked(nk), emit)
|
|
}
|
|
case []any:
|
|
if len(x) == 0 {
|
|
emit(prefix+"t[]", shapeEntry{path, "[]", marked})
|
|
}
|
|
for i, v := range x {
|
|
walkShape(v, c, prefix+indexElem(i), append(path, i), marked, emit)
|
|
}
|
|
default:
|
|
t := typeName(obj)
|
|
emit(prefix+"t"+t, shapeEntry{path, t, marked})
|
|
}
|
|
}
|
|
|
|
func shape(obj any, c string) map[string]struct{} {
|
|
out := map[string]struct{}{}
|
|
walkShape(obj, c, "", nil, false, func(key string, _ shapeEntry) { out[key] = struct{}{} })
|
|
return out
|
|
}
|
|
|
|
// added is the shape of obj that base lacks.
|
|
func added(obj any, c string, base map[string]struct{}) []shapeEntry {
|
|
seen := map[string]bool{}
|
|
var out []shapeEntry
|
|
walkShape(obj, c, "", nil, false, func(key string, e shapeEntry) {
|
|
if _, ok := base[key]; ok || seen[key] {
|
|
return
|
|
}
|
|
seen[key] = true
|
|
e.path = append([]any(nil), e.path...)
|
|
out = append(out, e)
|
|
})
|
|
return out
|
|
}
|
|
|
|
func tupleRepr(path []any) string {
|
|
parts := make([]string, len(path))
|
|
for i, e := range path {
|
|
if s, ok := e.(string); ok {
|
|
parts[i] = repr(s)
|
|
} else {
|
|
parts[i] = fmt.Sprint(e)
|
|
}
|
|
}
|
|
if len(parts) == 1 {
|
|
return "(" + parts[0] + ",)"
|
|
}
|
|
return "(" + strings.Join(parts, ", ") + ")"
|
|
}
|
|
|
|
// describe lists up to four entries, ordered as the first version of this
|
|
// check ordered them: by the Python text of (path, type).
|
|
func describe(entries []shapeEntry) string {
|
|
type keyed struct {
|
|
key string
|
|
e shapeEntry
|
|
}
|
|
sorted := make([]keyed, len(entries))
|
|
for i, e := range entries {
|
|
sorted[i] = keyed{"(" + tupleRepr(e.path) + ", " + repr(e.typ) + ")", e}
|
|
}
|
|
sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].key < sorted[j].key })
|
|
var parts []string
|
|
for _, k := range sorted[:min(4, len(sorted))] {
|
|
parts = append(parts, "+"+joinPath(k.e.path)+":"+k.e.typ)
|
|
}
|
|
return strings.Join(parts, ", ")
|
|
}
|
|
|
|
// pathEntry is a string at a path of a document, in the order a walk meets
|
|
// it; a later string at the same path replaces the value, not the position.
|
|
type pathEntry struct {
|
|
key string
|
|
path []any
|
|
val string
|
|
}
|
|
|
|
type orderedPaths struct {
|
|
index map[string]int
|
|
list []pathEntry
|
|
}
|
|
|
|
func (o *orderedPaths) set(key string, path []any, val string) {
|
|
if o.index == nil {
|
|
o.index = map[string]int{}
|
|
}
|
|
if i, ok := o.index[key]; ok {
|
|
o.list[i].val = val
|
|
if o.list[i].path == nil && path != nil {
|
|
o.list[i].path = append([]any(nil), path...)
|
|
}
|
|
return
|
|
}
|
|
o.index[key] = len(o.list)
|
|
if path != nil {
|
|
path = append([]any(nil), path...)
|
|
}
|
|
o.list = append(o.list, pathEntry{key, path, val})
|
|
}
|
|
|
|
func (o *orderedPaths) get(key string) (string, bool) {
|
|
i, ok := o.index[key]
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
return o.list[i].val, true
|
|
}
|
|
|
|
// leaves is every string of obj, keyed by its path with keys normalized. A
|
|
// leaf keeps its path only when the canary is in its value: no other is
|
|
// reported.
|
|
func leaves(obj any, c string) *orderedPaths {
|
|
out := &orderedPaths{}
|
|
var walk func(v any, prefix string, path []any)
|
|
walk = func(v any, prefix string, path []any) {
|
|
switch x := v.(type) {
|
|
case map[string]any:
|
|
for _, k := range sortedKeys(x) {
|
|
nk := normKey(k, c)
|
|
walk(x[k], prefix+keyElem(nk), append(path, nk))
|
|
}
|
|
case []any:
|
|
for i, e := range x {
|
|
walk(e, prefix+indexElem(i), append(path, i))
|
|
}
|
|
case string:
|
|
if containsFold(x, c) {
|
|
out.set(prefix, path, x)
|
|
} else {
|
|
out.set(prefix, nil, x)
|
|
}
|
|
}
|
|
}
|
|
walk(obj, "", nil)
|
|
return out
|
|
}
|
|
|
|
func basename(p string) string {
|
|
return p[strings.LastIndexByte(p, '/')+1:]
|
|
}
|
|
|
|
func isShellFlag(s string) bool {
|
|
if len(s) < 2 || s[0] != '-' {
|
|
return false
|
|
}
|
|
c := false
|
|
for i := 1; i < len(s); i++ {
|
|
if s[i] < 'a' || s[i] > 'z' {
|
|
return false
|
|
}
|
|
c = c || s[i] == 'c'
|
|
}
|
|
return c
|
|
}
|
|
|
|
// findScripts is every shell script of obj by its path, keys as they are:
|
|
// the argument of `sh [-opts] -c`, the value of a *.sh key, a string that
|
|
// starts with a shell shebang.
|
|
func findScripts(obj any) *orderedPaths {
|
|
out := &orderedPaths{}
|
|
var walk func(v any, prefix string, path []any)
|
|
walk = func(v any, prefix string, path []any) {
|
|
switch x := v.(type) {
|
|
case map[string]any:
|
|
cmd, _ := x["command"].([]any)
|
|
args, _ := x["args"].([]any)
|
|
argv := append(append([]any(nil), cmd...), args...)
|
|
for i, a := range argv {
|
|
if s, ok := a.(string); !ok || !shells[basename(s)] {
|
|
continue
|
|
}
|
|
for j := i + 1; j < min(i+5, len(argv)-1); j++ {
|
|
flag, ok := argv[j].(string)
|
|
script, ok2 := argv[j+1].(string)
|
|
if !ok || !ok2 || !isShellFlag(flag) {
|
|
continue
|
|
}
|
|
k := j + 1
|
|
if k < len(cmd) {
|
|
out.set(prefix+keyElem("command")+indexElem(k), append(path, "command", k), script)
|
|
} else {
|
|
out.set(prefix+keyElem("args")+indexElem(k-len(cmd)), append(path, "args", k-len(cmd)), script)
|
|
}
|
|
break
|
|
}
|
|
}
|
|
for _, k := range sortedKeys(x) {
|
|
if s, ok := x[k].(string); ok && strings.HasSuffix(k, ".sh") {
|
|
out.set(prefix+keyElem(k), append(path, k), s)
|
|
}
|
|
walk(x[k], prefix+keyElem(k), append(path, k))
|
|
}
|
|
case []any:
|
|
for i, e := range x {
|
|
walk(e, prefix+indexElem(i), append(path, i))
|
|
}
|
|
case string:
|
|
first, _, _ := strings.Cut(x, "\n")
|
|
if strings.HasPrefix(x, "#!") && strings.Contains(first, "sh") {
|
|
out.set(prefix, path, x)
|
|
}
|
|
}
|
|
}
|
|
walk(obj, "", nil)
|
|
return out
|
|
}
|
|
|
|
// memo caches what strings decode to, for a slot whose reference values are
|
|
// decoded once per payload.
|
|
type memo map[string]any
|
|
|
|
func (m memo) structured(text string) any {
|
|
if v, ok := m[text]; ok {
|
|
return v
|
|
}
|
|
v := structured(text)
|
|
m[text] = v
|
|
return v
|
|
}
|
|
|
|
// embedded is the finding type for a string that carries YAML or JSON, if
|
|
// any, and whether the reference string is structured at all.
|
|
func embedded(m memo, bv, pv, c, kind string) (string, bool) {
|
|
bs := m.structured(bv)
|
|
if bs == nil {
|
|
return "", false
|
|
}
|
|
ps := m.structured(pv)
|
|
if ps == nil {
|
|
return kind + "-break", true
|
|
}
|
|
for _, e := range added(ps, c, shape(bs, c)) {
|
|
if e.marked {
|
|
return kind + "-inject", true
|
|
}
|
|
}
|
|
return "", true
|
|
}
|
|
|
|
// refDoc is a document of a reference render with what every payload render
|
|
// is compared against, worked out once.
|
|
type refDoc struct {
|
|
doc
|
|
id string
|
|
shape map[string]struct{}
|
|
scripts *orderedPaths
|
|
leaves *orderedPaths
|
|
}
|
|
|
|
type reference struct {
|
|
docs []refDoc
|
|
ids []string
|
|
}
|
|
|
|
func prepare(docs []doc, c string) *reference {
|
|
ref := &reference{}
|
|
for _, d := range docs {
|
|
id, _ := ident(d.obj)
|
|
ref.docs = append(ref.docs, refDoc{d, id, shape(d.obj, c), findScripts(d.obj), leaves(d.obj, c)})
|
|
ref.ids = append(ref.ids, id)
|
|
}
|
|
return ref
|
|
}
|
|
|
|
func ident(v any) (key, display string) {
|
|
if m, ok := v.(map[string]any); ok {
|
|
av, kd := pyRepr(m["apiVersion"]), pyRepr(m["kind"])
|
|
return "d" + av + "\x00" + kd, "(" + av + ", " + kd + ")"
|
|
}
|
|
t := typeName(v)
|
|
return "t" + t, t
|
|
}
|
|
|
|
func count(ids []string, id string) int {
|
|
n := 0
|
|
for _, x := range ids {
|
|
if x == id {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// compare is the findings of a payload render that succeeded, against the
|
|
// reference: pDocs and err are what decoding pOut gave.
|
|
func compare(m memo, ref *reference, pDocs []doc, err error, pOut, c string) []finding {
|
|
var findings []finding
|
|
if err != nil {
|
|
return []finding{{"yaml-break", "?", truncate(err.Error(), 200)}}
|
|
}
|
|
|
|
if marker := c + "tpleval"; strings.Contains(pOut, marker) {
|
|
src := "?"
|
|
for _, d := range pDocs {
|
|
if j, err := json.Marshal(d.obj); err == nil && strings.Contains(string(j), marker) {
|
|
src = d.source
|
|
break
|
|
}
|
|
}
|
|
line := ""
|
|
for _, l := range splitLines(pOut) {
|
|
if strings.Contains(l, marker) {
|
|
line = l
|
|
break
|
|
}
|
|
}
|
|
findings = append(findings, finding{"tpl-eval", src, truncate(strip(line), 160)})
|
|
}
|
|
|
|
pIDs := make([]string, len(pDocs))
|
|
pShown := make([]string, len(pDocs))
|
|
for i, d := range pDocs {
|
|
pIDs[i], pShown[i] = ident(d.obj)
|
|
}
|
|
if strings.Join(pIDs, "\x01") != strings.Join(ref.ids, "\x01") || len(pIDs) != len(ref.ids) {
|
|
var extra []string
|
|
for i, id := range pIDs {
|
|
if count(pIDs, id) > count(ref.ids, id) {
|
|
extra = append(extra, pDocs[i].source+" "+pShown[i])
|
|
}
|
|
}
|
|
src := "?"
|
|
if len(extra) > 0 {
|
|
src, _, _ = strings.Cut(extra[0], " ")
|
|
} else if len(pDocs) > 0 {
|
|
src = pDocs[0].source
|
|
}
|
|
detail := fmt.Sprintf("%d -> %d documents; ", len(ref.ids), len(pIDs)) + strings.Join(extra[:min(2, len(extra))], "; ")
|
|
return append(findings, finding{"doc-injection", src, detail})
|
|
}
|
|
|
|
for i, b := range ref.docs {
|
|
pd := pDocs[i].obj
|
|
src := b.source
|
|
kind := ""
|
|
if pm, ok := pd.(map[string]any); ok {
|
|
if k, has := pm["kind"]; has {
|
|
kind = pyStr(k)
|
|
}
|
|
if ns, ok := asMap(pm["metadata"])["namespace"].(string); ok && containsFold(ns, c) {
|
|
findings = append(findings, finding{"namespace", src, kind + " namespace " + repr(ns)})
|
|
}
|
|
}
|
|
add := added(pd, c, b.shape)
|
|
var inj []shapeEntry
|
|
for _, e := range add {
|
|
if e.marked {
|
|
inj = append(inj, e)
|
|
}
|
|
}
|
|
if len(inj) > 0 {
|
|
findings = append(findings, finding{"yaml-inject", src, kind + " " + describe(inj)})
|
|
continue
|
|
}
|
|
if len(add) > 0 {
|
|
findings = append(findings, finding{"yaml-shape", src, kind + " " + describe(add)})
|
|
continue
|
|
}
|
|
|
|
pScripts := findScripts(pd)
|
|
for _, ps := range pScripts.list {
|
|
btext, ok := b.scripts.get(ps.key)
|
|
if !ok || !containsFold(ps.val, c) {
|
|
continue
|
|
}
|
|
where := joinPath(ps.path)
|
|
bp := parseScript(btext)
|
|
if !bp.ok {
|
|
continue
|
|
}
|
|
pp := parseScript(ps.val)
|
|
if !pp.ok {
|
|
findings = append(findings, finding{"shell-break", src, where})
|
|
continue
|
|
}
|
|
if pp.skeleton != bp.skeleton {
|
|
findings = append(findings, finding{"shell-injection", src, where})
|
|
continue
|
|
}
|
|
for h := 0; h < min(len(bp.heredocs), len(pp.heredocs)); h++ {
|
|
bh, ph := bp.heredocs[h], pp.heredocs[h]
|
|
if !containsFold(ph, c) {
|
|
continue
|
|
}
|
|
typ, isStruct := embedded(m, bh, ph, c, "heredoc")
|
|
if typ != "" {
|
|
findings = append(findings, finding{strings.ReplaceAll(typ, "heredoc-break", "heredoc-newline"), src, where})
|
|
} else if !isStruct && strings.Count(ph, "\n") > strings.Count(bh, "\n") {
|
|
findings = append(findings, finding{"heredoc-newline", src, where})
|
|
}
|
|
}
|
|
if nl := "\n" + c + "x"; strings.Contains(ps.val, nl) && !strings.Contains(btext, nl) {
|
|
findings = append(findings, finding{"script-newline", src, where})
|
|
}
|
|
}
|
|
|
|
for _, pl := range leaves(pd, c).list {
|
|
bv, ok := b.leaves.get(pl.key)
|
|
if !ok || !containsFold(pl.val, c) {
|
|
continue
|
|
}
|
|
if _, isScript := pScripts.index[pl.key]; isScript {
|
|
continue
|
|
}
|
|
where := joinPath(pl.path)
|
|
typ, isStruct := embedded(m, bv, pl.val, c, "embedded")
|
|
switch {
|
|
case typ != "":
|
|
findings = append(findings, finding{typ, src, where})
|
|
case isStruct || !strings.Contains(bv, "\n"):
|
|
case strings.Count(pl.val, "\n") > strings.Count(bv, "\n") || strings.Count(pl.val, "\r") > strings.Count(bv, "\r"):
|
|
findings = append(findings, finding{"embedded-newline", src, where})
|
|
case strings.Contains(pl.val, c+"\""+c+"x") || strings.Contains(pl.val, c+"'"+c+"x"):
|
|
findings = append(findings, finding{"embedded-quote", src, where})
|
|
}
|
|
}
|
|
}
|
|
return findings
|
|
}
|