Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/lib/multi.go
2061 views
1
package nuclei
2
3
import (
4
"context"
5
"time"
6
7
"github.com/logrusorgru/aurora"
8
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/loader"
9
"github.com/projectdiscovery/nuclei/v3/pkg/core"
10
"github.com/projectdiscovery/nuclei/v3/pkg/input/provider"
11
"github.com/projectdiscovery/nuclei/v3/pkg/loader/workflow"
12
"github.com/projectdiscovery/nuclei/v3/pkg/output"
13
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
14
"github.com/projectdiscovery/nuclei/v3/pkg/types"
15
"github.com/projectdiscovery/ratelimit"
16
"github.com/projectdiscovery/utils/errkit"
17
"github.com/rs/xid"
18
)
19
20
// unsafeOptions are those nuclei objects/instances/types
21
// that are required to run nuclei engine but are not thread safe
22
// hence they are ephemeral and are created on every ExecuteNucleiWithOpts invocation
23
// in ThreadSafeNucleiEngine
24
type unsafeOptions struct {
25
executerOpts *protocols.ExecutorOptions
26
engine *core.Engine
27
}
28
29
// createEphemeralObjects creates ephemeral nuclei objects/instances/types
30
func createEphemeralObjects(ctx context.Context, base *NucleiEngine, opts *types.Options) (*unsafeOptions, error) {
31
u := &unsafeOptions{}
32
u.executerOpts = &protocols.ExecutorOptions{
33
Output: base.customWriter,
34
Options: opts,
35
Progress: base.customProgress,
36
Catalog: base.catalog,
37
IssuesClient: base.rc,
38
RateLimiter: base.rateLimiter,
39
Interactsh: base.interactshClient,
40
HostErrorsCache: base.hostErrCache,
41
Colorizer: aurora.NewAurora(true),
42
ResumeCfg: types.NewResumeCfg(),
43
Parser: base.parser,
44
Browser: base.browserInstance,
45
}
46
if opts.ShouldUseHostError() && base.hostErrCache != nil {
47
u.executerOpts.HostErrorsCache = base.hostErrCache
48
}
49
if opts.RateLimitMinute > 0 {
50
opts.RateLimit = opts.RateLimitMinute
51
opts.RateLimitDuration = time.Minute
52
}
53
if opts.RateLimit > 0 && opts.RateLimitDuration == 0 {
54
opts.RateLimitDuration = time.Second
55
}
56
if opts.RateLimit == 0 && opts.RateLimitDuration == 0 {
57
u.executerOpts.RateLimiter = ratelimit.NewUnlimited(ctx)
58
} else {
59
u.executerOpts.RateLimiter = ratelimit.New(ctx, uint(opts.RateLimit), opts.RateLimitDuration)
60
}
61
u.engine = core.New(opts)
62
u.engine.SetExecuterOptions(u.executerOpts)
63
return u, nil
64
}
65
66
// closeEphemeralObjects closes all resources used by ephemeral nuclei objects/instances/types
67
func closeEphemeralObjects(u *unsafeOptions) {
68
if u.executerOpts.RateLimiter != nil {
69
u.executerOpts.RateLimiter.Stop()
70
}
71
// dereference all objects that were inherited from base nuclei engine
72
// since these are meant to be closed globally by base nuclei engine
73
u.executerOpts.Output = nil
74
u.executerOpts.IssuesClient = nil
75
u.executerOpts.Interactsh = nil
76
u.executerOpts.HostErrorsCache = nil
77
u.executerOpts.Progress = nil
78
u.executerOpts.Catalog = nil
79
u.executerOpts.Parser = nil
80
}
81
82
// ThreadSafeNucleiEngine is a tweaked version of nuclei.Engine whose methods are thread-safe
83
// and can be used concurrently. Non-thread-safe methods start with Global prefix
84
type ThreadSafeNucleiEngine struct {
85
eng *NucleiEngine
86
}
87
88
// NewThreadSafeNucleiEngine creates a new nuclei engine with given options
89
// whose methods are thread-safe and can be used concurrently
90
// Note: Non-thread-safe methods start with Global prefix
91
func NewThreadSafeNucleiEngineCtx(ctx context.Context, opts ...NucleiSDKOptions) (*ThreadSafeNucleiEngine, error) {
92
defaultOptions := types.DefaultOptions()
93
defaultOptions.ExecutionId = xid.New().String()
94
// default options
95
e := &NucleiEngine{
96
opts: defaultOptions,
97
mode: threadSafe,
98
}
99
for _, option := range opts {
100
if err := option(e); err != nil {
101
return nil, err
102
}
103
}
104
if err := e.init(ctx); err != nil {
105
return nil, err
106
}
107
return &ThreadSafeNucleiEngine{eng: e}, nil
108
}
109
110
// Deprecated: use NewThreadSafeNucleiEngineCtx instead
111
func NewThreadSafeNucleiEngine(opts ...NucleiSDKOptions) (*ThreadSafeNucleiEngine, error) {
112
return NewThreadSafeNucleiEngineCtx(context.Background(), opts...)
113
}
114
115
// GlobalLoadAllTemplates loads all templates from nuclei-templates repo
116
// This method will load all templates based on filters given at the time of nuclei engine creation in opts
117
func (e *ThreadSafeNucleiEngine) GlobalLoadAllTemplates() error {
118
return e.eng.LoadAllTemplates()
119
}
120
121
// GlobalResultCallback sets a callback function which will be called for each result
122
func (e *ThreadSafeNucleiEngine) GlobalResultCallback(callback func(event *output.ResultEvent)) {
123
e.eng.resultCallbacks = []func(*output.ResultEvent){callback}
124
}
125
126
// ExecuteNucleiWithOptsCtx executes templates on targets and calls callback on each result(only if results are found)
127
// This method can be called concurrently and it will use some global resources but can be runned parallelly
128
// by invoking this method with different options and targets
129
// Note: Not all options are thread-safe. this method will throw error if you try to use non-thread-safe options
130
func (e *ThreadSafeNucleiEngine) ExecuteNucleiWithOptsCtx(ctx context.Context, targets []string, opts ...NucleiSDKOptions) error {
131
baseOpts := e.eng.opts.Copy()
132
tmpEngine := &NucleiEngine{opts: baseOpts, mode: threadSafe}
133
for _, option := range opts {
134
if err := option(tmpEngine); err != nil {
135
return err
136
}
137
}
138
139
// create ephemeral nuclei objects/instances/types using base nuclei engine
140
unsafeOpts, err := createEphemeralObjects(ctx, e.eng, tmpEngine.opts)
141
if err != nil {
142
return err
143
}
144
// cleanup and stop all resources
145
defer closeEphemeralObjects(unsafeOpts)
146
147
// load templates
148
workflowLoader, err := workflow.NewLoader(unsafeOpts.executerOpts)
149
if err != nil {
150
return errkit.Wrapf(err, "Could not create workflow loader: %s", err)
151
}
152
unsafeOpts.executerOpts.WorkflowLoader = workflowLoader
153
154
store, err := loader.New(loader.NewConfig(tmpEngine.opts, e.eng.catalog, unsafeOpts.executerOpts))
155
if err != nil {
156
return errkit.Wrapf(err, "Could not create loader client: %s", err)
157
}
158
store.Load()
159
160
inputProvider := provider.NewSimpleInputProviderWithUrls(e.eng.opts.ExecutionId, targets...)
161
162
if len(store.Templates()) == 0 && len(store.Workflows()) == 0 {
163
return ErrNoTemplatesAvailable
164
}
165
if inputProvider.Count() == 0 {
166
return ErrNoTargetsAvailable
167
}
168
169
engine := core.New(tmpEngine.opts)
170
engine.SetExecuterOptions(unsafeOpts.executerOpts)
171
172
_ = engine.ExecuteScanWithOpts(ctx, store.Templates(), inputProvider, false)
173
174
engine.WorkPool().Wait()
175
return nil
176
}
177
178
// ExecuteNucleiWithOpts is same as ExecuteNucleiWithOptsCtx but with default context
179
// This is a placeholder and will be deprecated in future major release
180
func (e *ThreadSafeNucleiEngine) ExecuteNucleiWithOpts(targets []string, opts ...NucleiSDKOptions) error {
181
return e.ExecuteNucleiWithOptsCtx(context.Background(), targets, opts...)
182
}
183
184
// Close all resources used by nuclei engine
185
func (e *ThreadSafeNucleiEngine) Close() {
186
e.eng.Close()
187
}
188
189