Repository navigation
Expand file tree
/
Copy pathparser_test.go
More file actions
496 lines (450 loc) · 15.2 KB
/
Copy pathparser_test.go
File metadata and controls
496 lines (450 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package templates
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/disk"
"github.com/projectdiscovery/nuclei/v3/pkg/model"
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/severity"
"github.com/projectdiscovery/nuclei/v3/pkg/model/types/stringslice"
"github.com/stretchr/testify/require"
)
type countingCatalog struct {
reads atomic.Int32
}
func (c *countingCatalog) OpenFile(string) (io.ReadCloser, error) {
c.reads.Add(1)
time.Sleep(25 * time.Millisecond)
return io.NopCloser(strings.NewReader("id: concurrent-parse\ninfo:\n name: Concurrent parse\n author: pd\n severity: info\n")), nil
}
func (*countingCatalog) GetTemplatePath(string) ([]string, error) { return nil, nil }
func (*countingCatalog) GetTemplatesPath([]string) ([]string, map[string]error) {
return nil, nil
}
func (*countingCatalog) ResolvePath(string, string) (string, error) { return "", nil }
func TestParserLifecycle(t *testing.T) {
t.Run("purge clears parsed and compiled caches", func(t *testing.T) {
parser := NewParser()
parser.Cache().Store("tpl-a", &Template{}, []byte("raw"), nil)
parser.CompiledCache().Store("tpl-a", &Template{}, []byte("raw"), nil)
require.Equal(t, 1, parser.ParsedCount())
require.Equal(t, 1, parser.CompiledCount())
parser.Purge()
require.Zero(t, parser.ParsedCount())
require.Zero(t, parser.CompiledCount())
})
t.Run("execution parser shares only parsed cache", func(t *testing.T) {
parent := NewParser()
parent.ShouldValidate = true
parent.NoStrictSyntax = true
parent.Cache().Store("parsed", &Template{}, []byte("raw"), nil)
parent.CompiledCache().StoreWithoutRaw("parent-compiled", &Template{}, nil)
execution := NewExecutionParser(parent)
sibling := NewExecutionParser(parent)
require.Same(t, parent.Cache(), execution.Cache())
require.Same(t, parent.Cache(), sibling.Cache())
require.NotSame(t, parent.CompiledCache(), execution.CompiledCache())
require.NotSame(t, execution.CompiledCache(), sibling.CompiledCache())
require.True(t, execution.ShouldValidate)
require.True(t, execution.NoStrictSyntax)
require.Equal(t, 1, execution.ParsedCount())
require.Zero(t, execution.CompiledCount())
execution.CompiledCache().StoreWithoutRaw("execution-compiled", &Template{}, nil)
require.Equal(t, 1, execution.CompiledCount())
require.Zero(t, sibling.CompiledCount())
require.Equal(t, 1, parent.CompiledCount())
})
t.Run("purge compiled preserves shared parsed cache", func(t *testing.T) {
parent := NewParser()
parent.Cache().Store("parsed", &Template{}, []byte("raw"), nil)
execution := NewExecutionParser(parent)
execution.CompiledCache().StoreWithoutRaw("compiled", &Template{}, nil)
execution.PurgeCompiled()
require.Zero(t, execution.CompiledCount())
require.Equal(t, 1, execution.ParsedCount())
require.Equal(t, 1, parent.ParsedCount())
})
}
func TestParseTemplateCoalescesConcurrentCacheMisses(t *testing.T) {
const callers = 20
cache := NewCache()
catalog := &countingCatalog{}
start := make(chan struct{})
errs := make(chan error, callers)
var wg sync.WaitGroup
for range callers {
parser := NewParserWithParsedCache(cache)
wg.Add(1)
go func(parser *Parser) {
defer wg.Done()
<-start
_, err := parser.ParseTemplate("concurrent.yaml", catalog)
errs <- err
}(parser)
}
close(start)
wg.Wait()
close(errs)
for err := range errs {
require.NoError(t, err)
}
require.EqualValues(t, 1, catalog.reads.Load(), "one shared cache miss should read and parse the template once")
}
func TestLoadTemplate(t *testing.T) {
catalog := disk.NewCatalog("")
p := NewParser()
tt := []struct {
name string
template *Template
templateErr error
filter TagFilterConfig
expectedErr error
isValid bool
}{
{
name: "valid",
template: &Template{
ID: "CVE-2021-27330",
Info: model.Info{
Name: "Valid template",
Authors: stringslice.StringSlice{Value: "Author"},
SeverityHolder: severity.Holder{Severity: severity.Medium},
},
},
isValid: true,
},
{
name: "emptyTemplate",
template: &Template{},
isValid: false,
expectedErr: errors.New("cause=\"Could not load template emptyTemplate: cause=\\\"mandatory 'name' field is missing\\\"\\ncause=\\\"mandatory 'author' field is missing\\\"\\ncause=\\\"mandatory 'id' field is missing\\\"\""),
},
{
name: "emptyNameWithInvalidID",
template: &Template{
ID: "invalid id",
Info: model.Info{
Authors: stringslice.StringSlice{Value: "Author"},
SeverityHolder: severity.Holder{Severity: severity.Medium},
},
},
expectedErr: errors.New("cause=\"Could not load template emptyNameWithInvalidID: cause=\\\"mandatory 'name' field is missing\\\"\\ncause=\\\"invalid field format for 'id' (allowed format is ^([a-zA-Z0-9]+[-_])*[a-zA-Z0-9]+$)\\\"\""),
},
{
name: "emptySeverity",
template: &Template{
ID: "CVE-2021-27330",
Info: model.Info{
Name: "Valid template",
Authors: stringslice.StringSlice{Value: "Author"},
},
},
isValid: true,
expectedErr: errors.New("field 'severity' is missing"),
},
{
name: "template-without-severity-with-correct-filter-id",
template: &Template{
ID: "CVE-2021-27330",
Info: model.Info{
Name: "Valid template",
Authors: stringslice.StringSlice{Value: "Author"},
},
},
// should be error because the template is loaded
expectedErr: errors.New("field 'severity' is missing"),
isValid: true,
filter: TagFilterConfig{IncludeIds: []string{"CVE-2021-27330"}},
},
{
name: "template-without-severity-with-diff-filter-id",
template: &Template{
ID: "CVE-2021-27330",
Info: model.Info{
Name: "Valid template",
Authors: stringslice.StringSlice{Value: "Author"},
},
},
isValid: false,
filter: TagFilterConfig{IncludeIds: []string{"another-id"}},
// no error because the template is not loaded
expectedErr: nil,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
p.parsedTemplatesCache.Store(tc.name, tc.template, nil, tc.templateErr)
tagFilter, err := NewTagFilter(&tc.filter)
require.Nil(t, err)
success, err := p.LoadTemplate(tc.name, tagFilter, nil, catalog)
if tc.expectedErr == nil {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, tc.expectedErr.Error())
}
require.Equal(t, tc.isValid, success)
})
}
// Regression test for projectdiscovery/nuclei#7448.
//
// Templates loaded from JSON used to silently accept unknown fields because
// [Template.UnmarshalJSON] delegated to a non-strict json.Unmarshal call.
// That meant `-validate` would pass templates that contained typoed fields
// or HTTP-only fields on a network.Request block, which then failed at
// runtime with the unknown-field error. Strict mode is the default and
// must be opt-out via the parser's [Parser.NoStrictSyntax] field (set
// from the runner's `-no-strict-syntax` flag).
t.Run("strictJSONRejectsUnknownFields", func(t *testing.T) {
const tmpl = `{
"id": "JSON-UNKNOWN-FIELD",
"info": {
"name": "strict json regression",
"author": "anonymous",
"severity": "info",
"tags": "test"
},
"tcp": [{
"host": ["{{Hostname}}"],
"port": "80",
"name": "first_read",
"req-condition": true,
"bogus_field_42": "anything",
"inputs": [{"data": "X"}],
"matchers": [{"type": "word", "words": ["HTTP"]}]
}]
}`
dir := t.TempDir()
strictPath := filepath.Join(dir, "tmpl-strict.json")
require.NoError(t, os.WriteFile(strictPath, []byte(tmpl), 0o600))
// Strict mode (default): unknown fields must be rejected.
strictParser := NewParser()
_, err := strictParser.ParseTemplate(strictPath, disk.NewCatalog(""))
require.Error(t, err, "expected strict JSON decode to reject unknown fields")
require.Contains(t, err.Error(), "unknown field", "expected unknown-field error, got: %v", err)
// Lax mode: when the parser opts out via NoStrictSyntax (set from the
// `-no-strict-syntax` flag) the same template must still parse.
laxParser := NewParser()
laxParser.NoStrictSyntax = true
laxPath := filepath.Join(dir, "tmpl-lax.json")
require.NoError(t, os.WriteFile(laxPath, []byte(tmpl), 0o600))
_, err = laxParser.ParseTemplate(laxPath, disk.NewCatalog(""))
require.NoError(t, err, "NoStrictSyntax should allow unknown fields")
})
// json.Decoder by design only consumes one top-level value. Without an
// explicit EOF check, concatenated JSON documents would silently load
// only the first — e.g. `{"id":"safe"...}{"id":"hijack"...}` would scan
// under the safe id while the second document is ignored.
t.Run("strictJSONRejectsTrailingData", func(t *testing.T) {
const tmpl = `{
"id": "JSON-TRAILING-DATA",
"info": {
"name": "trailing data regression",
"author": "anonymous",
"severity": "info"
},
"http": [{
"method": "GET",
"path": ["{{BaseURL}}"],
"matchers": [{"type": "word", "words": ["HTTP"]}]
}]
}
{"id":"HIJACK","info":{"name":"x","author":"y","severity":"high"}}
`
dir := t.TempDir()
path := filepath.Join(dir, "tmpl.json")
require.NoError(t, os.WriteFile(path, []byte(tmpl), 0o600))
_, err := NewParser().ParseTemplate(path, disk.NewCatalog(""))
require.Error(t, err, "expected strict JSON to reject trailing data")
require.Contains(t, err.Error(), "trailing data", "expected trailing-data error, got: %v", err)
})
// Strictness is a per-parser setting (not a process global) so two
// parsers in the same process with different `-no-strict-syntax` values
// must not interfere with each other. Cf. concurrent-engines support
// introduced in #6322.
t.Run("strictJSONIsPerParser", func(t *testing.T) {
const tmpl = `{
"id": "JSON-PER-PARSER",
"info": {
"name": "per-parser strictness",
"author": "anonymous",
"severity": "info"
},
"http": [{
"method": "GET",
"path": ["{{BaseURL}}"],
"matchers": [{"type": "word", "words": ["HTTP"]}],
"bogus_field": "ignore me"
}]
}`
dir := t.TempDir()
strictPath := filepath.Join(dir, "per-parser-strict.json")
laxPath := filepath.Join(dir, "per-parser-lax.json")
require.NoError(t, os.WriteFile(strictPath, []byte(tmpl), 0o600))
require.NoError(t, os.WriteFile(laxPath, []byte(tmpl), 0o600))
strictParser := NewParser()
laxParser := NewParser()
laxParser.NoStrictSyntax = true
_, strictErr := strictParser.ParseTemplate(strictPath, disk.NewCatalog(""))
_, laxErr := laxParser.ParseTemplate(laxPath, disk.NewCatalog(""))
require.Error(t, strictErr, "strict parser must reject unknown field")
require.Contains(t, strictErr.Error(), "unknown field")
require.NoError(t, laxErr, "lax parser must accept the same template")
})
t.Run("strictYAMLRejectsUnknownFields", func(t *testing.T) {
const tmpl = `id: yaml-unknown-field
info:
name: strict yaml regression
author: anonymous
severity: info
http:
- method: GET
path:
- "{{BaseURL}}"
bogus_field: ignore me
matchers:
- type: word
words:
- HTTP
`
dir := t.TempDir()
strictPath := filepath.Join(dir, "tmpl-strict.yaml")
laxPath := filepath.Join(dir, "tmpl-lax.yaml")
require.NoError(t, os.WriteFile(strictPath, []byte(tmpl), 0o600))
require.NoError(t, os.WriteFile(laxPath, []byte(tmpl), 0o600))
_, strictErr := NewParser().ParseTemplate(strictPath, disk.NewCatalog(""))
laxParser := NewParser()
laxParser.NoStrictSyntax = true
_, laxErr := laxParser.ParseTemplate(laxPath, disk.NewCatalog(""))
require.Error(t, strictErr, "strict YAML decode must reject unknown fields")
require.Contains(t, strictErr.Error(), "bogus_field")
require.NoError(t, laxErr, "NoStrictSyntax should allow unknown YAML fields")
})
t.Run("strictYAMLRejectsDuplicateFields", func(t *testing.T) {
const tmpl = `id: yaml-duplicate-field
id: yaml-duplicate-field-overwrite
info:
name: duplicate yaml regression
author: anonymous
severity: info
http:
- method: GET
path:
- "{{BaseURL}}"
matchers:
- type: word
words:
- HTTP
`
dir := t.TempDir()
path := filepath.Join(dir, "tmpl.yaml")
require.NoError(t, os.WriteFile(path, []byte(tmpl), 0o600))
_, err := NewParser().ParseTemplate(path, disk.NewCatalog(""))
require.Error(t, err, "strict YAML decode must reject duplicate fields")
require.Contains(t, err.Error(), "already")
})
t.Run("laxYAMLAllowsDuplicateFields", func(t *testing.T) {
const tmpl = `id: yaml-duplicate-field
id: yaml-duplicate-field-overwrite
info:
name: duplicate yaml regression
author: anonymous
severity: info
http:
- method: GET
path:
- "{{BaseURL}}"
matchers:
- type: word
words:
- HTTP
`
dir := t.TempDir()
path := filepath.Join(dir, "tmpl.yaml")
require.NoError(t, os.WriteFile(path, []byte(tmpl), 0o600))
laxParser := NewParser()
laxParser.NoStrictSyntax = true
parsed, err := laxParser.ParseTemplate(path, disk.NewCatalog(""))
require.NoError(t, err, "NoStrictSyntax should preserve yaml.v2 duplicate-field behavior")
template, ok := parsed.(*Template)
require.True(t, ok)
require.Equal(t, "yaml-duplicate-field-overwrite", template.ID)
})
t.Run("YAMLPreservesMultiProtocolOrder", func(t *testing.T) {
const tmpl = `id: yaml-protocol-order
info:
name: protocol order regression
author: anonymous
severity: info
dns:
- name: "{{FQDN}}"
type: cname
http:
- method: GET
path:
- "{{BaseURL}}"
matchers:
- type: word
words:
- HTTP
`
dir := t.TempDir()
path := filepath.Join(dir, "tmpl.yaml")
require.NoError(t, os.WriteFile(path, []byte(tmpl), 0o600))
parsed, err := NewParser().ParseTemplate(path, disk.NewCatalog(""))
require.NoError(t, err)
template, ok := parsed.(*Template)
require.True(t, ok)
require.Len(t, template.RequestsQueue, 2)
require.Equal(t, "dns", template.RequestsQueue[0].Type().String())
require.Equal(t, "http", template.RequestsQueue[1].Type().String())
})
t.Run("invalidTemplateID", func(t *testing.T) {
tt := []struct {
id string
success bool
}{
{id: "A-B-C", success: true},
{id: "A-B-C-1", success: true},
{id: "CVE_2021_27330", success: true},
{id: "ABC DEF", success: false},
{id: "_-__AAA_", success: false},
{id: " CVE-2021-27330", success: false},
{id: "CVE-2021-27330 ", success: false},
{id: "CVE-2021-27330-", success: false},
{id: "-CVE-2021-27330-", success: false},
{id: "CVE-2021--27330", success: false},
{id: "CVE-2021+27330", success: false},
}
for i, tc := range tt {
name := fmt.Sprintf("regexp%d", i)
t.Run(name, func(t *testing.T) {
template := &Template{
ID: tc.id,
Info: model.Info{
Name: "Valid template",
Authors: stringslice.StringSlice{Value: "Author"},
SeverityHolder: severity.Holder{Severity: severity.Medium},
},
}
p.parsedTemplatesCache.Store(name, template, nil, nil)
tagFilter, err := NewTagFilter(&TagFilterConfig{})
require.Nil(t, err)
success, err := p.LoadTemplate(name, tagFilter, nil, catalog)
if tc.success {
require.NoError(t, err)
require.True(t, success)
} else {
require.ErrorContains(t, err, "invalid field format for 'id' (allowed format is ^([a-zA-Z0-9]+[-_])*[a-zA-Z0-9]+$)")
require.False(t, success)
}
})
}
})
}