Debian Codegraph @

main.go

raw symbols SCIP
1 package main
2
3 import (
4 "context"
5 "flag"
6 "fmt"
7 "io"
8 "log"
9 "os"
10 "strings"
11 "time"
12
13 "github.com/ffuf/ffuf/v2/pkg/ffuf"
14 "github.com/ffuf/ffuf/v2/pkg/filter"
15 "github.com/ffuf/ffuf/v2/pkg/input"
16 "github.com/ffuf/ffuf/v2/pkg/interactive"
17 "github.com/ffuf/ffuf/v2/pkg/output"
18 "github.com/ffuf/ffuf/v2/pkg/runner"
19 "github.com/ffuf/ffuf/v2/pkg/scraper"
20 )
21
22 type multiStringFlag []string
23 type wordlistFlag []string
24
25 func (m *multiStringFlag) String() string {
26 return ""
27 }
28
29 func (m *wordlistFlag) String() string {
30 return ""
31 }
32
33 func (m *multiStringFlag) Set(value string) error {
34 *m = append(*m, value)
35 return nil
36 }
37
38 func (m *wordlistFlag) Set(value string) error {
39 delimited := strings.Split(value, ",")
40
41 if len(delimited) > 1 {
42 *m = append(*m, delimited...)
43 } else {
44 *m = append(*m, value)
45 }
46
47 return nil
48 }
49
50 // ParseFlags parses the command line flags and (re)populates the ConfigOptions struct
51 func ParseFlags(opts *ffuf.ConfigOptions) *ffuf.ConfigOptions {
52 var ignored bool
53
54 var cookies, autocalibrationstrings, autocalibrationstrategies, headers, inputcommands multiStringFlag
55 var wordlists, encoders wordlistFlag
56
57 cookies = opts.HTTP.Cookies
58 autocalibrationstrings = opts.General.AutoCalibrationStrings
59 headers = opts.HTTP.Headers
60 inputcommands = opts.Input.Inputcommands
61 wordlists = opts.Input.Wordlists
62 encoders = opts.Input.Encoders
63
64 flag.BoolVar(&ignored, "compressed", true, "Dummy flag for copy as curl functionality (ignored)")
65 flag.BoolVar(&ignored, "i", true, "Dummy flag for copy as curl functionality (ignored)")
66 flag.BoolVar(&ignored, "k", false, "Dummy flag for backwards compatibility")
67 flag.BoolVar(&opts.Output.OutputSkipEmptyFile, "or", opts.Output.OutputSkipEmptyFile, "Don't create the output file if we don't have results")
68 flag.BoolVar(&opts.General.AutoCalibration, "ac", opts.General.AutoCalibration, "Automatically calibrate filtering options")
69 flag.BoolVar(&opts.General.AutoCalibrationPerHost, "ach", opts.General.AutoCalibration, "Per host autocalibration")
70 flag.BoolVar(&opts.General.Colors, "c", opts.General.Colors, "Colorize output.")
71 flag.BoolVar(&opts.General.Json, "json", opts.General.Json, "JSON output, printing newline-delimited JSON records")
72 flag.BoolVar(&opts.General.Noninteractive, "noninteractive", opts.General.Noninteractive, "Disable the interactive console functionality")
73 flag.BoolVar(&opts.General.Quiet, "s", opts.General.Quiet, "Do not print additional information (silent mode)")
74 flag.BoolVar(&opts.General.ShowVersion, "V", opts.General.ShowVersion, "Show version information.")
75 flag.BoolVar(&opts.General.StopOn403, "sf", opts.General.StopOn403, "Stop when > 95% of responses return 403 Forbidden")
76 flag.BoolVar(&opts.General.StopOnAll, "sa", opts.General.StopOnAll, "Stop on all error cases. Implies -sf and -se.")
77 flag.BoolVar(&opts.General.StopOnErrors, "se", opts.General.StopOnErrors, "Stop on spurious errors")
78 flag.BoolVar(&opts.General.Verbose, "v", opts.General.Verbose, "Verbose output, printing full URL and redirect location (if any) with the results.")
79 flag.BoolVar(&opts.HTTP.FollowRedirects, "r", opts.HTTP.FollowRedirects, "Follow redirects")
80 flag.BoolVar(&opts.HTTP.IgnoreBody, "ignore-body", opts.HTTP.IgnoreBody, "Do not fetch the response content.")
81 flag.BoolVar(&opts.HTTP.Raw, "raw", opts.HTTP.Raw, "Do not encode URI")
82 flag.BoolVar(&opts.HTTP.Recursion, "recursion", opts.HTTP.Recursion, "Scan recursively. Only FUZZ keyword is supported, and URL (-u) has to end in it.")
83 flag.BoolVar(&opts.HTTP.Http2, "http2", opts.HTTP.Http2, "Use HTTP2 protocol")
84 flag.BoolVar(&opts.Input.DirSearchCompat, "D", opts.Input.DirSearchCompat, "DirSearch wordlist compatibility mode. Used in conjunction with -e flag.")
85 flag.BoolVar(&opts.Input.IgnoreWordlistComments, "ic", opts.Input.IgnoreWordlistComments, "Ignore wordlist comments")
86 flag.IntVar(&opts.General.MaxTime, "maxtime", opts.General.MaxTime, "Maximum running time in seconds for entire process.")
87 flag.IntVar(&opts.General.MaxTimeJob, "maxtime-job", opts.General.MaxTimeJob, "Maximum running time in seconds per job.")
88 flag.IntVar(&opts.General.Rate, "rate", opts.General.Rate, "Rate of requests per second")
89 flag.IntVar(&opts.General.Threads, "t", opts.General.Threads, "Number of concurrent threads.")
90 flag.IntVar(&opts.HTTP.RecursionDepth, "recursion-depth", opts.HTTP.RecursionDepth, "Maximum recursion depth.")
91 flag.IntVar(&opts.HTTP.Timeout, "timeout", opts.HTTP.Timeout, "HTTP request timeout in seconds.")
92 flag.IntVar(&opts.Input.InputNum, "input-num", opts.Input.InputNum, "Number of inputs to test. Used in conjunction with --input-cmd.")
93 flag.StringVar(&opts.General.AutoCalibrationKeyword, "ack", opts.General.AutoCalibrationKeyword, "Autocalibration keyword")
94 flag.StringVar(&opts.HTTP.ClientCert, "cc", "", "Client cert for authentication. Client key needs to be defined as well for this to work")
95 flag.StringVar(&opts.HTTP.ClientKey, "ck", "", "Client key for authentication. Client certificate needs to be defined as well for this to work")
96 flag.StringVar(&opts.General.ConfigFile, "config", "", "Load configuration from a file")
97 flag.StringVar(&opts.General.ScraperFile, "scraperfile", "", "Custom scraper file path")
98 flag.StringVar(&opts.General.Scrapers, "scrapers", opts.General.Scrapers, "Active scraper groups")
99 flag.StringVar(&opts.Filter.Mode, "fmode", opts.Filter.Mode, "Filter set operator. Either of: and, or")
100 flag.StringVar(&opts.Filter.Lines, "fl", opts.Filter.Lines, "Filter by amount of lines in response. Comma separated list of line counts and ranges")
101 flag.StringVar(&opts.Filter.Regexp, "fr", opts.Filter.Regexp, "Filter regexp")
102 flag.StringVar(&opts.Filter.Size, "fs", opts.Filter.Size, "Filter HTTP response size. Comma separated list of sizes and ranges")
103 flag.StringVar(&opts.Filter.Status, "fc", opts.Filter.Status, "Filter HTTP status codes from response. Comma separated list of codes and ranges")
104 flag.StringVar(&opts.Filter.Time, "ft", opts.Filter.Time, "Filter by number of milliseconds to the first response byte, either greater or less than. EG: >100 or <100")
105 flag.StringVar(&opts.Filter.Words, "fw", opts.Filter.Words, "Filter by amount of words in response. Comma separated list of word counts and ranges")
106 flag.StringVar(&opts.General.Delay, "p", opts.General.Delay, "Seconds of `delay` between requests, or a range of random delay. For example \"0.1\" or \"0.1-2.0\"")
107 flag.StringVar(&opts.General.Searchhash, "search", opts.General.Searchhash, "Search for a FFUFHASH payload from ffuf history")
108 flag.StringVar(&opts.HTTP.Data, "d", opts.HTTP.Data, "POST data")
109 flag.StringVar(&opts.HTTP.Data, "data", opts.HTTP.Data, "POST data (alias of -d)")
110 flag.StringVar(&opts.HTTP.Data, "data-ascii", opts.HTTP.Data, "POST data (alias of -d)")
111 flag.StringVar(&opts.HTTP.Data, "data-binary", opts.HTTP.Data, "POST data (alias of -d)")
112 flag.StringVar(&opts.HTTP.Method, "X", opts.HTTP.Method, "HTTP method to use")
113 flag.StringVar(&opts.HTTP.ProxyURL, "x", opts.HTTP.ProxyURL, "Proxy URL (SOCKS5 or HTTP). For example: http://127.0.0.1:8080 or socks5://127.0.0.1:8080")
114 flag.StringVar(&opts.HTTP.ReplayProxyURL, "replay-proxy", opts.HTTP.ReplayProxyURL, "Replay matched requests using this proxy.")
115 flag.StringVar(&opts.HTTP.RecursionStrategy, "recursion-strategy", opts.HTTP.RecursionStrategy, "Recursion strategy: \"default\" for a redirect based, and \"greedy\" to recurse on all matches")
116 flag.StringVar(&opts.HTTP.URL, "u", opts.HTTP.URL, "Target URL")
117 flag.StringVar(&opts.HTTP.SNI, "sni", opts.HTTP.SNI, "Target TLS SNI, does not support FUZZ keyword")
118 flag.StringVar(&opts.Input.Extensions, "e", opts.Input.Extensions, "Comma separated list of extensions. Extends FUZZ keyword.")
119 flag.StringVar(&opts.Input.InputMode, "mode", opts.Input.InputMode, "Multi-wordlist operation mode. Available modes: clusterbomb, pitchfork, sniper")
120 flag.StringVar(&opts.Input.InputShell, "input-shell", opts.Input.InputShell, "Shell to be used for running command")
121 flag.StringVar(&opts.Input.Request, "request", opts.Input.Request, "File containing the raw http request")
122 flag.StringVar(&opts.Input.RequestProto, "request-proto", opts.Input.RequestProto, "Protocol to use along with raw request")
123 flag.StringVar(&opts.Matcher.Mode, "mmode", opts.Matcher.Mode, "Matcher set operator. Either of: and, or")
124 flag.StringVar(&opts.Matcher.Lines, "ml", opts.Matcher.Lines, "Match amount of lines in response")
125 flag.StringVar(&opts.Matcher.Regexp, "mr", opts.Matcher.Regexp, "Match regexp")
126 flag.StringVar(&opts.Matcher.Size, "ms", opts.Matcher.Size, "Match HTTP response size")
127 flag.StringVar(&opts.Matcher.Status, "mc", opts.Matcher.Status, "Match HTTP status codes, or \"all\" for everything.")
128 flag.StringVar(&opts.Matcher.Time, "mt", opts.Matcher.Time, "Match how many milliseconds to the first response byte, either greater or less than. EG: >100 or <100")
129 flag.StringVar(&opts.Matcher.Words, "mw", opts.Matcher.Words, "Match amount of words in response")
130 flag.StringVar(&opts.Output.AuditLog, "audit-log", opts.Output.AuditLog, "Write audit log containing all requests, responses and config")
131 flag.StringVar(&opts.Output.DebugLog, "debug-log", opts.Output.DebugLog, "Write all of the internal logging to the specified file.")
132 flag.StringVar(&opts.Output.OutputDirectory, "od", opts.Output.OutputDirectory, "Directory path to store matched results to.")
133 flag.StringVar(&opts.Output.OutputFile, "o", opts.Output.OutputFile, "Write output to file")
134 flag.StringVar(&opts.Output.OutputFormat, "of", opts.Output.OutputFormat, "Output file format. Available formats: json, ejson, html, md, csv, ecsv (or, 'all' for all formats)")
135 flag.Var(&autocalibrationstrings, "acc", "Custom auto-calibration string. Can be used multiple times. Implies -ac")
136 flag.Var(&autocalibrationstrategies, "acs", "Custom auto-calibration strategies. Can be used multiple times. Implies -ac")
137 flag.Var(&cookies, "b", "Cookie data `\"NAME1=VALUE1; NAME2=VALUE2\"` for copy as curl functionality.")
138 flag.Var(&cookies, "cookie", "Cookie data (alias of -b)")
139 flag.Var(&headers, "H", "Header `\"Name: Value\"`, separated by colon. Multiple -H flags are accepted.")
140 flag.Var(&inputcommands, "input-cmd", "Command producing the input. --input-num is required when using this input method. Overrides -w.")
141 flag.Var(&wordlists, "w", "Wordlist file path and (optional) keyword separated by colon. eg. '/path/to/wordlist:KEYWORD'")
142 flag.Var(&encoders, "enc", "Encoders for keywords, eg. 'FUZZ:urlencode b64encode'")
143 flag.Usage = Usage
144 flag.Parse()
145
146 opts.General.AutoCalibrationStrings = autocalibrationstrings
147 if len(autocalibrationstrategies) > 0 {
148 opts.General.AutoCalibrationStrategies = []string{}
149 for _, strategy := range autocalibrationstrategies {
150 opts.General.AutoCalibrationStrategies = append(opts.General.AutoCalibrationStrategies, strings.Split(strategy, ",")...)
151 }
152 }
153 opts.HTTP.Cookies = cookies
154 opts.HTTP.Headers = headers
155 opts.Input.Inputcommands = inputcommands
156 opts.Input.Wordlists = wordlists
157 opts.Input.Encoders = encoders
158 return opts
159 }
160
161 func main() {
162
163 var err, optserr error
164 ctx, cancel := context.WithCancel(context.Background())
165 defer cancel()
166 // prepare the default config options from default config file
167 var opts *ffuf.ConfigOptions
168 opts, optserr = ffuf.ReadDefaultConfig()
169
170 opts = ParseFlags(opts)
171
172 // Handle searchhash functionality and exit
173 if opts.General.Searchhash != "" {
174 coptions, pos, err := ffuf.SearchHash(opts.General.Searchhash)
175 if err != nil {
176 fmt.Printf("[ERR] %s\n", err)
177 os.Exit(1)
178 }
179 if len(coptions) > 0 {
180 fmt.Printf("Request candidate(s) for hash %s\n", opts.General.Searchhash)
181 }
182 for _, copt := range coptions {
183 conf, err := ffuf.ConfigFromOptions(&copt.ConfigOptions, ctx, cancel)
184 if err != nil {
185 continue
186 }
187 ok, reason := ffuf.HistoryReplayable(conf)
188 if ok {
189 printSearchResults(conf, pos, copt.Time, opts.General.Searchhash)
190 } else {
191 fmt.Printf("[ERR] Hash cannot be mapped back because %s\n", reason)
192 }
193
194 }
195 if err != nil {
196 fmt.Printf("[ERR] %s\n", err)
197 }
198 os.Exit(0)
199 }
200
201 if opts.General.ShowVersion {
202 fmt.Printf("ffuf version: %s\n", ffuf.Version())
203 os.Exit(0)
204 }
205 if len(opts.Output.DebugLog) != 0 {
206 f, err := os.OpenFile(opts.Output.DebugLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
207 if err != nil {
208 fmt.Fprintf(os.Stderr, "Disabling logging, encountered error(s): %s\n", err)
209 log.SetOutput(io.Discard)
210 } else {
211 log.SetOutput(f)
212 defer f.Close()
213 }
214 } else {
215 log.SetOutput(io.Discard)
216 }
217 if optserr != nil {
218 log.Printf("Error while opening default config file: %s", optserr)
219 }
220
221 if opts.General.ConfigFile != "" {
222 opts, err = ffuf.ReadConfig(opts.General.ConfigFile)
223 if err != nil {
224 fmt.Fprintf(os.Stderr, "Encoutered error(s): %s\n", err)
225 Usage()
226 fmt.Fprintf(os.Stderr, "Encoutered error(s): %s\n", err)
227 os.Exit(1)
228 }
229 // Reset the flag package state
230 flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
231 // Re-parse the cli options
232 opts = ParseFlags(opts)
233 }
234
235 // Set up Config struct
236 conf, err := ffuf.ConfigFromOptions(opts, ctx, cancel)
237 if err != nil {
238 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
239 Usage()
240 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
241 os.Exit(1)
242 }
243
244 job, err := prepareJob(conf)
245
246 if job.AuditLogger != nil {
247 defer job.AuditLogger.Close()
248 }
249 if err != nil {
250 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
251 Usage()
252 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
253 os.Exit(1)
254 }
255 if err := SetupFilters(opts, conf); err != nil {
256 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
257 Usage()
258 fmt.Fprintf(os.Stderr, "Encountered error(s): %s\n", err)
259 os.Exit(1)
260 }
261
262 if !conf.Noninteractive {
263 go func() {
264 err := interactive.Handle(job)
265 if err != nil {
266 log.Printf("Error while trying to initialize interactive session: %s", err)
267 }
268 }()
269 }
270
271 // Job handles waiting for goroutines to complete itself
272 job.Start()
273 }
274
275 func prepareJob(conf *ffuf.Config) (*ffuf.Job, error) {
276 var err error
277 job := ffuf.NewJob(conf)
278 var errs ffuf.Multierror
279 job.Input, errs = input.NewInputProvider(conf)
280 // TODO: implement error handling for runnerprovider and outputprovider
281 // We only have http runner right now
282 job.Runner = runner.NewRunnerByName("http", conf, false)
283 if len(conf.ReplayProxyURL) > 0 {
284 job.ReplayRunner = runner.NewRunnerByName("http", conf, true)
285 }
286 // We only have stdout outputprovider right now
287 job.Output = output.NewOutputProviderByName("stdout", conf)
288
289 // Initialize the audit logger if specified
290 if len(conf.AuditLog) > 0 {
291 job.AuditLogger, err = output.NewAuditLogger(conf.AuditLog)
292 if err != nil {
293 errs.Add(err)
294 } else {
295 err = job.AuditLogger.Write(conf)
296 if err != nil {
297 errs.Add(err)
298 }
299 }
300 }
301
302 // Initialize scraper
303 newscraper, scraper_err := scraper.FromDir(ffuf.SCRAPERDIR, conf.Scrapers)
304 if scraper_err.ErrorOrNil() != nil {
305 errs.Add(scraper_err.ErrorOrNil())
306 }
307 job.Scraper = newscraper
308 if conf.ScraperFile != "" {
309 err = job.Scraper.AppendFromFile(conf.ScraperFile)
310 if err != nil {
311 errs.Add(err)
312 }
313 }
314 return job, errs.ErrorOrNil()
315 }
316
317 func SetupFilters(parseOpts *ffuf.ConfigOptions, conf *ffuf.Config) error {
318 errs := ffuf.NewMultierror()
319 conf.MatcherManager = filter.NewMatcherManager()
320 // If any other matcher is set, ignore -mc default value
321 matcherSet := false
322 statusSet := false
323 warningIgnoreBody := false
324 flag.Visit(func(f *flag.Flag) {
325 if f.Name == "mc" {
326 statusSet = true
327 }
328 if f.Name == "ms" {
329 matcherSet = true
330 warningIgnoreBody = true
331 }
332 if f.Name == "ml" {
333 matcherSet = true
334 warningIgnoreBody = true
335 }
336 if f.Name == "mr" {
337 matcherSet = true
338 }
339 if f.Name == "mt" {
340 matcherSet = true
341 }
342 if f.Name == "mw" {
343 matcherSet = true
344 warningIgnoreBody = true
345 }
346 })
347 // Only set default matchers if no
348 if statusSet || !matcherSet {
349 if err := conf.MatcherManager.AddMatcher("status", parseOpts.Matcher.Status); err != nil {
350 errs.Add(err)
351 }
352 }
353
354 if parseOpts.Filter.Status != "" {
355 if err := conf.MatcherManager.AddFilter("status", parseOpts.Filter.Status, false); err != nil {
356 errs.Add(err)
357 }
358 }
359 if parseOpts.Filter.Size != "" {
360 warningIgnoreBody = true
361 if err := conf.MatcherManager.AddFilter("size", parseOpts.Filter.Size, false); err != nil {
362 errs.Add(err)
363 }
364 }
365 if parseOpts.Filter.Regexp != "" {
366 if err := conf.MatcherManager.AddFilter("regexp", parseOpts.Filter.Regexp, false); err != nil {
367 errs.Add(err)
368 }
369 }
370 if parseOpts.Filter.Words != "" {
371 warningIgnoreBody = true
372 if err := conf.MatcherManager.AddFilter("word", parseOpts.Filter.Words, false); err != nil {
373 errs.Add(err)
374 }
375 }
376 if parseOpts.Filter.Lines != "" {
377 warningIgnoreBody = true
378 if err := conf.MatcherManager.AddFilter("line", parseOpts.Filter.Lines, false); err != nil {
379 errs.Add(err)
380 }
381 }
382 if parseOpts.Filter.Time != "" {
383 if err := conf.MatcherManager.AddFilter("time", parseOpts.Filter.Time, false); err != nil {
384 errs.Add(err)
385 }
386 }
387 if parseOpts.Matcher.Size != "" {
388 if err := conf.MatcherManager.AddMatcher("size", parseOpts.Matcher.Size); err != nil {
389 errs.Add(err)
390 }
391 }
392 if parseOpts.Matcher.Regexp != "" {
393 if err := conf.MatcherManager.AddMatcher("regexp", parseOpts.Matcher.Regexp); err != nil {
394 errs.Add(err)
395 }
396 }
397 if parseOpts.Matcher.Words != "" {
398 if err := conf.MatcherManager.AddMatcher("word", parseOpts.Matcher.Words); err != nil {
399 errs.Add(err)
400 }
401 }
402 if parseOpts.Matcher.Lines != "" {
403 if err := conf.MatcherManager.AddMatcher("line", parseOpts.Matcher.Lines); err != nil {
404 errs.Add(err)
405 }
406 }
407 if parseOpts.Matcher.Time != "" {
408 if err := conf.MatcherManager.AddMatcher("time", parseOpts.Matcher.Time); err != nil {
409 errs.Add(err)
410 }
411 }
412 if conf.IgnoreBody && warningIgnoreBody {
413 fmt.Printf("*** Warning: possible undesired combination of -ignore-body and the response options: fl,fs,fw,ml,ms and mw.\n")
414 }
415 return errs.ErrorOrNil()
416 }
417
418 func printSearchResults(conf *ffuf.Config, pos int, exectime time.Time, hash string) {
419 inp, err := input.NewInputProvider(conf)
420 if err.ErrorOrNil() != nil {
421 fmt.Printf("-------------------------------------------\n")
422 fmt.Println("Encountered error that prevents reproduction of the request:")
423 fmt.Println(err.ErrorOrNil())
424 return
425 }
426 inp.SetPosition(pos)
427 inputdata := inp.Value()
428 inputdata["FFUFHASH"] = []byte(hash)
429 basereq := ffuf.BaseRequest(conf)
430 dummyrunner := runner.NewRunnerByName("simple", conf, false)
431 ffufreq, _ := dummyrunner.Prepare(inputdata, &basereq)
432 rawreq, _ := dummyrunner.Dump(&ffufreq)
433 fmt.Printf("-------------------------------------------\n")
434 fmt.Printf("ffuf job started at: %s\n\n", exectime.Format(time.RFC3339))
435 fmt.Printf("%s\n", string(rawreq))
436 }