diff --git a/lib/config.go b/lib/config.go index 023c4bfa94..66a2a9ef4c 100644 --- a/lib/config.go +++ b/lib/config.go @@ -339,6 +339,21 @@ func WithScanStrategy(strategy string) NucleiSDKOptions { // OutputWriter type OutputWriter output.Writer +// WithResultCallback sets a result callback invoked for each finding. +// +// When used with ThreadSafeNucleiEngine.ExecuteNucleiWithOpts / ExecuteNucleiWithOptsCtx, +// the callback is scoped to that execution only (combined with any GlobalResultCallback). +// When used at engine construction time, it behaves like the default result callback list. +func WithResultCallback(callback func(event *output.ResultEvent)) NucleiSDKOptions { + return func(e *NucleiEngine) error { + if callback == nil { + return nil + } + e.resultCallbacks = append(e.resultCallbacks, callback) + return nil + } +} + // UseOutputWriter allows setting custom output writer // by default a mock writer is used with user defined callback // if outputWriter is used callback will be ignored diff --git a/lib/multi.go b/lib/multi.go index 338ed15927..fd5278231c 100644 --- a/lib/multi.go +++ b/lib/multi.go @@ -5,6 +5,7 @@ import ( "time" "github.com/logrusorgru/aurora/v4" + "github.com/projectdiscovery/nuclei/v3/internal/tests/testutils" "github.com/projectdiscovery/nuclei/v3/pkg/catalog/loader" "github.com/projectdiscovery/nuclei/v3/pkg/core" "github.com/projectdiscovery/nuclei/v3/pkg/input/provider" @@ -25,11 +26,15 @@ type unsafeOptions struct { engine *core.Engine } -// createEphemeralObjects creates ephemeral nuclei objects/instances/types -func createEphemeralObjects(ctx context.Context, base *NucleiEngine, opts *types.Options) (*unsafeOptions, error) { +// createEphemeralObjects creates ephemeral nuclei objects/instances/types. +// outputWriter overrides the base engine writer when non-nil (used for per-call callbacks). +func createEphemeralObjects(ctx context.Context, base *NucleiEngine, opts *types.Options, outputWriter output.Writer) (*unsafeOptions, error) { + if outputWriter == nil { + outputWriter = base.customWriter + } u := &unsafeOptions{} u.executerOpts = &protocols.ExecutorOptions{ - Output: base.customWriter, + Output: outputWriter, Options: opts, Progress: base.customProgress, Catalog: base.catalog, @@ -40,6 +45,11 @@ func createEphemeralObjects(ctx context.Context, base *NucleiEngine, opts *types ResumeCfg: types.NewResumeCfg(), Parser: base.parser, Browser: base.browserInstance, + // Thread-safe executes can run concurrently with different Output writers. + // The compiled-template cache shallow-copies requests and mutates shared + // ExecutorOptions.Output via UpdateOptions/ApplyNewEngineOptions, which + // would otherwise route all findings to whichever call last won the race. + DoNotCache: true, } if opts.ShouldUseHostError() && base.hostErrCache != nil { u.executerOpts.HostErrorsCache = base.hostErrCache @@ -57,6 +67,30 @@ func createEphemeralObjects(ctx context.Context, base *NucleiEngine, opts *types return u, nil } +// resolveEphemeralOutput combines the base/global writer with any per-call result callbacks. +// Global callbacks keep working; per-call callbacks are isolated to this execution. +func resolveEphemeralOutput(base, call *NucleiEngine) output.Writer { + out := base.customWriter + if call == nil || len(call.resultCallbacks) == 0 { + return out + } + + callbacks := append([]func(event *output.ResultEvent){}, call.resultCallbacks...) + callWriter := testutils.NewMockOutputWriter(call.opts.OmitTemplate) + callWriter.WriteCallback = func(event *output.ResultEvent) { + for _, cb := range callbacks { + if cb != nil { + cb(event) + } + } + } + + if out == nil { + return callWriter + } + return output.NewMultiWriter(out, callWriter) +} + // closeEphemeralObjects closes all resources used by ephemeral nuclei objects/instances/types func closeEphemeralObjects(u *unsafeOptions) { if u.executerOpts.RateLimiter != nil { @@ -113,14 +147,15 @@ func (e *ThreadSafeNucleiEngine) GlobalLoadAllTemplates() error { } // GlobalResultCallback sets a callback function which will be called for each result +// across all ExecuteNucleiWithOpts invocations. For a callback scoped to a single +// execution, pass WithResultCallback in that call's opts instead. func (e *ThreadSafeNucleiEngine) GlobalResultCallback(callback func(event *output.ResultEvent)) { e.eng.resultCallbacks = []func(*output.ResultEvent){callback} } -// ExecuteNucleiWithOptsCtx executes templates on targets and calls callback on each result(only if results are found) -// This method can be called concurrently and it will use some global resources but can be run parallelly -// by invoking this method with different options and targets -// Note: Not all options are thread-safe. this method will throw error if you try to use non-thread-safe options +// ExecuteNucleiWithOptsCtx executes templates on targets and can be called concurrently. +// Pass WithResultCallback in opts for a per-execution result callback (combined with any +// GlobalResultCallback). Not all options are thread-safe. func (e *ThreadSafeNucleiEngine) ExecuteNucleiWithOptsCtx(ctx context.Context, targets []string, opts ...NucleiSDKOptions) error { baseOpts := e.eng.opts.Copy() tmpEngine := &NucleiEngine{opts: baseOpts, mode: threadSafe} @@ -131,7 +166,7 @@ func (e *ThreadSafeNucleiEngine) ExecuteNucleiWithOptsCtx(ctx context.Context, t } // create ephemeral nuclei objects/instances/types using base nuclei engine - unsafeOpts, err := createEphemeralObjects(ctx, e.eng, tmpEngine.opts) + unsafeOpts, err := createEphemeralObjects(ctx, e.eng, tmpEngine.opts, resolveEphemeralOutput(e.eng, tmpEngine)) if err != nil { return err } diff --git a/lib/result_callback_test.go b/lib/result_callback_test.go new file mode 100644 index 0000000000..ca5b7ad060 --- /dev/null +++ b/lib/result_callback_test.go @@ -0,0 +1,168 @@ +package nuclei_test + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + + nuclei "github.com/projectdiscovery/nuclei/v3/lib" + "github.com/projectdiscovery/nuclei/v3/pkg/output" + "github.com/stretchr/testify/require" +) + +func TestThreadSafeWithResultCallbackIsolation(t *testing.T) { + templatePath := writeSDKMatchTemplate(t) + + srvA := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("token-A-unique")) + })) + t.Cleanup(srvA.Close) + + srvB := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("token-B-unique")) + })) + t.Cleanup(srvB.Close) + + ne, err := nuclei.NewThreadSafeNucleiEngineCtx(context.Background()) + require.NoError(t, err) + t.Cleanup(ne.Close) + + var ( + mu sync.Mutex + callbackA []string + callbackB []string + globalURLs []string + globalCount int + errA, errB error + ) + + ne.GlobalResultCallback(func(event *output.ResultEvent) { + mu.Lock() + defer mu.Unlock() + globalCount++ + globalURLs = append(globalURLs, eventMatchedURL(event)) + }) + + var wg sync.WaitGroup + wg.Add(2) + + go func() { + defer wg.Done() + errA = ne.ExecuteNucleiWithOptsCtx(context.Background(), []string{srvA.URL}, + nuclei.WithTemplatesOrWorkflows(nuclei.TemplateSources{Templates: []string{templatePath}}), + nuclei.WithTemplateFilters(nuclei.TemplateFilters{IDs: []string{"sdk-callback-match"}}), + nuclei.WithResultCallback(func(event *output.ResultEvent) { + mu.Lock() + defer mu.Unlock() + callbackA = append(callbackA, eventMatchedURL(event)) + }), + ) + }() + + go func() { + defer wg.Done() + errB = ne.ExecuteNucleiWithOptsCtx(context.Background(), []string{srvB.URL}, + nuclei.WithTemplatesOrWorkflows(nuclei.TemplateSources{Templates: []string{templatePath}}), + nuclei.WithTemplateFilters(nuclei.TemplateFilters{IDs: []string{"sdk-callback-match"}}), + nuclei.WithResultCallback(func(event *output.ResultEvent) { + mu.Lock() + defer mu.Unlock() + callbackB = append(callbackB, eventMatchedURL(event)) + }), + ) + }() + + wg.Wait() + + require.NoError(t, errA) + require.NoError(t, errB) + + mu.Lock() + defer mu.Unlock() + + require.NotEmpty(t, callbackA, "per-call callback A should receive results") + require.NotEmpty(t, callbackB, "per-call callback B should receive results") + for _, matched := range callbackA { + require.Contains(t, matched, srvA.URL, "callback A must only see server A") + require.NotContains(t, matched, srvB.URL, "callback A must not see server B") + } + for _, matched := range callbackB { + require.Contains(t, matched, srvB.URL, "callback B must only see server B") + require.NotContains(t, matched, srvA.URL, "callback B must not see server A") + } + + // Global callback still sees both executions (no regression). + require.GreaterOrEqual(t, globalCount, 2) + require.NotEmpty(t, globalURLs) +} + +func TestThreadSafeGlobalCallbackWithoutPerCallStillWorks(t *testing.T) { + templatePath := writeSDKMatchTemplate(t) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("token-A-unique")) + })) + t.Cleanup(srv.Close) + + ne, err := nuclei.NewThreadSafeNucleiEngineCtx(context.Background()) + require.NoError(t, err) + t.Cleanup(ne.Close) + + var got int + ne.GlobalResultCallback(func(event *output.ResultEvent) { + got++ + }) + + err = ne.ExecuteNucleiWithOptsCtx(context.Background(), []string{srv.URL}, + nuclei.WithTemplatesOrWorkflows(nuclei.TemplateSources{Templates: []string{templatePath}}), + nuclei.WithTemplateFilters(nuclei.TemplateFilters{IDs: []string{"sdk-callback-match"}}), + ) + require.NoError(t, err) + require.GreaterOrEqual(t, got, 1, "global callback should still receive results without WithResultCallback") +} + +func TestWithResultCallbackNilIsNoop(t *testing.T) { + ne, err := nuclei.NewThreadSafeNucleiEngineCtx(context.Background(), nuclei.WithResultCallback(nil)) + require.NoError(t, err) + ne.Close() +} + +func writeSDKMatchTemplate(t *testing.T) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "sdk-callback-match.yaml") + content := `id: sdk-callback-match +info: + name: SDK callback match + author: nuclei-sdk-test + severity: info +http: + - method: GET + path: + - "{{BaseURL}}/" + matchers: + - type: word + words: + - "token-" +` + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + return path +} + +// eventMatchedURL prefers Matched/URL over Host (Host omits the port). +func eventMatchedURL(event *output.ResultEvent) string { + if event == nil { + return "" + } + if event.Matched != "" { + return event.Matched + } + if event.URL != "" { + return event.URL + } + return event.Host +}