package javascript
import (
"bytes"
"context"
"fmt"
"maps"
"net"
"strings"
"sync/atomic"
"time"
"github.com/Mzack9999/goja"
"github.com/alecthomas/chroma/quick"
"github.com/ditashi/jsbeautifier-go/jsbeautifier"
"github.com/pkg/errors"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/nuclei/v3/pkg/js/compiler"
"github.com/projectdiscovery/nuclei/v3/pkg/js/gojs"
"github.com/projectdiscovery/nuclei/v3/pkg/model"
"github.com/projectdiscovery/nuclei/v3/pkg/operators"
"github.com/projectdiscovery/nuclei/v3/pkg/operators/extractors"
"github.com/projectdiscovery/nuclei/v3/pkg/operators/matchers"
"github.com/projectdiscovery/nuclei/v3/pkg/output"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/eventcreator"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/interactsh"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"
protocolutils "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"
"github.com/projectdiscovery/nuclei/v3/pkg/types"
"github.com/projectdiscovery/utils/errkit"
iputil "github.com/projectdiscovery/utils/ip"
mapsutil "github.com/projectdiscovery/utils/maps"
syncutil "github.com/projectdiscovery/utils/sync"
urlutil "github.com/projectdiscovery/utils/url"
)
type Request struct {
operators.Operators `yaml:",inline,omitempty" json:",inline,omitempty"`
CompiledOperators *operators.Operators `yaml:"-" json:"-"`
ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id of the request,description=ID is the optional ID of the Request"`
Init string `yaml:"init,omitempty" json:"init,omitempty" jsonschema:"title=init javascript code,description=Init is the javascript code to execute after compiling template"`
PreCondition string `yaml:"pre-condition,omitempty" json:"pre-condition,omitempty" jsonschema:"title=pre-condition for the request,description=PreCondition is a condition which is evaluated before sending the request"`
Args map[string]interface{} `yaml:"args,omitempty" json:"args,omitempty"`
Code string `yaml:"code,omitempty" json:"code,omitempty" jsonschema:"title=code to execute in javascript,description=Executes inline javascript code for the request"`
StopAtFirstMatch bool `yaml:"stop-at-first-match,omitempty" json:"stop-at-first-match,omitempty" jsonschema:"title=stop at first match,description=Stop the execution after a match is found"`
AttackType generators.AttackTypeHolder `yaml:"attack,omitempty" json:"attack,omitempty" jsonschema:"title=attack is the payload combination,description=Attack is the type of payload combinations to perform,enum=sniper,enum=pitchfork,enum=clusterbomb"`
Threads int `yaml:"threads,omitempty" json:"threads,omitempty" jsonschema:"title=threads for sending requests,description=Threads specifies number of threads to use sending requests. This enables Connection Pooling"`
Payloads map[string]interface{} `yaml:"payloads,omitempty" json:"payloads,omitempty" jsonschema:"title=payloads for the webosocket request,description=Payloads contains any payloads for the current request"`
generator *generators.PayloadGenerator
options *protocols.ExecutorOptions `yaml:"-" json:"-"`
preConditionCompiled *goja.Program `yaml:"-" json:"-"`
scriptCompiled *goja.Program `yaml:"-" json:"-"`
}
func (request *Request) Compile(options *protocols.ExecutorOptions) error {
request.options = options
var err error
if len(request.Payloads) > 0 {
request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, options.Catalog, options.Options.AttackType, options.Options)
if err != nil {
return errors.Wrap(err, "could not parse payloads")
}
request.Threads = options.GetThreadsForNPayloadRequests(request.Requests(), request.Threads)
}
if len(request.Matchers) > 0 || len(request.Extractors) > 0 {
compiled := &request.Operators
compiled.ExcludeMatchers = options.ExcludeMatchers
compiled.TemplateID = options.TemplateID
for _, matcher := range compiled.Matchers {
if matcher.Part == "" && matcher.Type.MatcherType != matchers.DSLMatcher {
matcher.Part = "response"
}
}
for _, extractor := range compiled.Extractors {
if extractor.Part == "" {
extractor.Part = "response"
}
}
if err := compiled.Compile(); err != nil {
return errkit.Newf("could not compile operators got %v", err)
}
request.CompiledOperators = compiled
}
if strings.Contains(request.getPort(), "{{") {
return errkit.New("'Port' variable cannot contain any dsl expressions")
}
if request.Init != "" {
if request.options.Options.Debug || request.options.Options.DebugRequests {
gologger.Debug().Msgf("[%s] Executing Template Init\n", request.TemplateID)
var highlightFormatter = "terminal256"
if request.options.Options.NoColor {
highlightFormatter = "text"
}
var buff bytes.Buffer
_ = quick.Highlight(&buff, beautifyJavascript(request.Init), "javascript", highlightFormatter, "monokai")
prettyPrint(request.TemplateID, buff.String())
}
opts := &compiler.ExecuteOptions{
ExecutionId: request.options.Options.ExecutionId,
TimeoutVariants: request.options.Options.GetTimeouts(),
Source: &request.Init,
Context: context.Background(),
}
opts.Callback = func(runtime *goja.Runtime) error {
err := gojs.RegisterFuncWithSignature(runtime, gojs.FuncOpts{
Name: "set",
Signatures: []string{
"set(string, interface{})",
},
Description: "set variable from init code. this function is available in init code block only",
FuncDecl: func(varname string, value any) error {
if varname == "" {
return fmt.Errorf("variable name cannot be empty")
}
if value == nil {
return fmt.Errorf("variable value cannot be empty")
}
if request.Args == nil {
request.Args = make(map[string]interface{})
}
request.Args[varname] = value
return nil
},
})
if err != nil {
return err
}
return gojs.RegisterFuncWithSignature(runtime, gojs.FuncOpts{
Name: "updatePayload",
Signatures: []string{
"updatePayload(string, interface{})",
},
Description: "update/override any payload from init code. this function is available in init code block only",
FuncDecl: func(varname string, Value any) error {
if request.Payloads == nil {
request.Payloads = make(map[string]interface{})
}
if request.generator != nil {
request.Payloads[varname] = Value
request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, options.Catalog, options.Options.AttackType, options.Options)
if err != nil {
return err
}
} else {
return fmt.Errorf("payloads not defined and cannot be updated")
}
return nil
},
})
}
opts.Cleanup = func(runtime *goja.Runtime) {
_ = runtime.GlobalObject().Delete("set")
_ = runtime.GlobalObject().Delete("updatePayload")
}
args := compiler.NewExecuteArgs()
allVars := generators.MergeMaps(options.Variables.GetAll(), options.Options.Vars.AsMap(), request.options.Constants)
args.Args, _ = request.evaluateArgs(allVars, options, true)
initCompiled, err := compiler.SourceAutoMode(request.Init, false)
if err != nil {
return errkit.Newf("could not compile init code: %s", err)
}
result, err := request.options.JsCompiler.ExecuteWithOptions(initCompiled, args, opts)
if err != nil {
return errkit.Newf("could not execute pre-condition: %s", err)
}
if types.ToString(result["error"]) != "" {
gologger.Warning().Msgf("[%s] Init failed with error %v\n", request.TemplateID, result["error"])
return nil
} else {
if request.options.Options.Debug || request.options.Options.DebugResponse {
gologger.Debug().Msgf("[%s] Init executed successfully\n", request.TemplateID)
gologger.Debug().Msgf("[%s] Init result: %v\n", request.TemplateID, result["response"])
}
}
}
if request.PreCondition != "" {
preConditionCompiled, err := compiler.SourceAutoMode(request.PreCondition, false)
if err != nil {
return errkit.Newf("could not compile pre-condition: %s", err)
}
request.preConditionCompiled = preConditionCompiled
}
if request.Code != "" {
scriptCompiled, err := compiler.SourceAutoMode(request.Code, false)
if err != nil {
return errkit.Newf("could not compile javascript code: %s", err)
}
request.scriptCompiled = scriptCompiled
}
return nil
}
func (r *Request) Options() *protocols.ExecutorOptions {
return r.options
}
func (request *Request) Requests() int {
pre_conditions := 0
if request.PreCondition != "" {
pre_conditions = 1
}
if request.generator != nil {
payloadRequests := request.generator.NewIterator().Total()
return payloadRequests + pre_conditions
}
return 1 + pre_conditions
}
func (request *Request) GetID() string {
return request.ID
}
func (request *Request) ExecuteWithResults(target *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {
input := target.Clone()
if err := input.UseNetworkPort(request.getPort(), request.getExcludePorts()); err != nil {
gologger.Debug().Msgf("Could not network port from constants: %s\n", err)
}
hostPort, err := getAddress(input.MetaInput.Input)
if err != nil {
request.options.Progress.IncrementFailedRequestsBy(1)
return err
}
hostname, port, _ := net.SplitHostPort(hostPort)
if hostname == "" {
hostname = hostPort
}
requestOptions := request.options
templateCtx := request.options.GetTemplateCtx(input.MetaInput)
payloadValues := generators.BuildPayloadFromOptions(request.options.Options)
maps.Copy(payloadValues, dynamicValues)
payloadValues["Hostname"] = hostPort
payloadValues["Host"] = hostname
payloadValues["Port"] = port
hostnameVariables := protocolutils.GenerateDNSVariables(hostname)
values := generators.MergeMaps(payloadValues, hostnameVariables, request.options.Constants, templateCtx.GetAll())
variablesMap := request.options.Variables.Evaluate(values)
payloadValues = generators.MergeMaps(variablesMap, payloadValues, request.options.Constants, hostnameVariables)
var interactshURLs []string
if request.options.Interactsh != nil {
for payloadName, payloadValue := range payloadValues {
var urls []string
payloadValue, urls = request.options.Interactsh.Replace(types.ToString(payloadValue), interactshURLs)
if len(urls) > 0 {
interactshURLs = append(interactshURLs, urls...)
payloadValues[payloadName] = payloadValue
}
}
}
templateCtx.Merge(payloadValues)
if vardump.EnableVarDump {
gologger.Debug().Msgf("JavaScript Protocol request variables: %s\n", vardump.DumpVariables(payloadValues))
}
if request.PreCondition != "" {
payloads := generators.MergeMaps(payloadValues, previous)
if request.options.Options.Debug || request.options.Options.DebugRequests {
gologger.Debug().Msgf("[%s] Executing Precondition for request\n", request.TemplateID)
var highlightFormatter = "terminal256"
if requestOptions.Options.NoColor {
highlightFormatter = "text"
}
var buff bytes.Buffer
_ = quick.Highlight(&buff, beautifyJavascript(request.PreCondition), "javascript", highlightFormatter, "monokai")
prettyPrint(request.TemplateID, buff.String())
}
argsCopy, err := request.getArgsCopy(input, payloads, requestOptions, true)
if err != nil {
return err
}
argsCopy.TemplateCtx = templateCtx.GetAll()
result, err := request.options.JsCompiler.ExecuteWithOptions(request.preConditionCompiled, argsCopy,
&compiler.ExecuteOptions{
ExecutionId: requestOptions.Options.ExecutionId,
TimeoutVariants: requestOptions.Options.GetTimeouts(),
Source: &request.PreCondition, Context: target.Context(),
})
if err == nil && result.GetSuccess() {
if request.options.Options.Debug || request.options.Options.DebugRequests {
request.options.Progress.IncrementRequests()
gologger.Debug().Msgf("[%s] Precondition for request was satisfied\n", request.TemplateID)
}
} else {
var outError error
if err != nil {
outError = errkit.Append(errkit.New("pre-condition not satisfied skipping template execution"), err)
} else {
outError = errkit.New("pre-condition not satisfied skipping template execution")
}
results := map[string]interface{}(result)
results["error"] = outError.Error()
data := request.generateEventData(input, results, hostPort)
data = generators.MergeMaps(data, payloadValues)
event := eventcreator.CreateEventWithAdditionalOptions(request, data, request.options.Options.Debug || request.options.Options.DebugResponse, func(wrappedEvent *output.InternalWrappedEvent) {
allVars := argsCopy.Map()
allVars = generators.MergeMaps(allVars, data)
wrappedEvent.OperatorsResult.PayloadValues = allVars
})
callback(event)
return err
}
}
if request.generator != nil && request.Threads > 1 {
request.executeRequestParallel(target.Context(), hostPort, hostname, input, payloadValues, callback)
return nil
}
var gotMatches bool
if request.generator != nil {
iterator := request.generator.NewIterator()
for {
value, ok := iterator.Value()
if !ok {
return nil
}
select {
case <-input.Context().Done():
return input.Context().Err()
default:
}
if err := request.executeRequestWithPayloads(hostPort, input, hostname, value, payloadValues, func(result *output.InternalWrappedEvent) {
if result.OperatorsResult != nil && result.OperatorsResult.Matched {
gotMatches = true
request.options.Progress.IncrementMatched()
}
callback(result)
}, requestOptions, interactshURLs); err != nil {
if errkit.IsNetworkPermanentErr(err) {
return err
}
}
shouldStopAtFirstMatch := request.options.Options.StopAtFirstMatch || request.StopAtFirstMatch
if shouldStopAtFirstMatch && gotMatches {
return nil
}
}
}
return request.executeRequestWithPayloads(hostPort, input, hostname, nil, payloadValues, callback, requestOptions, interactshURLs)
}
func (request *Request) executeRequestParallel(ctxParent context.Context, hostPort, hostname string, input *contextargs.Context, payloadValues map[string]interface{}, callback protocols.OutputEventCallback) {
threads := request.Threads
if threads == 0 {
threads = 1
}
ctx, cancel := context.WithCancelCause(ctxParent)
defer cancel(nil)
requestOptions := request.options
gotmatches := &atomic.Bool{}
shouldFollowGlobal := threads == request.options.Options.PayloadConcurrency
sg, _ := syncutil.New(syncutil.WithSize(threads))
if request.generator != nil {
iterator := request.generator.NewIterator()
for {
value, ok := iterator.Value()
if !ok {
break
}
select {
case <-input.Context().Done():
return
default:
}
if shouldFollowGlobal && sg.Size != request.options.Options.PayloadConcurrency {
if err := sg.Resize(ctxParent, request.options.Options.PayloadConcurrency); err != nil {
gologger.Warning().Msgf("Could not resize workpool: %s\n", err)
}
}
sg.Add()
go func() {
defer sg.Done()
if ctx.Err() != nil {
return
}
shouldStopAtFirstMatch := request.options.Options.StopAtFirstMatch || request.StopAtFirstMatch
if err := request.executeRequestWithPayloads(hostPort, input, hostname, value, payloadValues, func(result *output.InternalWrappedEvent) {
if result.OperatorsResult != nil && result.OperatorsResult.Matched {
gotmatches.Store(true)
}
callback(result)
}, requestOptions, []string{}); err != nil {
if errkit.IsNetworkPermanentErr(err) {
cancel(err)
return
}
}
if shouldStopAtFirstMatch && gotmatches.Load() {
cancel(nil)
return
}
}()
}
}
sg.Wait()
if gotmatches.Load() {
request.options.Progress.IncrementMatched()
}
}
func (request *Request) executeRequestWithPayloads(hostPort string, input *contextargs.Context, _ string, payload map[string]interface{}, previous output.InternalEvent, callback protocols.OutputEventCallback, requestOptions *protocols.ExecutorOptions, interactshURLs []string) error {
payloadValues := generators.MergeMaps(payload, previous)
argsCopy, err := request.getArgsCopy(input, payloadValues, requestOptions, false)
if err != nil {
return err
}
if request.options.HasTemplateCtx(input.MetaInput) {
argsCopy.TemplateCtx = request.options.GetTemplateCtx(input.MetaInput).GetAll()
} else {
argsCopy.TemplateCtx = map[string]interface{}{}
}
if request.options.Interactsh != nil {
if argsCopy.Args != nil {
for k, v := range argsCopy.Args {
var urls []string
v, urls = request.options.Interactsh.Replace(fmt.Sprint(v), []string{})
if len(urls) > 0 {
interactshURLs = append(interactshURLs, urls...)
argsCopy.Args[k] = v
}
}
}
}
results, err := request.options.JsCompiler.ExecuteWithOptions(request.scriptCompiled, argsCopy,
&compiler.ExecuteOptions{
ExecutionId: requestOptions.Options.ExecutionId,
TimeoutVariants: requestOptions.Options.GetTimeouts(),
Source: &request.Code,
Context: input.Context(),
})
if err != nil {
results = compiler.ExecuteResult{"success": false, "error": err.Error()}
}
request.options.Progress.IncrementRequests()
requestOptions.Output.Request(requestOptions.TemplateID, hostPort, request.Type().String(), err)
gologger.Verbose().Msgf("[%s] Sent Javascript request to %s", request.options.TemplateID, hostPort)
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests || requestOptions.Options.StoreResponse {
msg := fmt.Sprintf("[%s] Dumped Javascript request for %s:\nVariables:\n %v", requestOptions.TemplateID, input.MetaInput.Input, vardump.DumpVariables(argsCopy.Args))
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests {
gologger.Debug().Str("address", input.MetaInput.Input).Msg(msg)
var highlightFormatter = "terminal256"
if requestOptions.Options.NoColor {
highlightFormatter = "text"
}
var buff bytes.Buffer
_ = quick.Highlight(&buff, beautifyJavascript(request.Code), "javascript", highlightFormatter, "monokai")
prettyPrint(request.TemplateID, buff.String())
}
if requestOptions.Options.StoreResponse {
request.options.Output.WriteStoreDebugData(input.MetaInput.Input, request.options.TemplateID, request.Type().String(), msg)
}
}
values := mapsutil.Merge(payloadValues, results)
data := request.generateEventData(input, values, hostPort)
request.options.AddTemplateVars(input.MetaInput, request.Type(), request.GetID(), data)
data = generators.MergeMaps(data, request.options.GetTemplateCtx(input.MetaInput).GetAll())
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests || requestOptions.Options.StoreResponse {
msg := fmt.Sprintf("[%s] Dumped Javascript response for %s:\n%v", requestOptions.TemplateID, input.MetaInput.Input, vardump.DumpVariables(results))
if requestOptions.Options.Debug || requestOptions.Options.DebugRequests {
gologger.Debug().Str("address", input.MetaInput.Input).Msg(msg)
}
if requestOptions.Options.StoreResponse {
request.options.Output.WriteStoreDebugData(input.MetaInput.Input, request.options.TemplateID, request.Type().String(), msg)
}
}
if _, ok := data["error"]; ok {
event := eventcreator.CreateEventWithAdditionalOptions(request, generators.MergeMaps(data, payloadValues), request.options.Options.Debug || request.options.Options.DebugResponse, func(wrappedEvent *output.InternalWrappedEvent) {
wrappedEvent.OperatorsResult.PayloadValues = payload
})
callback(event)
return err
}
if request.options.Interactsh != nil {
request.options.Interactsh.MakePlaceholders(interactshURLs, data)
}
var event *output.InternalWrappedEvent
if len(interactshURLs) == 0 {
event = eventcreator.CreateEventWithAdditionalOptions(request, generators.MergeMaps(data, payloadValues), request.options.Options.Debug || request.options.Options.DebugResponse, func(wrappedEvent *output.InternalWrappedEvent) {
wrappedEvent.OperatorsResult.PayloadValues = payload
})
callback(event)
} else if request.options.Interactsh != nil {
event = &output.InternalWrappedEvent{InternalEvent: data, UsesInteractsh: true}
request.options.Interactsh.RequestEvent(interactshURLs, &interactsh.RequestData{
MakeResultFunc: request.MakeResultEvent,
Event: event,
Operators: request.CompiledOperators,
MatchFunc: request.Match,
ExtractFunc: request.Extract,
})
}
return nil
}
func (request *Request) generateEventData(input *contextargs.Context, values map[string]interface{}, matched string) map[string]interface{} {
dialers := protocolstate.GetDialersWithId(request.options.Options.ExecutionId)
if dialers == nil {
panic(fmt.Sprintf("dialers not initialized for %s", request.options.Options.ExecutionId))
}
data := make(map[string]interface{})
maps.Copy(data, values)
data["type"] = request.Type().String()
data["request-pre-condition"] = beautifyJavascript(request.PreCondition)
data["request"] = beautifyJavascript(request.Code)
data["host"] = input.MetaInput.Input
data["matched"] = matched
data["template-path"] = request.options.TemplatePath
data["template-id"] = request.options.TemplateID
data["template-info"] = request.options.TemplateInfo
if request.StopAtFirstMatch || request.options.StopAtFirstMatch {
data["stop-at-first-match"] = true
}
if input.MetaInput.CustomIP != "" {
data["ip"] = input.MetaInput.CustomIP
} else {
hostname := input.MetaInput.Input
if strings.Contains(hostname, ":") {
host, _, err := net.SplitHostPort(hostname)
if err == nil {
hostname = host
} else {
if !strings.Contains(hostname, "]") {
hostname = hostname[:strings.LastIndex(hostname, ":")]
}
}
}
data["ip"] = dialers.Fastdialer.GetDialedIP(hostname)
if iputil.IsIP(hostname) {
data["ip"] = hostname
}
dnsData, err := dialers.Fastdialer.GetDNSData(hostname)
if err == nil {
for _, v := range dnsData.A {
data["ip"] = v
break
}
if data["ip"] == "" {
for _, v := range dnsData.AAAA {
data["ip"] = v
break
}
}
}
}
return data
}
func (request *Request) getArgsCopy(input *contextargs.Context, payloadValues map[string]interface{}, requestOptions *protocols.ExecutorOptions, ignoreErrors bool) (*compiler.ExecuteArgs, error) {
argsCopy, err := request.evaluateArgs(payloadValues, requestOptions, ignoreErrors)
if err != nil {
requestOptions.Output.Request(requestOptions.TemplateID, input.MetaInput.Input, request.Type().String(), err)
requestOptions.Progress.IncrementFailedRequestsBy(1)
}
argsCopy["Port"] = input.Port()
return &compiler.ExecuteArgs{Args: argsCopy}, nil
}
func (request *Request) evaluateArgs(payloadValues map[string]interface{}, _ *protocols.ExecutorOptions, ignoreErrors bool) (map[string]interface{}, error) {
argsCopy := make(map[string]interface{})
mainLoop:
for k, v := range request.Args {
if vVal, ok := v.(string); ok && strings.Contains(vVal, "{") {
finalAddress, dataErr := expressions.Evaluate(vVal, payloadValues)
if dataErr != nil {
return nil, errors.Wrap(dataErr, "could not evaluate template expressions")
}
if finalAddress == vVal && ignoreErrors {
argsCopy[k] = ""
continue mainLoop
}
argsCopy[k] = finalAddress
} else {
argsCopy[k] = v
}
}
return argsCopy, nil
}
var RequestPartDefinitions = map[string]string{
"type": "Type is the type of request made",
"response": "Javascript protocol result response",
"host": "Host is the input to the template",
"matched": "Matched is the input which was matched upon",
}
func getAddress(toTest string) (string, error) {
urlx, err := urlutil.Parse(toTest)
if err != nil {
return toTest, nil
}
return urlx.Host, nil
}
func (request *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) {
return protocols.MakeDefaultMatchFunc(data, matcher)
}
func (request *Request) Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{} {
return protocols.MakeDefaultExtractFunc(data, matcher)
}
func (request *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent {
return protocols.MakeDefaultResultEvent(request, wrapped)
}
func (request *Request) GetCompiledOperators() []*operators.Operators {
return []*operators.Operators{request.CompiledOperators}
}
func (request *Request) Type() templateTypes.ProtocolType {
return templateTypes.JavascriptProtocol
}
func (request *Request) getPort() string {
for k, v := range request.Args {
if strings.EqualFold(k, "Port") {
return types.ToString(v)
}
}
return ""
}
func (request *Request) getExcludePorts() string {
for k, v := range request.Args {
if strings.EqualFold(k, "exclude-ports") {
return types.ToString(v)
}
}
return ""
}
func (request *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent {
fields := protocolutils.GetJsonFieldsFromURL(types.ToString(wrapped.InternalEvent["host"]))
if types.ToString(wrapped.InternalEvent["ip"]) != "" {
fields.Ip = types.ToString(wrapped.InternalEvent["ip"])
}
data := &output.ResultEvent{
TemplateID: types.ToString(wrapped.InternalEvent["template-id"]),
TemplatePath: types.ToString(wrapped.InternalEvent["template-path"]),
Info: wrapped.InternalEvent["template-info"].(model.Info),
TemplateVerifier: request.options.TemplateVerifier,
Type: types.ToString(wrapped.InternalEvent["type"]),
Host: fields.Host,
Port: fields.Port,
URL: fields.URL,
Matched: types.ToString(wrapped.InternalEvent["matched"]),
Metadata: wrapped.OperatorsResult.PayloadValues,
ExtractedResults: wrapped.OperatorsResult.OutputExtracts,
Timestamp: time.Now(),
MatcherStatus: true,
Request: types.ToString(wrapped.InternalEvent["request"]),
Response: types.ToString(wrapped.InternalEvent["response"]),
IP: fields.Ip,
TemplateEncoded: request.options.EncodeTemplate(),
Error: types.ToString(wrapped.InternalEvent["error"]),
}
return data
}
func beautifyJavascript(code string) string {
opts := jsbeautifier.DefaultOptions()
beautified, err := jsbeautifier.Beautify(&code, opts)
if err != nil {
return code
}
return beautified
}
func prettyPrint(templateId string, buff string) {
lines := strings.Split(buff, "\n")
final := []string{}
for _, v := range lines {
if v != "" {
final = append(final, "\t"+v)
}
}
gologger.Debug().Msgf(" [%v] Javascript Code:\n\n%v\n\n", templateId, strings.Join(final, "\n"))
}
func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {
r.options.ApplyNewEngineOptions(opts)
}