Skip to content

Commit f26996c

Browse files
hdmMzack9999dwisiswant0
authored
Remove singletons from Nuclei engine (continuation of #6210) (#6296)
* introducing execution id * wip * . * adding separate execution context id * lint * vet * fixing pg dialers * test ignore * fixing loader FD limit * test * fd fix * wip: remove CloseProcesses() from dev merge * wip: fix merge issue * protocolstate: stop memguarding on last dialer delete * avoid data race in dialers.RawHTTPClient * use shared logger and avoid race conditions * use shared logger and avoid race conditions * go mod * patch executionId into compiled template cache * clean up comment in Parse * go mod update * bump echarts * address merge issues * fix use of gologger * switch cmd/nuclei to options.Logger * address merge issues with go.mod * go vet: address copy of lock with new Copy function * fixing tests * disable speed control * fix nil ExecuterOptions * removing deprecated code * fixing result print * default logger * cli default logger * filter warning from results * fix performance test * hardcoding path * disable upload * refactor(runner): uses `Warning` instead of `Print` for `pdcpUploadErrMsg` Signed-off-by: Dwi Siswanto <[email protected]> * Revert "disable upload" This reverts commit 114fbe6. * Revert "hardcoding path" This reverts commit cf12ca8. --------- Signed-off-by: Dwi Siswanto <[email protected]> Co-authored-by: Mzack9999 <[email protected]> Co-authored-by: Dwi Siswanto <[email protected]> Co-authored-by: Dwi Siswanto <[email protected]>
1 parent 285c5e1 commit f26996c

File tree

180 files changed

+2271
-1031
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

180 files changed

+2271
-1031
lines changed

.github/workflows/tests.yaml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,11 @@ jobs:
5959
working-directory: examples/simple/
6060
# - run: go run . # Temporarily disabled very flaky in github actions
6161
# working-directory: examples/advanced/
62-
- name: "with Speed Control"
63-
run: go run .
64-
working-directory: examples/with_speed_control/
62+
63+
# TODO: FIX with ExecutionID (ref: https://github.com/projectdiscovery/nuclei/pull/6296)
64+
# - name: "with Speed Control"
65+
# run: go run .
66+
# working-directory: examples/with_speed_control/
6567

6668
integration:
6769
name: "Integration tests"

cmd/functional-test/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ func runFunctionalTests(debug bool) (error, bool) {
4242
return errors.Wrap(err, "could not open test cases"), true
4343
}
4444
defer func() {
45-
_ = file.Close()
46-
}()
45+
_ = file.Close()
46+
}()
4747

4848
errored, failedTestCases := runTestCases(file, debug)
4949

cmd/integration-test/headless.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,8 @@ func (h *headlessFileUpload) Execute(filePath string) error {
179179
}
180180

181181
defer func() {
182-
_ = file.Close()
183-
}()
182+
_ = file.Close()
183+
}()
184184

185185
content, err := io.ReadAll(file)
186186
if err != nil {
@@ -238,8 +238,8 @@ func (h *headlessFileUploadNegative) Execute(filePath string) error {
238238
}
239239

240240
defer func() {
241-
_ = file.Close()
242-
}()
241+
_ = file.Close()
242+
}()
243243

244244
content, err := io.ReadAll(file)
245245
if err != nil {

cmd/integration-test/http.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -948,8 +948,8 @@ func (h *httpRequestSelfContained) Execute(filePath string) error {
948948
_ = server.ListenAndServe()
949949
}()
950950
defer func() {
951-
_ = server.Close()
952-
}()
951+
_ = server.Close()
952+
}()
953953

954954
results, err := testutils.RunNucleiTemplateAndGetResults(filePath, "", debug, "-esc")
955955
if err != nil {
@@ -986,8 +986,8 @@ func (h *httpRequestSelfContainedWithParams) Execute(filePath string) error {
986986
_ = server.ListenAndServe()
987987
}()
988988
defer func() {
989-
_ = server.Close()
990-
}()
989+
_ = server.Close()
990+
}()
991991

992992
results, err := testutils.RunNucleiTemplateAndGetResults(filePath, "", debug, "-esc")
993993
if err != nil {
@@ -1021,8 +1021,8 @@ func (h *httpRequestSelfContainedFileInput) Execute(filePath string) error {
10211021
_ = server.ListenAndServe()
10221022
}()
10231023
defer func() {
1024-
_ = server.Close()
1025-
}()
1024+
_ = server.Close()
1025+
}()
10261026

10271027
// create temp file
10281028
FileLoc, err := os.CreateTemp("", "self-contained-payload-*.txt")
@@ -1033,8 +1033,8 @@ func (h *httpRequestSelfContainedFileInput) Execute(filePath string) error {
10331033
return errorutil.NewWithErr(err).Msgf("failed to write payload to temp file")
10341034
}
10351035
defer func() {
1036-
_ = FileLoc.Close()
1037-
}()
1036+
_ = FileLoc.Close()
1037+
}()
10381038

10391039
results, err := testutils.RunNucleiTemplateAndGetResults(filePath, "", debug, "-V", "test="+FileLoc.Name(), "-esc")
10401040
if err != nil {

cmd/integration-test/integration-test.go

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"flag"
55
"fmt"
66
"os"
7+
"regexp"
78
"runtime"
89
"strings"
910

@@ -90,8 +91,8 @@ func main() {
9091
defer fuzzplayground.Cleanup()
9192
server := fuzzplayground.GetPlaygroundServer()
9293
defer func() {
93-
_ = server.Close()
94-
}()
94+
_ = server.Close()
95+
}()
9596
go func() {
9697
if err := server.Start("localhost:8082"); err != nil {
9798
if !strings.Contains(err.Error(), "Server closed") {
@@ -210,7 +211,7 @@ func execute(testCase testutils.TestCase, templatePath string) (string, error) {
210211
}
211212

212213
func expectResultsCount(results []string, expectedNumbers ...int) error {
213-
results = filterHeadlessLogs(results)
214+
results = filterLines(results)
214215
match := sliceutil.Contains(expectedNumbers, len(results))
215216
if !match {
216217
return fmt.Errorf("incorrect number of results: %d (actual) vs %v (expected) \nResults:\n\t%s\n", len(results), expectedNumbers, strings.Join(results, "\n\t")) // nolint:all
@@ -224,6 +225,13 @@ func normalizeSplit(str string) []string {
224225
})
225226
}
226227

228+
// filterLines applies all filtering functions to the results
229+
func filterLines(results []string) []string {
230+
results = filterHeadlessLogs(results)
231+
results = filterUnsignedTemplatesWarnings(results)
232+
return results
233+
}
234+
227235
// if chromium is not installed go-rod installs it in .cache directory
228236
// this function filters out the logs from download and installation
229237
func filterHeadlessLogs(results []string) []string {
@@ -237,3 +245,16 @@ func filterHeadlessLogs(results []string) []string {
237245
}
238246
return filtered
239247
}
248+
249+
// filterUnsignedTemplatesWarnings filters out warning messages about unsigned templates
250+
func filterUnsignedTemplatesWarnings(results []string) []string {
251+
filtered := []string{}
252+
unsignedTemplatesRegex := regexp.MustCompile(`Loading \d+ unsigned templates for scan\. Use with caution\.`)
253+
for _, result := range results {
254+
if unsignedTemplatesRegex.MatchString(result) {
255+
continue
256+
}
257+
filtered = append(filtered, result)
258+
}
259+
return filtered
260+
}

cmd/integration-test/library.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,21 @@ func executeNucleiAsLibrary(templatePath, templateURL string) ([]string, error)
6868
cache := hosterrorscache.New(30, hosterrorscache.DefaultMaxHostsCount, nil)
6969
defer cache.Close()
7070

71+
defaultOpts := types.DefaultOptions()
72+
defaultOpts.ExecutionId = "test"
73+
7174
mockProgress := &testutils.MockProgressClient{}
72-
reportingClient, err := reporting.New(&reporting.Options{}, "", false)
75+
reportingClient, err := reporting.New(&reporting.Options{ExecutionId: defaultOpts.ExecutionId}, "", false)
7376
if err != nil {
7477
return nil, err
7578
}
7679
defer reportingClient.Close()
7780

78-
defaultOpts := types.DefaultOptions()
7981
_ = protocolstate.Init(defaultOpts)
8082
_ = protocolinit.Init(defaultOpts)
8183

84+
defer protocolstate.Close(defaultOpts.ExecutionId)
85+
8286
defaultOpts.Templates = goflags.StringSlice{templatePath}
8387
defaultOpts.ExcludeTags = config.ReadIgnoreFile().Tags
8488

@@ -100,7 +104,7 @@ func executeNucleiAsLibrary(templatePath, templateURL string) ([]string, error)
100104
ratelimiter := ratelimit.New(context.Background(), 150, time.Second)
101105
defer ratelimiter.Stop()
102106

103-
executerOpts := protocols.ExecutorOptions{
107+
executerOpts := &protocols.ExecutorOptions{
104108
Output: outputWriter,
105109
Options: defaultOpts,
106110
Progress: mockProgress,
@@ -116,7 +120,7 @@ func executeNucleiAsLibrary(templatePath, templateURL string) ([]string, error)
116120
engine := core.New(defaultOpts)
117121
engine.SetExecuterOptions(executerOpts)
118122

119-
workflowLoader, err := parsers.NewLoader(&executerOpts)
123+
workflowLoader, err := parsers.NewLoader(executerOpts)
120124
if err != nil {
121125
log.Fatalf("Could not create workflow loader: %s\n", err)
122126
}
@@ -128,7 +132,7 @@ func executeNucleiAsLibrary(templatePath, templateURL string) ([]string, error)
128132
}
129133
store.Load()
130134

131-
_ = engine.Execute(context.Background(), store.Templates(), provider.NewSimpleInputProviderWithUrls(templateURL))
135+
_ = engine.Execute(context.Background(), store.Templates(), provider.NewSimpleInputProviderWithUrls(defaultOpts.ExecutionId, templateURL))
132136
engine.WorkPool().Wait() // Wait for the scan to finish
133137

134138
return results, nil

cmd/integration-test/network.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ func (h *networkBasic) Execute(filePath string) error {
3434

3535
ts := testutils.NewTCPServer(nil, defaultStaticPort, func(conn net.Conn) {
3636
defer func() {
37-
_ = conn.Close()
38-
}()
37+
_ = conn.Close()
38+
}()
3939

4040
data, err := reader.ConnReadNWithTimeout(conn, 4, time.Duration(5)*time.Second)
4141
if err != nil {
@@ -71,8 +71,8 @@ func (h *networkMultiStep) Execute(filePath string) error {
7171

7272
ts := testutils.NewTCPServer(nil, defaultStaticPort, func(conn net.Conn) {
7373
defer func() {
74-
_ = conn.Close()
75-
}()
74+
_ = conn.Close()
75+
}()
7676

7777
data, err := reader.ConnReadNWithTimeout(conn, 5, time.Duration(5)*time.Second)
7878
if err != nil {
@@ -119,8 +119,8 @@ type networkRequestSelContained struct{}
119119
func (h *networkRequestSelContained) Execute(filePath string) error {
120120
ts := testutils.NewTCPServer(nil, defaultStaticPort, func(conn net.Conn) {
121121
defer func() {
122-
_ = conn.Close()
123-
}()
122+
_ = conn.Close()
123+
}()
124124

125125
_, _ = conn.Write([]byte("Authentication successful"))
126126
})
@@ -141,8 +141,8 @@ func (h *networkVariables) Execute(filePath string) error {
141141

142142
ts := testutils.NewTCPServer(nil, defaultStaticPort, func(conn net.Conn) {
143143
defer func() {
144-
_ = conn.Close()
145-
}()
144+
_ = conn.Close()
145+
}()
146146

147147
data, err := reader.ConnReadNWithTimeout(conn, 4, time.Duration(5)*time.Second)
148148
if err != nil {
@@ -171,8 +171,8 @@ type networkPort struct{}
171171
func (n *networkPort) Execute(filePath string) error {
172172
ts := testutils.NewTCPServer(nil, 23846, func(conn net.Conn) {
173173
defer func() {
174-
_ = conn.Close()
175-
}()
174+
_ = conn.Close()
175+
}()
176176

177177
data, err := reader.ConnReadNWithTimeout(conn, 4, time.Duration(5)*time.Second)
178178
if err != nil {
@@ -206,8 +206,8 @@ func (n *networkPort) Execute(filePath string) error {
206206
// this is positive test case where we expect port to be overridden and 34567 to be used
207207
ts2 := testutils.NewTCPServer(nil, 34567, func(conn net.Conn) {
208208
defer func() {
209-
_ = conn.Close()
210-
}()
209+
_ = conn.Close()
210+
}()
211211

212212
data, err := reader.ConnReadNWithTimeout(conn, 4, time.Duration(5)*time.Second)
213213
if err != nil {

cmd/integration-test/profile-loader.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ var profileLoaderTestcases = []TestCaseInfo{
1616
type profileLoaderByRelFile struct{}
1717

1818
func (h *profileLoaderByRelFile) Execute(testName string) error {
19-
results, err := testutils.RunNucleiWithArgsAndGetResults(false, "-tl", "-tp", "cloud.yml")
19+
results, err := testutils.RunNucleiWithArgsAndGetResults(debug, "-tl", "-tp", "cloud.yml")
2020
if err != nil {
2121
return errorutil.NewWithErr(err).Msgf("failed to load template with id")
2222
}
@@ -29,7 +29,7 @@ func (h *profileLoaderByRelFile) Execute(testName string) error {
2929
type profileLoaderById struct{}
3030

3131
func (h *profileLoaderById) Execute(testName string) error {
32-
results, err := testutils.RunNucleiWithArgsAndGetResults(false, "-tl", "-tp", "cloud")
32+
results, err := testutils.RunNucleiWithArgsAndGetResults(debug, "-tl", "-tp", "cloud")
3333
if err != nil {
3434
return errorutil.NewWithErr(err).Msgf("failed to load template with id")
3535
}
@@ -43,7 +43,7 @@ func (h *profileLoaderById) Execute(testName string) error {
4343
type customProfileLoader struct{}
4444

4545
func (h *customProfileLoader) Execute(filepath string) error {
46-
results, err := testutils.RunNucleiWithArgsAndGetResults(false, "-tl", "-tp", filepath)
46+
results, err := testutils.RunNucleiWithArgsAndGetResults(debug, "-tl", "-tp", filepath)
4747
if err != nil {
4848
return errorutil.NewWithErr(err).Msgf("failed to load template with id")
4949
}

0 commit comments

Comments
 (0)