github.com/projectdiscovery/nuclei/v2@v2.9.15/pkg/testutils/testutils.go (about)

     1  package testutils
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/projectdiscovery/ratelimit"
     8  
     9  	"github.com/logrusorgru/aurora"
    10  
    11  	"github.com/projectdiscovery/gologger/levels"
    12  	"github.com/projectdiscovery/nuclei/v2/pkg/catalog/config"
    13  	"github.com/projectdiscovery/nuclei/v2/pkg/catalog/disk"
    14  	"github.com/projectdiscovery/nuclei/v2/pkg/model"
    15  	"github.com/projectdiscovery/nuclei/v2/pkg/model/types/severity"
    16  	"github.com/projectdiscovery/nuclei/v2/pkg/output"
    17  	"github.com/projectdiscovery/nuclei/v2/pkg/progress"
    18  	"github.com/projectdiscovery/nuclei/v2/pkg/protocols"
    19  	"github.com/projectdiscovery/nuclei/v2/pkg/protocols/common/protocolinit"
    20  	"github.com/projectdiscovery/nuclei/v2/pkg/types"
    21  	"github.com/projectdiscovery/nuclei/v2/pkg/utils"
    22  )
    23  
    24  // Init initializes the protocols and their configurations
    25  func Init(options *types.Options) {
    26  	_ = protocolinit.Init(options)
    27  }
    28  
    29  // DefaultOptions is the default options structure for nuclei during mocking.
    30  var DefaultOptions = &types.Options{
    31  	Metrics:                    false,
    32  	Debug:                      false,
    33  	DebugRequests:              false,
    34  	DebugResponse:              false,
    35  	Silent:                     false,
    36  	Verbose:                    false,
    37  	NoColor:                    true,
    38  	UpdateTemplates:            false,
    39  	JSONL:                      false,
    40  	OmitRawRequests:            false,
    41  	EnableProgressBar:          false,
    42  	TemplateList:               false,
    43  	Stdin:                      false,
    44  	StopAtFirstMatch:           false,
    45  	NoMeta:                     false,
    46  	Project:                    false,
    47  	MetricsPort:                0,
    48  	BulkSize:                   25,
    49  	TemplateThreads:            10,
    50  	Timeout:                    5,
    51  	Retries:                    1,
    52  	RateLimit:                  150,
    53  	ProjectPath:                "",
    54  	Severities:                 severity.Severities{},
    55  	Targets:                    []string{},
    56  	TargetsFilePath:            "",
    57  	Output:                     "",
    58  	Proxy:                      []string{},
    59  	TraceLogFile:               "",
    60  	Templates:                  []string{},
    61  	ExcludedTemplates:          []string{},
    62  	CustomHeaders:              []string{},
    63  	InteractshURL:              "https://oast.fun",
    64  	InteractionsCacheSize:      5000,
    65  	InteractionsEviction:       60,
    66  	InteractionsCoolDownPeriod: 5,
    67  	InteractionsPollDuration:   5,
    68  	GitHubTemplateRepo:         []string{},
    69  	GitHubToken:                "",
    70  }
    71  
    72  // TemplateInfo contains info for a mock executed template.
    73  type TemplateInfo struct {
    74  	ID   string
    75  	Info model.Info
    76  	Path string
    77  }
    78  
    79  // NewMockExecuterOptions creates a new mock executeroptions struct
    80  func NewMockExecuterOptions(options *types.Options, info *TemplateInfo) *protocols.ExecutorOptions {
    81  	progressImpl, _ := progress.NewStatsTicker(0, false, false, false, false, 0)
    82  	executerOpts := &protocols.ExecutorOptions{
    83  		TemplateID:   info.ID,
    84  		TemplateInfo: info.Info,
    85  		TemplatePath: info.Path,
    86  		Output:       NewMockOutputWriter(),
    87  		Options:      options,
    88  		Progress:     progressImpl,
    89  		ProjectFile:  nil,
    90  		IssuesClient: nil,
    91  		Browser:      nil,
    92  		Catalog:      disk.NewCatalog(config.DefaultConfig.TemplatesDirectory),
    93  		RateLimiter:  ratelimit.New(context.Background(), uint(options.RateLimit), time.Second),
    94  	}
    95  	return executerOpts
    96  }
    97  
    98  // NoopWriter is a NooP gologger writer.
    99  type NoopWriter struct{}
   100  
   101  // Write writes the data to an output writer.
   102  func (n *NoopWriter) Write(data []byte, level levels.Level) {}
   103  
   104  // MockOutputWriter is a mocked output writer.
   105  type MockOutputWriter struct {
   106  	aurora          aurora.Aurora
   107  	RequestCallback func(templateID, url, requestType string, err error)
   108  	WriteCallback   func(o *output.ResultEvent)
   109  }
   110  
   111  // NewMockOutputWriter creates a new mock output writer
   112  func NewMockOutputWriter() *MockOutputWriter {
   113  	return &MockOutputWriter{aurora: aurora.NewAurora(false)}
   114  }
   115  
   116  // Close closes the output writer interface
   117  func (m *MockOutputWriter) Close() {}
   118  
   119  // Colorizer returns the colorizer instance for writer
   120  func (m *MockOutputWriter) Colorizer() aurora.Aurora {
   121  	return m.aurora
   122  }
   123  
   124  // Write writes the event to file and/or screen.
   125  func (m *MockOutputWriter) Write(result *output.ResultEvent) error {
   126  	if m.WriteCallback != nil {
   127  		m.WriteCallback(result)
   128  	}
   129  	return nil
   130  }
   131  
   132  // Request writes a log the requests trace log
   133  func (m *MockOutputWriter) Request(templateID, url, requestType string, err error) {
   134  	if m.RequestCallback != nil {
   135  		m.RequestCallback(templateID, url, requestType, err)
   136  	}
   137  }
   138  
   139  // WriteFailure writes the event to file and/or screen.
   140  func (m *MockOutputWriter) WriteFailure(wrappedEvent *output.InternalWrappedEvent) error {
   141  	if m.WriteCallback != nil {
   142  		// create event
   143  		event := wrappedEvent.InternalEvent
   144  		templatePath, templateURL := utils.TemplatePathURL(types.ToString(event["template-path"]), types.ToString(event["template-id"]))
   145  		var templateInfo model.Info
   146  		if ti, ok := event["template-info"].(model.Info); ok {
   147  			templateInfo = ti
   148  		}
   149  		data := &output.ResultEvent{
   150  			Template:      templatePath,
   151  			TemplateURL:   templateURL,
   152  			TemplateID:    types.ToString(event["template-id"]),
   153  			TemplatePath:  types.ToString(event["template-path"]),
   154  			Info:          templateInfo,
   155  			Type:          types.ToString(event["type"]),
   156  			Host:          types.ToString(event["host"]),
   157  			Request:       types.ToString(event["request"]),
   158  			Response:      types.ToString(event["response"]),
   159  			MatcherStatus: false,
   160  			Timestamp:     time.Now(),
   161  		}
   162  		m.WriteCallback(data)
   163  	}
   164  	return nil
   165  }
   166  func (m *MockOutputWriter) WriteStoreDebugData(host, templateID, eventType string, data string) {
   167  
   168  }
   169  
   170  type MockProgressClient struct{}
   171  
   172  // Stop stops the progress recorder.
   173  func (m *MockProgressClient) Stop() {}
   174  
   175  // Init inits the progress bar with initial details for scan
   176  func (m *MockProgressClient) Init(hostCount int64, rulesCount int, requestCount int64) {}
   177  
   178  // AddToTotal adds a value to the total request count
   179  func (m *MockProgressClient) AddToTotal(delta int64) {}
   180  
   181  // IncrementRequests increments the requests counter by 1.
   182  func (m *MockProgressClient) IncrementRequests() {}
   183  
   184  // SetRequests sets the counter by incrementing it with a delta
   185  func (m *MockProgressClient) SetRequests(count uint64) {}
   186  
   187  // IncrementMatched increments the matched counter by 1.
   188  func (m *MockProgressClient) IncrementMatched() {}
   189  
   190  // IncrementErrorsBy increments the error counter by count.
   191  func (m *MockProgressClient) IncrementErrorsBy(count int64) {}
   192  
   193  // IncrementFailedRequestsBy increments the number of requests counter by count
   194  // along with errors.
   195  func (m *MockProgressClient) IncrementFailedRequestsBy(count int64) {}