Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix(postman): prevent infinite recursion in variable substitution (#4145)
Dustin Deckerc8921694a53d
diff --git a/pkg/sources/postman/postman.go b/pkg/sources/postman/postman.goindex e3ca0cf70..73862ddf0 100644--- a/pkg/sources/postman/postman.go+++ b/pkg/sources/postman/postman.go@@ -434,7 +434,7 @@ func (s *Source) scanEvent(ctx context.Context, chunksChan chan *sources.Chunk,metadata.LocationType = source_metadatapb.PostmanLocationType_COLLECTION_SCRIPT}- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, data)), metadata)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, data, DefaultMaxRecursionDepth)), metadata)metadata.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -532,7 +532,7 @@ func (s *Source) scanAuth(ctx context.Context, chunksChan chan *sources.Chunk, m} else if strings.Contains(m.Type, COLLECTION_TYPE) {m.LocationType = source_metadatapb.PostmanLocationType_COLLECTION_AUTHORIZATION}- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, authData)), m)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, authData, DefaultMaxRecursionDepth)), m)m.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -555,7 +555,7 @@ func (s *Source) scanHTTPRequest(ctx context.Context, chunksChan chan *sources.Cmetadata.Type = originalType + " > header"metadata.Link = metadata.Link + "?tab=headers"metadata.LocationType = source_metadatapb.PostmanLocationType_REQUEST_HEADER- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, strings.Join(r.HeaderString, " "))), metadata)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, strings.Join(r.HeaderString, " "), DefaultMaxRecursionDepth)), metadata)metadata.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -564,7 +564,7 @@ func (s *Source) scanHTTPRequest(ctx context.Context, chunksChan chan *sources.C// Note: query parameters are handled separatelyu := fmt.Sprintf("%s://%s/%s", r.URL.Protocol, strings.Join(r.URL.Host, "."), strings.Join(r.URL.Path, "/"))metadata.LocationType = source_metadatapb.PostmanLocationType_REQUEST_URL- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, u)), metadata)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(metadata, u, DefaultMaxRecursionDepth)), metadata)metadata.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -615,13 +615,13 @@ func (s *Source) scanRequestBody(ctx context.Context, chunksChan chan *sources.Cm.Type = originalType + " > raw"data := b.Rawm.LocationType = source_metadatapb.PostmanLocationType_REQUEST_BODY_RAW- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, data)), m)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, data, DefaultMaxRecursionDepth)), m)m.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMANcase "graphql":m.Type = originalType + " > graphql"data := b.GraphQL.Query + " " + b.GraphQL.Variablesm.LocationType = source_metadatapb.PostmanLocationType_REQUEST_BODY_GRAPHQL- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, data)), m)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, data, DefaultMaxRecursionDepth)), m)m.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}}@@ -647,7 +647,7 @@ func (s *Source) scanHTTPResponse(ctx context.Context, chunksChan chan *sources.m.Type = originalType + " > response header"// TODO Note: for now, links to Postman responses do not include a more granular tab for the params/header/body, but when they do, we will need to update the metadata.Link infom.LocationType = source_metadatapb.PostmanLocationType_RESPONSE_HEADER- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, strings.Join(response.HeaderString, " "))), m)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, strings.Join(response.HeaderString, " "), DefaultMaxRecursionDepth)), m)m.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -655,7 +655,7 @@ func (s *Source) scanHTTPResponse(ctx context.Context, chunksChan chan *sources.if response.Body != "" {m.Type = originalType + " > response body"m.LocationType = source_metadatapb.PostmanLocationType_RESPONSE_BODY- s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, response.Body)), m)+ s.scanData(ctx, chunksChan, s.formatAndInjectKeywords(s.buildSubstituteSet(m, response.Body, DefaultMaxRecursionDepth)), m)m.LocationType = source_metadatapb.PostmanLocationType_UNKNOWN_POSTMAN}@@ -688,7 +688,7 @@ func (s *Source) scanVariableData(ctx context.Context, chunksChan chan *sources.if valStr == "" {continue}- values = append(values, s.buildSubstituteSet(m, valStr)...)+ values = append(values, s.buildSubstituteSet(m, valStr, DefaultMaxRecursionDepth)...)}m.FieldType = m.Type + " variables"diff --git a/pkg/sources/postman/substitution.go b/pkg/sources/postman/substitution.goindex 7cb813743..692c3a7b7 100644--- a/pkg/sources/postman/substitution.go+++ b/pkg/sources/postman/substitution.go@@ -8,6 +8,9 @@ import (var subRe = regexp.MustCompile(`\{\{[^{}]+\}\}`)+// DefaultMaxRecursionDepth is the default maximum recursion depth for variable substitution+const DefaultMaxRecursionDepth = 2+type VariableInfo struct {value stringMetadata Metadata@@ -47,11 +50,14 @@ func (s *Source) formatAndInjectKeywords(data []string) string {return strings.Join(ret, "")}-func (s *Source) buildSubstituteSet(metadata Metadata, data string) []string {+// buildSubstituteSet creates a set of substitutions for the given data+// maxRecursionDepth is the maximum recursion depth to use for variable substitution+func (s *Source) buildSubstituteSet(metadata Metadata, data string, maxRecursionDepth int) []string {var ret []stringcombos := make(map[string]struct{})- s.buildSubstitution(data, metadata, &combos)+ // Call buildSubstitution with initial depth of 0 and the maxRecursionDepth+ s.buildSubstitution(data, metadata, &combos, 0, maxRecursionDepth)for combo := range combos {ret = append(ret, combo)@@ -63,26 +69,55 @@ func (s *Source) buildSubstituteSet(metadata Metadata, data string) []string {return ret}-func (s *Source) buildSubstitution(data string, metadata Metadata, combos *map[string]struct{}) {+// buildSubstitution performs variable substitution with a maximum recursion depth+// depth is the current recursion depth+// maxRecursionDepth is the maximum recursion depth to use for variable substitution+func (s *Source) buildSubstitution(data string, metadata Metadata, combos *map[string]struct{}, depth int, maxRecursionDepth int) {+ // Limit recursion depth to prevent stack overflow+ if depth > maxRecursionDepth {+ (*combos)[data] = struct{}{}+ return+ }+matches := removeDuplicateStr(subRe.FindAllString(data, -1))+ if len(matches) == 0 {+ // No more substitutions to make, add to combos+ (*combos)[data] = struct{}{}+ return+ }++ substitutionMade := falsefor _, match := range matches {- for _, slice := range s.sub.variables[strings.Trim(match, "{}")] {- if slice.Metadata.CollectionInfo.PostmanID != "" && slice.Metadata.CollectionInfo.PostmanID != metadata.CollectionInfo.PostmanID {+ varName := strings.Trim(match, "{}")+ slices := s.sub.variables[varName]+ if len(slices) == 0 {+ continue+ }++ for _, slice := range slices {+ if slice.Metadata.CollectionInfo.PostmanID != "" &&+ slice.Metadata.CollectionInfo.PostmanID != metadata.CollectionInfo.PostmanID {continue}- // to ensure we don't infinitely recurse, we will trim all `{{}}` from the values before replacement.- // this is to prevent the case where a variable is replaced with a value that contains the same variable causing- // an infinite loop- removedBrackets := strings.ReplaceAll(strings.ReplaceAll(slice.value, "{{", ""), "}}", "")+ // Prevent self-referential variables+ if strings.Contains(slice.value, match) {+ continue+ }- d := strings.ReplaceAll(data, match, removedBrackets)- s.buildSubstitution(d, metadata, combos)+ // Use the actual value for substitution, not just the stripped version+ d := strings.ReplaceAll(data, match, slice.value)++ // Only mark substitution as made if we actually changed something+ if d != data {+ substitutionMade = true+ s.buildSubstitution(d, metadata, combos, depth+1, maxRecursionDepth)+ }}}- if len(matches) == 0 {- // add to combos+ // If no substitutions were made, add the current data+ if !substitutionMade {(*combos)[data] = struct{}{}}}diff --git a/pkg/sources/postman/substitution_test.go b/pkg/sources/postman/substitution_test.goindex 75de88273..5204ccb1a 100644--- a/pkg/sources/postman/substitution_test.go+++ b/pkg/sources/postman/substitution_test.go@@ -84,12 +84,12 @@ func TestSource_BuildSubstituteSet(t *testing.T) {{"{{var2}}", []string{"value2"}},{"{{var1}}:{{var2}}", []string{"value1:value2"}},{"no variables", []string{"no variables"}},- {"{{var1}}:{{continuation_token}}", []string{"value1:'continuation_token'"}},- {"{{var1}}:{{continuation_token2}}", []string{"value1:'{continuation_token2}'"}},+ {"{{var1}}:{{continuation_token}}", []string{"value1:{{continuation_token}}"}},+ {"{{var1}}:{{continuation_token2}}", []string{"value1:{{continuation_token2}}"}},}for _, tc := range testCases {- result := s.buildSubstituteSet(metadata, tc.data)+ result := s.buildSubstituteSet(metadata, tc.data, DefaultMaxRecursionDepth)if !reflect.DeepEqual(result, tc.expected) {t.Errorf("Expected substitution set: %v, got: %v", tc.expected, result)}@@ -156,3 +156,101 @@ func TestSource_FormatAndInjectKeywords(t *testing.T) {}}}++func TestSource_BuildSubstitution_RecursionLimit(t *testing.T) {+ s := &Source{+ sub: NewSubstitution(),+ }+ metadata := Metadata{+ Type: ENVIRONMENT_TYPE,+ }++ // Setup test cases++ // 1. Self-referential variable (should be skipped)+ s.sub.add(metadata, "self_ref", "{{self_ref}}")++ // 2. Nested variables for testing recursion depth+ s.sub.add(metadata, "var1", "{{var2}}")+ s.sub.add(metadata, "var2", "{{var3}}")+ s.sub.add(metadata, "var3", "{{var4}}")+ s.sub.add(metadata, "var4", "{{var5}}")+ s.sub.add(metadata, "var5", "{{var6}}")+ s.sub.add(metadata, "var6", "{{var7}}")+ s.sub.add(metadata, "var7", "{{var8}}")+ s.sub.add(metadata, "var8", "{{var9}}")+ s.sub.add(metadata, "var9", "{{var10}}")+ s.sub.add(metadata, "var10", "{{var11}}")+ s.sub.add(metadata, "var11", "{{var12}}")+ s.sub.add(metadata, "var12", "final_value")++ // 3. Circular reference+ s.sub.add(metadata, "circular1", "{{circular2}}")+ s.sub.add(metadata, "circular2", "{{circular3}}")+ s.sub.add(metadata, "circular3", "{{circular1}}")++ testCases := []struct {+ name string+ data string+ expected []string+ maxDepth int+ }{+ {+ name: "Self-referential variable",+ data: "{{self_ref}}",+ expected: []string{"{{self_ref}}"},+ },+ {+ name: "Nested variables within depth limit",+ data: "{{var8}}",+ expected: []string{"{{var11}}"},+ },+ {+ name: "Nested variables exceeding depth limit",+ data: "{{var1}}",+ expected: []string{"{{var4}}"},+ },+ {+ name: "Circular reference",+ data: "{{circular1}}",+ expected: []string{"{{circular1}}"},+ },+ {+ name: "Custom recursion depth limit (5)",+ data: "{{var1}}",+ expected: []string{"{{var7}}"},+ maxDepth: 5,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ combos := make(map[string]struct{})++ // Use custom maxDepth if provided, otherwise use default+ if tc.maxDepth > 0 {+ s.buildSubstitution(tc.data, metadata, &combos, 0, tc.maxDepth)+ } else {+ s.buildSubstitution(tc.data, metadata, &combos, 0, DefaultMaxRecursionDepth)+ }++ var result []string+ for combo := range combos {+ result = append(result, combo)+ }++ // If no substitutions were made, the original data should be returned+ if len(result) == 0 {+ result = []string{tc.data}+ }++ // Sort both slices for consistent comparison+ sort.Strings(result)+ sort.Strings(tc.expected)++ if !reflect.DeepEqual(result, tc.expected) {+ t.Errorf("Expected: %v, got: %v", tc.expected, result)+ }+ })+ }+}