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
35 changes: 21 additions & 14 deletions pkg/analysis/topology/topology.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,7 @@ func ExtractTopology(fn *ssa.Function) *FunctionTopology {
val = val[:maxStrLen]
}

// Security Fix: Prevent DoS via O(N^2) ValidString checks on binary data.
// Perform a linear scan O(N) to find the longest valid UTF-8 prefix.
if !utf8.ValidString(val) {
validLen := 0
for i := 0; i < len(val); {
r, size := utf8.DecodeRuneInString(val[i:])
if r == utf8.RuneError && size == 1 {
break // Stop at first invalid byte
}
validLen += size
i += size
}
val = val[:validLen]
}
val = truncateToValidUTF8(val)

if currentStringBytes+len(val) <= maxTotalBytes {
t.StringLiterals = append(t.StringLiterals, val)
Expand Down Expand Up @@ -576,3 +563,23 @@ func flattenStringLiterals(literals []string) []byte {
}
return dataAccumulator
}

// truncateToValidUTF8 returns the longest valid UTF-8 prefix of s.
// It avoids O(N^2) behavior by performing a single linear scan if the string is invalid.
func truncateToValidUTF8(s string) string {
if utf8.ValidString(s) {
return s
}

// Perform a linear scan O(N) to find the longest valid UTF-8 prefix.
validLen := 0
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
break // Stop at first invalid byte
}
validLen += size
i += size
}
return s[:validLen]
}
53 changes: 53 additions & 0 deletions pkg/analysis/topology/topology_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,56 @@ func BenchmarkFlattenStringLiterals(b *testing.B) {
_ = flattenStringLiterals(literals)
}
}

func TestTruncateToValidUTF8(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "Empty string",
input: "",
expected: "",
},
{
name: "Valid ASCII",
input: "hello world",
expected: "hello world",
},
{
name: "Valid UTF-8",
input: "Hello, 世界",
expected: "Hello, 世界",
},
{
name: "Invalid at end",
input: "Hello, \xFF",
expected: "Hello, ",
},
{
name: "Invalid in middle",
input: "Hello, \xFF World",
expected: "Hello, ",
},
{
name: "Binary start",
input: "\xFF\xFE",
expected: "",
},
{
name: "Partial multi-byte rune at end",
input: string([]byte{0xe4, 0xb8, 0x96, 0xe7, 0x95}), // "世" + first byte of "界"
expected: "世",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := truncateToValidUTF8(tt.input)
if result != tt.expected {
t.Errorf("truncateToValidUTF8(%q) = %q; want %q", tt.input, result, tt.expected)
}
})
}
}
Loading