nuclei/pkg/protocols/http/operators.go

207 lines
7.5 KiB
Go
Raw Normal View History

package http
import (
"net/http"
"strings"
"time"
2020-12-24 20:47:41 +05:30
"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/helpers/responsehighlighter"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/utils"
"github.com/projectdiscovery/nuclei/v3/pkg/types"
)
2020-12-24 20:47:41 +05:30
// Match matches a generic data response again a given matcher
// TODO: Try to consolidate this in protocols.MakeDefaultMatchFunc to avoid any inconsistencies
func (request *Request) Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string) {
item, ok := request.getMatchPart(matcher.Part, data)
if !ok && matcher.Type.MatcherType != matchers.DSLMatcher {
return false, []string{}
}
2020-12-24 20:47:41 +05:30
switch matcher.GetType() {
case matchers.StatusMatcher:
statusCode, ok := getStatusCode(data)
2020-12-24 20:47:41 +05:30
if !ok {
return false, []string{}
2020-12-24 20:47:41 +05:30
}
return matcher.Result(matcher.MatchStatusCode(statusCode)), []string{responsehighlighter.CreateStatusCodeSnippet(data["response"].(string), statusCode)}
2020-12-24 20:47:41 +05:30
case matchers.SizeMatcher:
return matcher.Result(matcher.MatchSize(len(item))), []string{}
2020-12-24 20:47:41 +05:30
case matchers.WordsMatcher:
return matcher.ResultWithMatchedSnippet(matcher.MatchWords(item, data))
2020-12-24 20:47:41 +05:30
case matchers.RegexMatcher:
return matcher.ResultWithMatchedSnippet(matcher.MatchRegex(item))
2020-12-24 20:47:41 +05:30
case matchers.BinaryMatcher:
return matcher.ResultWithMatchedSnippet(matcher.MatchBinary(item))
2020-12-24 20:47:41 +05:30
case matchers.DSLMatcher:
return matcher.Result(matcher.MatchDSL(data)), []string{}
case matchers.XPathMatcher:
return matcher.Result(matcher.MatchXPath(item)), []string{}
2020-12-24 20:47:41 +05:30
}
return false, []string{}
2020-12-24 20:47:41 +05:30
}
func getStatusCode(data map[string]interface{}) (int, bool) {
statusCodeValue, ok := data["status_code"]
if !ok {
return 0, false
}
statusCode, ok := statusCodeValue.(int)
if !ok {
return 0, false
}
return statusCode, true
}
2021-09-07 17:31:46 +03:00
// Extract performs extracting operation for an extractor on model and returns true or false.
func (request *Request) Extract(data map[string]interface{}, extractor *extractors.Extractor) map[string]struct{} {
item, ok := request.getMatchPart(extractor.Part, data)
2022-04-20 11:32:13 +02:00
if !ok && !extractors.SupportsMap(extractor) {
return nil
2020-12-24 20:47:41 +05:30
}
switch extractor.GetType() {
case extractors.RegexExtractor:
return extractor.ExtractRegex(item)
case extractors.KValExtractor:
return extractor.ExtractKval(data)
2021-08-02 21:43:50 +05:30
case extractors.XPathExtractor:
return extractor.ExtractXPath(item)
2021-07-31 22:49:23 +02:00
case extractors.JSONExtractor:
2021-08-01 14:42:04 +02:00
return extractor.ExtractJSON(item)
2022-04-20 11:32:13 +02:00
case extractors.DSLExtractor:
return extractor.ExtractDSL(data)
}
return nil
}
// getMatchPart returns the match part honoring "all" matchers + others.
func (request *Request) getMatchPart(part string, data output.InternalEvent) (string, bool) {
2021-11-11 17:30:25 +05:30
if part == "" {
part = "body"
}
if part == "header" {
part = "all_headers"
}
var itemStr string
if part == "all" {
builder := &strings.Builder{}
builder.WriteString(types.ToString(data["body"]))
builder.WriteString(types.ToString(data["all_headers"]))
itemStr = builder.String()
} else {
item, ok := data[part]
if !ok {
return "", false
}
itemStr = types.ToString(item)
}
return itemStr, true
2020-12-24 20:47:41 +05:30
}
2021-09-07 17:31:46 +03:00
// responseToDSLMap converts an HTTP response to a map for use in DSL matching
func (request *Request) responseToDSLMap(resp *http.Response, host, matched, rawReq, rawResp, body, headers string, duration time.Duration, extra map[string]interface{}) output.InternalEvent {
data := make(output.InternalEvent, 12+len(extra)+len(resp.Header)+len(resp.Cookies()))
for k, v := range extra {
data[k] = v
}
2020-12-24 12:13:18 +05:30
for _, cookie := range resp.Cookies() {
request.setHashOrDefault(data, strings.ToLower(cookie.Name), cookie.Value)
2020-12-24 12:13:18 +05:30
}
for k, v := range resp.Header {
2021-02-26 13:13:11 +05:30
k = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(k), "-", "_"))
request.setHashOrDefault(data, k, strings.Join(v, " "))
}
data["host"] = host
data["type"] = request.Type().String()
data["matched"] = matched
request.setHashOrDefault(data, "request", rawReq)
request.setHashOrDefault(data, "response", rawResp)
data["status_code"] = resp.StatusCode
request.setHashOrDefault(data, "body", body)
request.setHashOrDefault(data, "all_headers", headers)
request.setHashOrDefault(data, "header", headers)
data["duration"] = duration.Seconds()
data["template-id"] = request.options.TemplateID
data["template-info"] = request.options.TemplateInfo
data["template-path"] = request.options.TemplatePath
data["content_length"] = utils.CalculateContentLength(resp.ContentLength, int64(len(body)))
if request.StopAtFirstMatch || request.options.StopAtFirstMatch {
data["stop-at-first-match"] = true
}
return data
}
// TODO: disabling hdd storage while testing backpressure mechanism
func (request *Request) setHashOrDefault(data output.InternalEvent, k string, v string) {
// if hash, err := request.options.Storage.SetString(v); err == nil {
// data[k] = hash
// } else {
data[k] = v
//}
}
// MakeResultEvent creates a result event from internal wrapped event
func (request *Request) MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent {
return protocols.MakeDefaultResultEvent(request, wrapped)
2021-01-11 21:11:35 +05:30
}
func (request *Request) GetCompiledOperators() []*operators.Operators {
return []*operators.Operators{request.CompiledOperators}
}
func (request *Request) MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent {
fields := utils.GetJsonFieldsFromURL(types.ToString(wrapped.InternalEvent["host"]))
if types.ToString(wrapped.InternalEvent["ip"]) != "" {
fields.Ip = types.ToString(wrapped.InternalEvent["ip"])
}
if types.ToString(wrapped.InternalEvent["path"]) != "" {
fields.Path = types.ToString(wrapped.InternalEvent["path"])
}
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
var isGlobalMatchers bool
if value, ok := wrapped.InternalEvent["global-matchers"]; ok {
isGlobalMatchers = value.(bool)
}
2021-01-11 21:11:35 +05:30
data := &output.ResultEvent{
TemplateID: types.ToString(wrapped.InternalEvent["template-id"]),
2021-06-05 18:01:08 +05:30
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,
Scheme: fields.Scheme,
URL: fields.URL,
Path: fields.Path,
Matched: types.ToString(wrapped.InternalEvent["matched"]),
Metadata: wrapped.OperatorsResult.PayloadValues,
ExtractedResults: wrapped.OperatorsResult.OutputExtracts,
Timestamp: time.Now(),
MatcherStatus: true,
IP: fields.Ip,
feat: global matchers (#5701) * feat: global matchers Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com> * feat(globalmatchers): make `Callback` as type Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `passive` term to `(matchers-)static` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `origin-template-*` event also use `Set` method instead of `maps.Clone` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat: update `matchers-static` term to `global-matchers` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): clone event before `operator.Execute` Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(tmplexec): don't store `matched` on `global-matchers` templ This will end up generating 2 events from the same `scan.ScanContext` if one of the templates has `global-matchers` enabled. This way, non- `global-matchers` templates can enter the `writeFailureCallback` func to log failure output. Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): initializes `requests` on `New` Signed-off-by: Dwi Siswanto <git@dw1.io> * feat(globalmatchers): add `hasStorage` method Signed-off-by: Dwi Siswanto <git@dw1.io> * refactor(templates): rename global matchers checks method Signed-off-by: Dwi Siswanto <git@dw1.io> * fix(loader): handle nil `templates.Template` pointer Signed-off-by: Dwi Siswanto <git@dw1.io> --------- Signed-off-by: Dwi Siswanto <git@dw1.io> Co-authored-by: Ice3man543 <ice3man543@users.noreply.github.com>
2024-10-14 20:55:46 +07:00
GlobalMatchers: isGlobalMatchers,
Request: types.ToString(wrapped.InternalEvent["request"]),
Response: request.truncateResponse(wrapped.InternalEvent["response"]),
CURLCommand: types.ToString(wrapped.InternalEvent["curl-command"]),
TemplateEncoded: request.options.EncodeTemplate(),
Error: types.ToString(wrapped.InternalEvent["error"]),
}
2021-01-11 21:11:35 +05:30
return data
}
func (request *Request) truncateResponse(response interface{}) string {
responseString := types.ToString(response)
if len(responseString) > request.options.Options.ResponseSaveSize {
return responseString[:request.options.Options.ResponseSaveSize]
}
return responseString
}