nuclei/lib/sdk_private.go
Ice3man fa56800fcc
Fuzzing layer enhancements + input-types support (#4477)
* feat: move fuzz package to root directory

* feat: added support for input providers like openapi,postman,etc

* feat: integration of new fuzzing logic in engine

* bugfix: use and instead of or

* fixed lint errors

* go mod tidy

* add new reqresp type + bump utils

* custom http request parser

* use new struct type RequestResponse

* introduce unified input/target provider

* abstract input formats via new inputprovider

* completed input provider refactor

* remove duplicated code

* add sdk method to load targets

* rename component url->path

* add new yaml format + remove duplicated code

* use gopkg.in/yaml.v3 for parsing

* update .gitignore

* refactor/move + docs fuzzing in http protocol

* fuzz: header + query integration test using fuzzplayground

* fix integration test runner in windows

* feat add support for filter in http fuzz

* rewrite header/query integration test with filter

* add replace regex rule

* support kv fuzzing + misc updates

* add path fuzzing example + misc improvements

* fix matchedURL + skip httpx on multi formats

* cookie fuzz integration test

* add json body + params body tests

* feat add multipart/form-data fuzzing support

* add all fuzz body integration test

* misc bug fixes + minor refactor

* add multipart form + body form unit tests

* only run fuzzing templates if -fuzz flag is given

* refactor/move fuzz playground server to pkg

* fix integration test + refactor

* add auth types and strategies

* add file auth provider

* start implementing auth logic in http

* add logic in http protocol

* static auth implemented for http

* default :80,:443 normalization

* feat: dynamic auth init

* feat: dynamic auth using templates

* validate targets count in openapi+swagger

* inputformats: add support to accept variables

* fix workflow integration test

* update lazy cred fetch logic

* fix unit test

* drop postman support

* domain related normalization

* update secrets.yaml file format + misc updates

* add auth prefetch option

* remove old secret files

* add fuzzing+auth related sdk options

* fix/support multiple mode in kv header fuzzing

* rename 'headers' -> 'header' in fuzzing rules

* fix deadlock due to merge conflict resolution

* misc update

* add bool type in parsed value

* add openapi validation+override+ new flags

* misc updates

* remove optional path parameters when unavailable

* fix swagger.yaml file

* misc updates

* update print msg

* multiple openapi validation enchancements + appMode

* add optional params in required_openapi_vars.yaml file

* improve warning/verbose msgs in format

* fix skip-format-validation not working

* use 'params/parameter' instead of 'variable' in openapi

* add retry support for falky tests

* fix nuclei loading ignored templates (#4849)

* fix tag include logic

* fix unit test

* remove quoting in extractor output

* remove quote in debug code command

* feat: issue tracker URLs in JSON + misc fixes (#4855)

* feat: issue tracker URLs in JSON + misc fixes

* misc changes

* feat: status update support for issues

* feat: report metadata generation hook support

* feat: added CLI summary of tickets created

* misc changes

* introduce `disable-unsigned-templates` flag (#4820)

* introduce `disable-unsigned-templates` flag

* minor

* skip instead of exit

* remove duplicate imports

* use stats package + misc enhancements

* force display warning + adjust skipped stats in unsigned count

* include unsigned skipped templates without -dut flag

---------

Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io>

* Purge cache on global callback set (#4840)

* purge cache on global callback set

* lint

* purging cache

* purge cache in runner after loading templates

* include internal cache from parsers + add global cache register/purge via config

* remove disable cache purge option

---------

Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io>

* misc update

* add application/octet-stream support

* openapi: support path specific params

* misc option + readme update

---------

Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io>
Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io>
Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com>
Co-authored-by: Mzack9999 <mzack9999@protonmail.com>
2024-03-14 03:08:53 +05:30

234 lines
7.3 KiB
Go

package nuclei
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/logrusorgru/aurora"
"github.com/pkg/errors"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/gologger/levels"
"github.com/projectdiscovery/httpx/common/httpx"
"github.com/projectdiscovery/nuclei/v3/internal/runner"
"github.com/projectdiscovery/nuclei/v3/pkg/authprovider"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/config"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog/disk"
"github.com/projectdiscovery/nuclei/v3/pkg/core"
"github.com/projectdiscovery/nuclei/v3/pkg/input/provider"
"github.com/projectdiscovery/nuclei/v3/pkg/installer"
"github.com/projectdiscovery/nuclei/v3/pkg/output"
"github.com/projectdiscovery/nuclei/v3/pkg/progress"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/hosterrorscache"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/interactsh"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolinit"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/protocolstate"
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/http/httpclientpool"
"github.com/projectdiscovery/nuclei/v3/pkg/reporting"
"github.com/projectdiscovery/nuclei/v3/pkg/testutils"
"github.com/projectdiscovery/nuclei/v3/pkg/types"
nucleiUtils "github.com/projectdiscovery/nuclei/v3/pkg/utils"
"github.com/projectdiscovery/ratelimit"
)
// applyRequiredDefaults to options
func (e *NucleiEngine) applyRequiredDefaults() {
mockoutput := testutils.NewMockOutputWriter(e.opts.OmitTemplate)
mockoutput.WriteCallback = func(event *output.ResultEvent) {
if len(e.resultCallbacks) > 0 {
for _, callback := range e.resultCallbacks {
if callback != nil {
callback(event)
}
}
return
}
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("[%v] ", event.TemplateID))
if event.Matched != "" {
sb.WriteString(event.Matched)
} else {
sb.WriteString(event.Host)
}
fmt.Println(sb.String())
}
if e.onFailureCallback != nil {
mockoutput.FailureCallback = e.onFailureCallback
}
if e.customWriter != nil {
e.customWriter = output.NewMultiWriter(e.customWriter, mockoutput)
} else {
e.customWriter = mockoutput
}
if e.customProgress == nil {
e.customProgress = &testutils.MockProgressClient{}
}
if e.hostErrCache == nil {
e.hostErrCache = hosterrorscache.New(30, hosterrorscache.DefaultMaxHostsCount, nil)
}
// setup interactsh
if e.interactshOpts != nil {
e.interactshOpts.Output = e.customWriter
e.interactshOpts.Progress = e.customProgress
} else {
e.interactshOpts = interactsh.DefaultOptions(e.customWriter, e.rc, e.customProgress)
}
if e.rateLimiter == nil {
e.rateLimiter = ratelimit.New(context.Background(), 150, time.Second)
}
if e.opts.ExcludeTags == nil {
e.opts.ExcludeTags = []string{}
}
// these templates are known to have weak matchers
// and idea is to disable them to avoid false positives
e.opts.ExcludeTags = append(e.opts.ExcludeTags, config.ReadIgnoreFile().Tags...)
e.inputProvider = provider.NewSimpleInputProvider()
}
// init
func (e *NucleiEngine) init() error {
if e.opts.Verbose {
gologger.DefaultLogger.SetMaxLevel(levels.LevelVerbose)
} else if e.opts.Debug {
gologger.DefaultLogger.SetMaxLevel(levels.LevelDebug)
} else if e.opts.Silent {
gologger.DefaultLogger.SetMaxLevel(levels.LevelSilent)
}
if err := runner.ValidateOptions(e.opts); err != nil {
return err
}
if e.opts.ProxyInternal && types.ProxyURL != "" || types.ProxySocksURL != "" {
httpclient, err := httpclientpool.Get(e.opts, &httpclientpool.Configuration{})
if err != nil {
return err
}
e.httpClient = httpclient
}
_ = protocolstate.Init(e.opts)
_ = protocolinit.Init(e.opts)
e.applyRequiredDefaults()
var err error
// setup progressbar
if e.enableStats {
progressInstance, progressErr := progress.NewStatsTicker(e.opts.StatsInterval, e.enableStats, e.opts.StatsJSON, false, e.opts.MetricsPort)
if progressErr != nil {
return err
}
e.customProgress = progressInstance
e.interactshOpts.Progress = progressInstance
}
if err := reporting.CreateConfigIfNotExists(); err != nil {
return err
}
// we don't support reporting config in sdk mode
if e.rc, err = reporting.New(&reporting.Options{}, "", false); err != nil {
return err
}
e.interactshOpts.IssuesClient = e.rc
if e.httpClient != nil {
e.interactshOpts.HTTPClient = e.httpClient
}
if e.interactshClient, err = interactsh.New(e.interactshOpts); err != nil {
return err
}
e.catalog = disk.NewCatalog(config.DefaultConfig.TemplatesDirectory)
e.executerOpts = protocols.ExecutorOptions{
Output: e.customWriter,
Options: e.opts,
Progress: e.customProgress,
Catalog: e.catalog,
IssuesClient: e.rc,
RateLimiter: e.rateLimiter,
Interactsh: e.interactshClient,
HostErrorsCache: e.hostErrCache,
Colorizer: aurora.NewAurora(true),
ResumeCfg: types.NewResumeCfg(),
Browser: e.browserInstance,
}
if len(e.opts.SecretsFile) > 0 {
authTmplStore, err := runner.GetAuthTmplStore(*e.opts, e.catalog, e.executerOpts)
if err != nil {
return errors.Wrap(err, "failed to load dynamic auth templates")
}
authOpts := &authprovider.AuthProviderOptions{SecretsFiles: e.opts.SecretsFile}
authOpts.LazyFetchSecret = runner.GetLazyAuthFetchCallback(&runner.AuthLazyFetchOptions{
TemplateStore: authTmplStore,
ExecOpts: e.executerOpts,
})
// initialize auth provider
provider, err := authprovider.NewAuthProvider(authOpts)
if err != nil {
return errors.Wrap(err, "could not create auth provider")
}
e.executerOpts.AuthProvider = provider
}
if e.authprovider != nil {
e.executerOpts.AuthProvider = e.authprovider
}
// prefetch secrets
if e.executerOpts.AuthProvider != nil && e.opts.PreFetchSecrets {
if err := e.executerOpts.AuthProvider.PreFetchSecrets(); err != nil {
return errors.Wrap(err, "could not prefetch secrets")
}
}
if e.opts.RateLimitMinute > 0 {
e.executerOpts.RateLimiter = ratelimit.New(context.Background(), uint(e.opts.RateLimitMinute), time.Minute)
} else if e.opts.RateLimit > 0 {
e.executerOpts.RateLimiter = ratelimit.New(context.Background(), uint(e.opts.RateLimit), time.Second)
} else {
e.executerOpts.RateLimiter = ratelimit.NewUnlimited(context.Background())
}
e.engine = core.New(e.opts)
e.engine.SetExecuterOptions(e.executerOpts)
httpxOptions := httpx.DefaultOptions
httpxOptions.Timeout = 5 * time.Second
if client, err := httpx.New(&httpxOptions); err != nil {
return err
} else {
e.httpxClient = nucleiUtils.GetInputLivenessChecker(client)
}
// Only Happens once regardless how many times this function is called
// This will update ignore file to filter out templates with weak matchers to avoid false positives
// and also upgrade templates to latest version if available
installer.NucleiSDKVersionCheck()
return e.processUpdateCheckResults()
}
type syncOnce struct {
sync.Once
}
var updateCheckInstance = &syncOnce{}
// processUpdateCheckResults processes update check results
func (e *NucleiEngine) processUpdateCheckResults() error {
var err error
updateCheckInstance.Do(func() {
if e.onUpdateAvailableCallback != nil {
e.onUpdateAvailableCallback(config.DefaultConfig.LatestNucleiTemplatesVersion)
}
tm := installer.TemplateManager{}
err = tm.UpdateIfOutdated()
})
return err
}