Path: blob/dev/pkg/protocols/websocket/websocket.go
2070 views
package websocket12import (3"crypto/tls"4"fmt"5"io"6"maps"7"net"8"net/http"9"net/url"10"path"11"strings"12"time"1314"github.com/gobwas/ws"15"github.com/gobwas/ws/wsutil"16"github.com/pkg/errors"1718"github.com/projectdiscovery/fastdialer/fastdialer"19"github.com/projectdiscovery/gologger"20"github.com/projectdiscovery/nuclei/v3/pkg/operators"21"github.com/projectdiscovery/nuclei/v3/pkg/operators/extractors"22"github.com/projectdiscovery/nuclei/v3/pkg/operators/matchers"23"github.com/projectdiscovery/nuclei/v3/pkg/output"24"github.com/projectdiscovery/nuclei/v3/pkg/protocols"25"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"26"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/expressions"27"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/generators"28"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/eventcreator"29"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/helpers/responsehighlighter"30"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/utils/vardump"31"github.com/projectdiscovery/nuclei/v3/pkg/protocols/network/networkclientpool"32protocolutils "github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"33templateTypes "github.com/projectdiscovery/nuclei/v3/pkg/templates/types"34"github.com/projectdiscovery/nuclei/v3/pkg/types"35urlutil "github.com/projectdiscovery/utils/url"36)3738// Request is a request for the Websocket protocol39type Request struct {40// Operators for the current request go here.41operators.Operators `yaml:",inline,omitempty" json:",inline,omitempty"`42CompiledOperators *operators.Operators `yaml:"-" json:"-"`4344// ID is the optional id of the request45ID string `yaml:"id,omitempty" json:"id,omitempty" jsonschema:"title=id of the request,description=ID of the network request"`46// description: |47// Address contains address for the request48Address string `yaml:"address,omitempty" json:"address,omitempty" jsonschema:"title=address for the websocket request,description=Address contains address for the request"`49// description: |50// Inputs contains inputs for the websocket protocol51Inputs []*Input `yaml:"inputs,omitempty" json:"inputs,omitempty" jsonschema:"title=inputs for the websocket request,description=Inputs contains any input/output for the current request"`52// description: |53// Headers contains headers for the request.54Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty" jsonschema:"title=headers contains the request headers,description=Headers contains headers for the request"`5556// description: |57// Attack is the type of payload combinations to perform.58//59// Sniper is each payload once, pitchfork combines multiple payload sets and clusterbomb generates60// permutations and combinations for all payloads.61AttackType 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"`62// description: |63// Payloads contains any payloads for the current request.64//65// Payloads support both key-values combinations where a list66// of payloads is provided, or optionally a single file can also67// be provided as payload which will be read on run-time.68Payloads map[string]interface{} `yaml:"payloads,omitempty" json:"payloads,omitempty" jsonschema:"title=payloads for the websocket request,description=Payloads contains any payloads for the current request"`6970generator *generators.PayloadGenerator7172// cache any variables that may be needed for operation.73dialer *fastdialer.Dialer74options *protocols.ExecutorOptions75}7677// Input is an input for the websocket protocol78type Input struct {79// description: |80// Data is the data to send as the input.81//82// It supports DSL Helper Functions as well as normal expressions.83// examples:84// - value: "\"TEST\""85// - value: "\"hex_decode('50494e47')\""86Data string `yaml:"data,omitempty" json:"data,omitempty" jsonschema:"title=data to send as input,description=Data is the data to send as the input"`87// description: |88// Name is the optional name of the data read to provide matching on.89// examples:90// - value: "\"prefix\""91Name string `yaml:"name,omitempty" json:"name,omitempty" jsonschema:"title=optional name for data read,description=Optional name of the data read to provide matching on"`92}9394const (95parseUrlErrorMessage = "could not parse input url"96evaluateTemplateExpressionErrorMessage = "could not evaluate template expressions"97)9899// Compile compiles the request generators preparing any requests possible.100func (request *Request) Compile(options *protocols.ExecutorOptions) error {101request.options = options102103client, err := networkclientpool.Get(options.Options, &networkclientpool.Configuration{104CustomDialer: options.CustomFastdialer,105})106if err != nil {107return errors.Wrap(err, "could not get network client")108}109request.dialer = client110111if len(request.Payloads) > 0 {112request.generator, err = generators.New(request.Payloads, request.AttackType.Value, request.options.TemplatePath, options.Catalog, options.Options.AttackType, types.DefaultOptions())113if err != nil {114return errors.Wrap(err, "could not parse payloads")115}116}117118if len(request.Matchers) > 0 || len(request.Extractors) > 0 {119compiled := &request.Operators120compiled.ExcludeMatchers = options.ExcludeMatchers121compiled.TemplateID = options.TemplateID122if err := compiled.Compile(); err != nil {123return errors.Wrap(err, "could not compile operators")124}125request.CompiledOperators = compiled126}127return nil128}129130// Requests returns the total number of requests the rule will perform131func (request *Request) Requests() int {132if request.generator != nil {133return request.generator.NewIterator().Total()134}135return 1136}137138// GetID returns the ID for the request if any.139func (request *Request) GetID() string {140return ""141}142143// ExecuteWithResults executes the protocol requests and returns results instead of writing them.144func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {145hostname, err := getAddress(input.MetaInput.Input)146if err != nil {147return err148}149150if request.generator != nil {151iterator := request.generator.NewIterator()152153for {154value, ok := iterator.Value()155if !ok {156break157}158if err := request.executeRequestWithPayloads(input, hostname, value, previous, callback); err != nil {159return err160}161}162} else {163value := make(map[string]interface{})164if err := request.executeRequestWithPayloads(input, hostname, value, previous, callback); err != nil {165return err166}167}168return nil169}170171// ExecuteWithResults executes the protocol requests and returns results instead of writing them.172func (request *Request) executeRequestWithPayloads(target *contextargs.Context, hostname string, dynamicValues, previous output.InternalEvent, callback protocols.OutputEventCallback) error {173header := http.Header{}174input := target.MetaInput.Input175176parsed, err := urlutil.Parse(input)177if err != nil {178return errors.Wrap(err, parseUrlErrorMessage)179}180defaultVars := protocolutils.GenerateVariables(parsed, false, nil)181optionVars := generators.BuildPayloadFromOptions(request.options.Options)182// add templatecontext variables to varMap183variables := request.options.Variables.Evaluate(generators.MergeMaps(defaultVars, optionVars, dynamicValues, request.options.GetTemplateCtx(target.MetaInput).GetAll()))184payloadValues := generators.MergeMaps(variables, defaultVars, optionVars, dynamicValues, request.options.Constants)185186requestOptions := request.options187for key, value := range request.Headers {188finalData, dataErr := expressions.EvaluateByte([]byte(value), payloadValues)189if dataErr != nil {190requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), dataErr)191requestOptions.Progress.IncrementFailedRequestsBy(1)192return errors.Wrap(dataErr, evaluateTemplateExpressionErrorMessage)193}194header.Set(key, string(finalData))195}196tlsConfig := &tls.Config{197InsecureSkipVerify: true,198ServerName: hostname,199MinVersion: tls.VersionTLS10,200}201if requestOptions.Options.SNI != "" {202tlsConfig.ServerName = requestOptions.Options.SNI203}204websocketDialer := ws.Dialer{205Header: ws.HandshakeHeaderHTTP(header),206Timeout: time.Duration(requestOptions.Options.Timeout) * time.Second,207NetDial: request.dialer.Dial,208TLSConfig: tlsConfig,209}210211if vardump.EnableVarDump {212gologger.Debug().Msgf("WebSocket Protocol request variables: %s\n", vardump.DumpVariables(payloadValues))213}214215finalAddress, dataErr := expressions.EvaluateByte([]byte(request.Address), payloadValues)216if dataErr != nil {217requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), dataErr)218requestOptions.Progress.IncrementFailedRequestsBy(1)219return errors.Wrap(dataErr, evaluateTemplateExpressionErrorMessage)220}221222addressToDial := string(finalAddress)223parsedAddress, err := url.Parse(addressToDial)224if err != nil {225requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)226requestOptions.Progress.IncrementFailedRequestsBy(1)227return errors.Wrap(err, parseUrlErrorMessage)228}229parsedAddress.Path = path.Join(parsedAddress.Path, parsed.Path)230addressToDial = parsedAddress.String()231232conn, readBuffer, _, err := websocketDialer.Dial(target.Context(), addressToDial)233if err != nil {234requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)235requestOptions.Progress.IncrementFailedRequestsBy(1)236return errors.Wrap(err, "could not connect to server")237}238defer func() {239_ = conn.Close()240}()241242responseBuilder := &strings.Builder{}243if readBuffer != nil {244_, _ = io.Copy(responseBuilder, readBuffer) // Copy initial response245}246247events, requestOutput, err := request.readWriteInputWebsocket(conn, payloadValues, input, responseBuilder)248if err != nil {249requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)250requestOptions.Progress.IncrementFailedRequestsBy(1)251return errors.Wrap(err, "could not read write response")252}253requestOptions.Progress.IncrementRequests()254255if requestOptions.Options.Debug || requestOptions.Options.DebugRequests {256gologger.Debug().Str("address", input).Msgf("[%s] Dumped Websocket request for %s", requestOptions.TemplateID, input)257gologger.Print().Msgf("%s", requestOutput)258}259260requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)261gologger.Verbose().Msgf("Sent Websocket request to %s", input)262263data := make(map[string]interface{})264265data["type"] = request.Type().String()266data["success"] = "true"267data["request"] = requestOutput268data["response"] = responseBuilder.String()269data["host"] = input270data["matched"] = addressToDial271data["ip"] = request.dialer.GetDialedIP(hostname)272273// add response fields to template context and merge templatectx variables to output event274request.options.AddTemplateVars(target.MetaInput, request.Type(), request.ID, data)275data = generators.MergeMaps(data, request.options.GetTemplateCtx(target.MetaInput).GetAll())276277maps.Copy(data, previous)278maps.Copy(data, events)279280event := eventcreator.CreateEventWithAdditionalOptions(request, data, requestOptions.Options.Debug || requestOptions.Options.DebugResponse, func(internalWrappedEvent *output.InternalWrappedEvent) {281internalWrappedEvent.OperatorsResult.PayloadValues = payloadValues282})283if requestOptions.Options.Debug || requestOptions.Options.DebugResponse {284responseOutput := responseBuilder.String()285gologger.Debug().Msgf("[%s] Dumped Websocket response for %s", requestOptions.TemplateID, input)286gologger.Print().Msgf("%s", responsehighlighter.Highlight(event.OperatorsResult, responseOutput, requestOptions.Options.NoColor, false))287}288289callback(event)290return nil291}292293func (request *Request) readWriteInputWebsocket(conn net.Conn, payloadValues map[string]interface{}, input string, respBuilder *strings.Builder) (events map[string]interface{}, req string, err error) {294reqBuilder := &strings.Builder{}295inputEvents := make(map[string]interface{})296297requestOptions := request.options298for _, req := range request.Inputs {299reqBuilder.Grow(len(req.Data))300301finalData, dataErr := expressions.EvaluateByte([]byte(req.Data), payloadValues)302if dataErr != nil {303requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), dataErr)304requestOptions.Progress.IncrementFailedRequestsBy(1)305return nil, "", errors.Wrap(dataErr, evaluateTemplateExpressionErrorMessage)306}307reqBuilder.WriteString(string(finalData))308309err = wsutil.WriteClientMessage(conn, ws.OpText, finalData)310if err != nil {311requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)312requestOptions.Progress.IncrementFailedRequestsBy(1)313return nil, "", errors.Wrap(err, "could not write request to server")314}315316msg, opCode, err := wsutil.ReadServerData(conn)317if err != nil {318requestOptions.Output.Request(requestOptions.TemplateID, input, request.Type().String(), err)319requestOptions.Progress.IncrementFailedRequestsBy(1)320return nil, "", errors.Wrap(err, "could not write request to server")321}322// Only perform matching and writes in case we receive323// text or binary opcode from the websocket server.324if opCode != ws.OpText && opCode != ws.OpBinary {325continue326}327328respBuilder.Write(msg)329if req.Name != "" {330bufferStr := string(msg)331inputEvents[req.Name] = bufferStr332333// Run any internal extractors for the request here and add found values to map.334if request.CompiledOperators != nil {335values := request.CompiledOperators.ExecuteInternalExtractors(map[string]interface{}{req.Name: bufferStr}, protocols.MakeDefaultExtractFunc)336maps.Copy(inputEvents, values)337}338}339}340return inputEvents, reqBuilder.String(), nil341}342343// getAddress returns the address of the host to make request to344func getAddress(toTest string) (string, error) {345parsed, err := url.Parse(toTest)346if err != nil {347return "", errors.Wrap(err, parseUrlErrorMessage)348}349scheme := strings.ToLower(parsed.Scheme)350351if scheme != "ws" && scheme != "wss" {352return "", fmt.Errorf("invalid url scheme provided: %s", scheme)353}354if parsed != nil && parsed.Host != "" {355return parsed.Host, nil356}357return "", nil358}359360// Match performs matching operation for a matcher on model and returns:361// true and a list of matched snippets if the matcher type is supports it362// otherwise false and an empty string slice363func (request *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) {364return protocols.MakeDefaultMatchFunc(data, matcher)365}366367// Extract performs extracting operation for an extractor on model and returns true or false.368func (request *Request) Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{} {369return protocols.MakeDefaultExtractFunc(data, matcher)370}371372// MakeResultEvent creates a result event from internal wrapped event373func (request *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent {374return protocols.MakeDefaultResultEvent(request, wrapped)375}376377// GetCompiledOperators returns a list of the compiled operators378func (request *Request) GetCompiledOperators() []*operators.Operators {379return []*operators.Operators{request.CompiledOperators}380}381382// RequestPartDefinitions contains a mapping of request part definitions and their383// description. Multiple definitions are separated by commas.384// Definitions not having a name (generated on runtime) are prefixed & suffixed by <>.385var RequestPartDefinitions = map[string]string{386"type": "Type is the type of request made",387"success": "Success specifies whether websocket connection was successful",388"request": "Websocket request made to the server",389"response": "Websocket response received from the server",390"host": "Host is the input to the template",391"matched": "Matched is the input which was matched upon",392}393394func (request *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent {395fields := protocolutils.GetJsonFieldsFromURL(types.ToString(wrapped.InternalEvent["host"]))396if types.ToString(wrapped.InternalEvent["ip"]) != "" {397fields.Ip = types.ToString(wrapped.InternalEvent["ip"])398}399data := &output.ResultEvent{400TemplateID: types.ToString(request.options.TemplateID),401TemplatePath: types.ToString(request.options.TemplatePath),402Info: request.options.TemplateInfo,403TemplateVerifier: request.options.TemplateVerifier,404Type: types.ToString(wrapped.InternalEvent["type"]),405Host: fields.Host,406Port: fields.Port,407Matched: types.ToString(wrapped.InternalEvent["matched"]),408Metadata: wrapped.OperatorsResult.PayloadValues,409ExtractedResults: wrapped.OperatorsResult.OutputExtracts,410Timestamp: time.Now(),411MatcherStatus: true,412IP: fields.Ip,413Request: types.ToString(wrapped.InternalEvent["request"]),414Response: types.ToString(wrapped.InternalEvent["response"]),415TemplateEncoded: request.options.EncodeTemplate(),416Error: types.ToString(wrapped.InternalEvent["error"]),417}418return data419}420421// Type returns the type of the protocol request422func (request *Request) Type() templateTypes.ProtocolType {423return templateTypes.WebsocketProtocol424}425426// UpdateOptions replaces this request's options with a new copy427func (r *Request) UpdateOptions(opts *protocols.ExecutorOptions) {428r.options.ApplyNewEngineOptions(opts)429}430431432