Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/common/interactsh/interactsh.go
2072 views
1
package interactsh
2
3
import (
4
"bytes"
5
"fmt"
6
"os"
7
"regexp"
8
"strings"
9
"sync"
10
"sync/atomic"
11
"time"
12
13
"errors"
14
15
"github.com/Mzack9999/gcache"
16
17
"github.com/projectdiscovery/gologger"
18
"github.com/projectdiscovery/interactsh/pkg/client"
19
"github.com/projectdiscovery/interactsh/pkg/server"
20
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
21
"github.com/projectdiscovery/nuclei/v3/pkg/output"
22
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/responsehighlighter"
23
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/writer"
24
"github.com/projectdiscovery/retryablehttp-go"
25
"github.com/projectdiscovery/utils/errkit"
26
stringsutil "github.com/projectdiscovery/utils/strings"
27
)
28
29
// Client is a wrapped client for interactsh server.
30
type Client struct {
31
sync.Once
32
sync.RWMutex
33
34
options *Options
35
36
// interactsh is a client for interactsh server.
37
interactsh *client.Client
38
// requests is a stored cache for interactsh-url->request-event data.
39
requests gcache.Cache[string, *RequestData]
40
// interactions is a stored cache for interactsh-interaction->interactsh-url data
41
interactions gcache.Cache[string, []*server.Interaction]
42
// matchedTemplates is a stored cache to track matched templates
43
matchedTemplates gcache.Cache[string, bool]
44
// interactshURLs is a stored cache to track multiple interactsh markers
45
interactshURLs gcache.Cache[string, string]
46
47
eviction time.Duration
48
pollDuration time.Duration
49
cooldownDuration time.Duration
50
51
hostname string
52
53
// determines if wait the cooldown period in case of generated URL
54
generated atomic.Bool
55
matched atomic.Bool
56
}
57
58
// New returns a new interactsh server client
59
func New(options *Options) (*Client, error) {
60
requestsCache := gcache.New[string, *RequestData](options.CacheSize).LRU().Build()
61
interactionsCache := gcache.New[string, []*server.Interaction](defaultMaxInteractionsCount).LRU().Build()
62
matchedTemplateCache := gcache.New[string, bool](defaultMaxInteractionsCount).LRU().Build()
63
interactshURLCache := gcache.New[string, string](defaultMaxInteractionsCount).LRU().Build()
64
65
interactClient := &Client{
66
eviction: options.Eviction,
67
interactions: interactionsCache,
68
matchedTemplates: matchedTemplateCache,
69
interactshURLs: interactshURLCache,
70
options: options,
71
requests: requestsCache,
72
pollDuration: options.PollDuration,
73
cooldownDuration: options.CooldownPeriod,
74
}
75
return interactClient, nil
76
}
77
78
func (c *Client) poll() error {
79
if c.options.NoInteractsh {
80
// do not init if disabled
81
return ErrInteractshClientNotInitialized
82
}
83
interactsh, err := client.New(&client.Options{
84
ServerURL: c.options.ServerURL,
85
Token: c.options.Authorization,
86
DisableHTTPFallback: c.options.DisableHttpFallback,
87
HTTPClient: c.options.HTTPClient,
88
KeepAliveInterval: time.Minute,
89
})
90
if err != nil {
91
return errkit.Wrap(err, "could not create client")
92
}
93
94
c.interactsh = interactsh
95
96
interactURL := interactsh.URL()
97
interactDomain := interactURL[strings.Index(interactURL, ".")+1:]
98
gologger.Info().Msgf("Using Interactsh Server: %s", interactDomain)
99
100
c.setHostname(interactDomain)
101
102
err = interactsh.StartPolling(c.pollDuration, func(interaction *server.Interaction) {
103
request, err := c.requests.Get(interaction.UniqueID)
104
// for more context in github actions
105
if strings.EqualFold(os.Getenv("GITHUB_ACTIONS"), "true") && c.options.Debug {
106
gologger.DefaultLogger.Print().Msgf("[Interactsh]: got interaction of %v for request %v and error %v", interaction, request, err)
107
}
108
if errors.Is(err, gcache.KeyNotFoundError) || request == nil {
109
// If we don't have any request for this ID, add it to temporary
110
// lru cache, so we can correlate when we get an add request.
111
items, err := c.interactions.Get(interaction.UniqueID)
112
if errkit.Is(err, gcache.KeyNotFoundError) || items == nil {
113
_ = c.interactions.SetWithExpire(interaction.UniqueID, []*server.Interaction{interaction}, defaultInteractionDuration)
114
} else {
115
items = append(items, interaction)
116
_ = c.interactions.SetWithExpire(interaction.UniqueID, items, defaultInteractionDuration)
117
}
118
return
119
}
120
121
if requestShouldStopAtFirstMatch(request) || c.options.StopAtFirstMatch {
122
if gotItem, err := c.matchedTemplates.Get(hash(request.Event.InternalEvent)); gotItem && err == nil {
123
return
124
}
125
}
126
127
_ = c.processInteractionForRequest(interaction, request)
128
})
129
130
if err != nil {
131
return errkit.Wrap(err, "could not perform interactsh polling")
132
}
133
return nil
134
}
135
136
// requestShouldStopAtFirstmatch checks if further interactions should be stopped
137
// note: extra care should be taken while using this function since internalEvent is
138
// synchronized all the time and if caller functions has already acquired lock its best to explicitly specify that
139
// we could use `TryLock()` but that may over complicate things and need to differentiate
140
// situations whether to block or skip
141
func requestShouldStopAtFirstMatch(request *RequestData) bool {
142
request.Event.RLock()
143
defer request.Event.RUnlock()
144
145
if stop, ok := request.Event.InternalEvent[stopAtFirstMatchAttribute]; ok {
146
if v, ok := stop.(bool); ok {
147
return v
148
}
149
}
150
return false
151
}
152
153
// processInteractionForRequest processes an interaction for a request
154
func (c *Client) processInteractionForRequest(interaction *server.Interaction, data *RequestData) bool {
155
var result *operators.Result
156
var matched bool
157
data.Event.Lock()
158
data.Event.InternalEvent["interactsh_protocol"] = interaction.Protocol
159
if strings.EqualFold(interaction.Protocol, "dns") {
160
data.Event.InternalEvent["interactsh_request"] = strings.ToLower(interaction.RawRequest)
161
} else {
162
data.Event.InternalEvent["interactsh_request"] = interaction.RawRequest
163
}
164
data.Event.InternalEvent["interactsh_response"] = interaction.RawResponse
165
data.Event.InternalEvent["interactsh_ip"] = interaction.RemoteAddress
166
data.Event.Unlock()
167
168
if data.Operators != nil {
169
result, matched = data.Operators.Execute(data.Event.InternalEvent, data.MatchFunc, data.ExtractFunc, c.options.Debug || c.options.DebugRequest || c.options.DebugResponse)
170
} else {
171
// this is most likely a bug so error instead of warning
172
var templateID string
173
if data.Event.InternalEvent != nil {
174
templateID = fmt.Sprint(data.Event.InternalEvent[templateIdAttribute])
175
}
176
gologger.Error().Msgf("missing compiled operators for '%v' template", templateID)
177
}
178
179
// for more context in github actions
180
if strings.EqualFold(os.Getenv("GITHUB_ACTIONS"), "true") && c.options.Debug {
181
gologger.DefaultLogger.Print().Msgf("[Interactsh]: got result %v and status %v after processing interaction", result, matched)
182
}
183
184
if c.options.FuzzParamsFrequency != nil {
185
if !matched {
186
c.options.FuzzParamsFrequency.MarkParameter(data.Parameter, data.Request.String(), data.Operators.TemplateID)
187
} else {
188
c.options.FuzzParamsFrequency.UnmarkParameter(data.Parameter, data.Request.String(), data.Operators.TemplateID)
189
}
190
}
191
192
// if we don't match, return
193
if !matched || result == nil {
194
return false
195
}
196
c.requests.Remove(interaction.UniqueID)
197
198
if data.Event.OperatorsResult != nil {
199
data.Event.OperatorsResult.Merge(result)
200
} else {
201
data.Event.SetOperatorResult(result)
202
}
203
204
data.Event.Lock()
205
data.Event.Results = data.MakeResultFunc(data.Event)
206
for _, event := range data.Event.Results {
207
event.Interaction = interaction
208
}
209
data.Event.Unlock()
210
211
if c.options.Debug || c.options.DebugRequest || c.options.DebugResponse {
212
c.debugPrintInteraction(interaction, data.Event.OperatorsResult)
213
}
214
215
// if event is not already matched, write it to output
216
if !data.Event.InteractshMatched.Load() && writer.WriteResult(data.Event, c.options.Output, c.options.Progress, c.options.IssuesClient) {
217
data.Event.InteractshMatched.Store(true)
218
c.matched.Store(true)
219
if requestShouldStopAtFirstMatch(data) || c.options.StopAtFirstMatch {
220
_ = c.matchedTemplates.SetWithExpire(hash(data.Event.InternalEvent), true, defaultInteractionDuration)
221
}
222
}
223
224
return true
225
}
226
227
func (c *Client) AlreadyMatched(data *RequestData) bool {
228
data.Event.RLock()
229
defer data.Event.RUnlock()
230
231
return c.matchedTemplates.Has(hash(data.Event.InternalEvent))
232
}
233
234
// URL returns a new URL that can be interacted with
235
func (c *Client) URL() (string, error) {
236
// first time initialization
237
var err error
238
c.Do(func() {
239
err = c.poll()
240
})
241
if err != nil {
242
return "", errkit.Wrap(ErrInteractshClientNotInitialized, err.Error())
243
}
244
245
if c.interactsh == nil {
246
return "", ErrInteractshClientNotInitialized
247
}
248
249
c.generated.Store(true)
250
return c.interactsh.URL(), nil
251
}
252
253
// Close the interactsh clients after waiting for cooldown period.
254
func (c *Client) Close() bool {
255
if c.cooldownDuration > 0 && c.generated.Load() {
256
time.Sleep(c.cooldownDuration)
257
}
258
if c.interactsh != nil {
259
_ = c.interactsh.StopPolling()
260
_ = c.interactsh.Close()
261
}
262
263
c.requests.Purge()
264
c.interactions.Purge()
265
c.matchedTemplates.Purge()
266
c.interactshURLs.Purge()
267
268
return c.matched.Load()
269
}
270
271
// ReplaceMarkers replaces the default {{interactsh-url}} placeholders with interactsh urls
272
func (c *Client) Replace(data string, interactshURLs []string) (string, []string) {
273
return c.ReplaceWithMarker(data, interactshURLMarkerRegex, interactshURLs)
274
}
275
276
// ReplaceMarkers replaces the placeholders with interactsh urls and appends them to interactshURLs
277
func (c *Client) ReplaceWithMarker(data string, regex *regexp.Regexp, interactshURLs []string) (string, []string) {
278
for _, interactshURLMarker := range regex.FindAllString(data, -1) {
279
if url, err := c.NewURLWithData(interactshURLMarker); err == nil {
280
interactshURLs = append(interactshURLs, url)
281
data = strings.Replace(data, interactshURLMarker, url, 1)
282
}
283
}
284
return data, interactshURLs
285
}
286
287
func (c *Client) NewURL() (string, error) {
288
return c.NewURLWithData("")
289
}
290
291
func (c *Client) NewURLWithData(data string) (string, error) {
292
url, err := c.URL()
293
if err != nil {
294
return "", err
295
}
296
if url == "" {
297
return "", errors.New("empty interactsh url")
298
}
299
_ = c.interactshURLs.SetWithExpire(url, data, defaultInteractionDuration)
300
return url, nil
301
}
302
303
// MakePlaceholders does placeholders for interact URLs and other data to a map
304
func (c *Client) MakePlaceholders(urls []string, data map[string]interface{}) {
305
data["interactsh-server"] = c.getHostname()
306
for _, url := range urls {
307
if interactshURLMarker, err := c.interactshURLs.Get(url); interactshURLMarker != "" && err == nil {
308
interactshMarker := strings.TrimSuffix(strings.TrimPrefix(interactshURLMarker, "{{"), "}}")
309
310
c.interactshURLs.Remove(url)
311
312
data[interactshMarker] = url
313
urlIndex := strings.Index(url, ".")
314
if urlIndex == -1 {
315
continue
316
}
317
data[strings.Replace(interactshMarker, "url", "id", 1)] = url[:urlIndex]
318
}
319
}
320
}
321
322
// MakeResultEventFunc is a result making function for nuclei
323
type MakeResultEventFunc func(wrapped *output.InternalWrappedEvent) []*output.ResultEvent
324
325
// RequestData contains data for a request event
326
type RequestData struct {
327
MakeResultFunc MakeResultEventFunc
328
Event *output.InternalWrappedEvent
329
Operators *operators.Operators
330
MatchFunc operators.MatchFunc
331
ExtractFunc operators.ExtractFunc
332
333
Parameter string
334
Request *retryablehttp.Request
335
}
336
337
// RequestEvent is the event for a network request sent by nuclei.
338
func (c *Client) RequestEvent(interactshURLs []string, data *RequestData) {
339
for _, interactshURL := range interactshURLs {
340
id := strings.TrimRight(strings.TrimSuffix(interactshURL, c.getHostname()), ".")
341
342
if requestShouldStopAtFirstMatch(data) || c.options.StopAtFirstMatch {
343
gotItem, err := c.matchedTemplates.Get(hash(data.Event.InternalEvent))
344
if gotItem && err == nil {
345
break
346
}
347
}
348
349
interactions, err := c.interactions.Get(id)
350
if interactions != nil && err == nil {
351
for _, interaction := range interactions {
352
if c.processInteractionForRequest(interaction, data) {
353
c.interactions.Remove(id)
354
break
355
}
356
}
357
} else {
358
_ = c.requests.SetWithExpire(id, data, c.eviction)
359
}
360
}
361
}
362
363
// HasMatchers returns true if an operator has interactsh part
364
// matchers or extractors.
365
//
366
// Used by requests to show result or not depending on presence of interact.sh
367
// data part matchers.
368
func HasMatchers(op *operators.Operators) bool {
369
if op == nil {
370
return false
371
}
372
373
for _, matcher := range op.Matchers {
374
for _, dsl := range matcher.DSL {
375
if stringsutil.ContainsAnyI(dsl, "interactsh") {
376
return true
377
}
378
}
379
if stringsutil.HasPrefixI(matcher.Part, "interactsh") {
380
return true
381
}
382
}
383
for _, matcher := range op.Extractors {
384
if stringsutil.HasPrefixI(matcher.Part, "interactsh") {
385
return true
386
}
387
}
388
return false
389
}
390
391
// HasMarkers checks if the text contains interactsh markers
392
func HasMarkers(data string) bool {
393
return interactshURLMarkerRegex.Match([]byte(data))
394
}
395
396
func (c *Client) debugPrintInteraction(interaction *server.Interaction, event *operators.Result) {
397
builder := &bytes.Buffer{}
398
399
switch interaction.Protocol {
400
case "dns":
401
builder.WriteString(formatInteractionHeader("DNS", interaction.FullId, interaction.RemoteAddress, interaction.Timestamp))
402
if c.options.DebugRequest || c.options.Debug {
403
builder.WriteString(formatInteractionMessage("DNS Request", interaction.RawRequest, event, c.options.NoColor))
404
}
405
if c.options.DebugResponse || c.options.Debug {
406
builder.WriteString(formatInteractionMessage("DNS Response", interaction.RawResponse, event, c.options.NoColor))
407
}
408
case "http":
409
builder.WriteString(formatInteractionHeader("HTTP", interaction.FullId, interaction.RemoteAddress, interaction.Timestamp))
410
if c.options.DebugRequest || c.options.Debug {
411
builder.WriteString(formatInteractionMessage("HTTP Request", interaction.RawRequest, event, c.options.NoColor))
412
}
413
if c.options.DebugResponse || c.options.Debug {
414
builder.WriteString(formatInteractionMessage("HTTP Response", interaction.RawResponse, event, c.options.NoColor))
415
}
416
case "smtp":
417
builder.WriteString(formatInteractionHeader("SMTP", interaction.FullId, interaction.RemoteAddress, interaction.Timestamp))
418
if c.options.DebugRequest || c.options.Debug || c.options.DebugResponse {
419
builder.WriteString(formatInteractionMessage("SMTP Interaction", interaction.RawRequest, event, c.options.NoColor))
420
}
421
case "ldap":
422
builder.WriteString(formatInteractionHeader("LDAP", interaction.FullId, interaction.RemoteAddress, interaction.Timestamp))
423
if c.options.DebugRequest || c.options.Debug || c.options.DebugResponse {
424
builder.WriteString(formatInteractionMessage("LDAP Interaction", interaction.RawRequest, event, c.options.NoColor))
425
}
426
}
427
_, _ = fmt.Fprint(os.Stderr, builder.String())
428
}
429
430
func formatInteractionHeader(protocol, ID, address string, at time.Time) string {
431
return fmt.Sprintf("[%s] Received %s interaction from %s at %s", ID, protocol, address, at.Format("2006-01-02 15:04:05"))
432
}
433
434
func formatInteractionMessage(key, value string, event *operators.Result, noColor bool) string {
435
value = responsehighlighter.Highlight(event, value, noColor, false)
436
return fmt.Sprintf("\n------------\n%s\n------------\n\n%s\n\n", key, value)
437
}
438
439
func hash(internalEvent output.InternalEvent) string {
440
templateId := internalEvent[templateIdAttribute].(string)
441
host := internalEvent["host"].(string)
442
return fmt.Sprintf("%s:%s", templateId, host)
443
}
444
445
func (c *Client) getHostname() string {
446
c.RLock()
447
defer c.RUnlock()
448
449
return c.hostname
450
}
451
452
func (c *Client) setHostname(hostname string) {
453
c.Lock()
454
defer c.Unlock()
455
456
c.hostname = hostname
457
}
458
459