spray/internal/runner.go

423 lines
9.6 KiB
Go
Raw Normal View History

2022-09-08 15:57:17 +08:00
package internal
import (
2022-09-15 19:27:07 +08:00
"context"
"github.com/chainreactors/files"
2022-09-08 15:57:17 +08:00
"github.com/chainreactors/logs"
2024-02-08 15:26:01 +08:00
"github.com/chainreactors/spray/internal/ihttp"
2024-02-10 18:23:50 +08:00
"github.com/chainreactors/spray/internal/pool"
"github.com/chainreactors/spray/pkg"
"github.com/chainreactors/words"
2022-12-06 21:45:14 +08:00
"github.com/chainreactors/words/rule"
2024-06-06 18:11:45 +08:00
"github.com/expr-lang/expr/vm"
"github.com/panjf2000/ants/v2"
2024-03-07 00:24:30 +08:00
"github.com/vbauerster/mpb/v8"
"github.com/vbauerster/mpb/v8/decor"
2022-09-08 15:57:17 +08:00
"sync"
)
var (
2024-02-20 18:25:43 +08:00
MAX = 2147483647
)
2022-09-08 15:57:17 +08:00
type Runner struct {
*Option
taskCh chan *Task
poolwg *sync.WaitGroup
outwg *sync.WaitGroup
outputCh chan *pkg.Baseline
fuzzyCh chan *pkg.Baseline
bar *mpb.Bar
2024-08-20 16:42:32 +08:00
bruteMod bool
2024-07-14 04:08:50 +08:00
IsCheck bool
Pools *ants.PoolWithFunc
PoolName map[string]bool
2024-07-22 16:27:07 +08:00
Tasks *TaskGenerator
Rules *rule.Program
AppendRules *rule.Program
Headers map[string]string
FilterExpr *vm.Program
MatchExpr *vm.Program
RecursiveExpr *vm.Program
OutputFile *files.File
2024-08-26 00:04:44 +08:00
//FuzzyFile *files.File
DumpFile *files.File
StatFile *files.File
Progress *mpb.Progress
Fns []func(string) []string
Count int // tasks total number
Wordlist []string
AppendWords []string
RecuDepth int
ClientType int
Probes []string
Total int // wordlist total number
Color bool
Jsonify bool
2022-09-08 15:57:17 +08:00
}
2024-02-10 18:23:50 +08:00
func (r *Runner) PrepareConfig() *pool.Config {
config := &pool.Config{
Thread: r.Threads,
Timeout: r.Timeout,
RateLimit: r.RateLimit,
Headers: r.Headers,
Method: r.Method,
Mod: pool.ModMap[r.Mod],
OutputCh: r.outputCh,
FuzzyCh: r.fuzzyCh,
2024-07-14 04:08:50 +08:00
Outwg: r.outwg,
Fuzzy: r.Fuzzy,
CheckPeriod: r.CheckPeriod,
ErrPeriod: int32(r.ErrPeriod),
BreakThreshold: int32(r.BreakThreshold),
MatchExpr: r.MatchExpr,
FilterExpr: r.FilterExpr,
RecuExpr: r.RecursiveExpr,
AppendRule: r.AppendRules, // 对有效目录追加规则, 根据rule生成
AppendWords: r.AppendWords, // 对有效目录追加字典
//IgnoreWaf: r.IgnoreWaf,
2024-08-26 01:20:03 +08:00
Crawl: r.CrawlPlugin,
Scope: r.Scope,
Active: r.Finger,
2024-08-26 01:20:03 +08:00
Bak: r.BakPlugin,
Common: r.CommonPlugin,
RetryLimit: r.RetryCount,
2023-03-24 14:20:31 +08:00
ClientType: r.ClientType,
RandomUserAgent: r.RandomUserAgent,
Random: r.Random,
Index: r.Index,
2024-02-07 01:29:05 +08:00
ProxyAddr: r.Proxy,
}
2023-01-10 00:57:55 +08:00
if config.ClientType == ihttp.Auto {
2024-02-10 18:23:50 +08:00
if config.Mod == pool.PathSpray {
2023-01-10 00:57:55 +08:00
config.ClientType = ihttp.FAST
2024-02-10 18:23:50 +08:00
} else if config.Mod == pool.HostSpray {
2023-01-10 00:57:55 +08:00
config.ClientType = ihttp.STANDARD
}
}
return config
}
func (r *Runner) AppendFunction(fn func(string) []string) {
r.Fns = append(r.Fns, fn)
}
2022-11-10 16:52:00 +08:00
func (r *Runner) Prepare(ctx context.Context) error {
2024-08-20 16:42:32 +08:00
if r.bruteMod {
r.IsCheck = false
}
2024-08-06 03:58:30 +08:00
r.OutputHandler()
2022-09-08 15:57:17 +08:00
var err error
2024-07-14 04:08:50 +08:00
if r.IsCheck {
2022-12-02 19:59:15 +08:00
// 仅check, 类似httpx
r.Pools, err = ants.NewPoolWithFunc(1, func(i interface{}) {
config := r.PrepareConfig()
2024-07-14 04:08:50 +08:00
checkPool, err := pool.NewCheckPool(ctx, config)
if err != nil {
logs.Log.Error(err.Error())
2024-07-14 04:08:50 +08:00
checkPool.Cancel()
r.poolwg.Done()
return
}
ch := make(chan string)
go func() {
2024-07-22 16:27:07 +08:00
for t := range r.Tasks.tasks {
ch <- t.baseUrl
}
close(ch)
}()
2024-07-14 04:08:50 +08:00
checkPool.Worder = words.NewWorderWithChan(ch)
checkPool.Worder.Fns = r.Fns
checkPool.Bar = pkg.NewBar("check", r.Count-r.Offset, checkPool.Statistor, r.Progress)
checkPool.Run(ctx, r.Offset, r.Count)
r.poolwg.Done()
})
2024-08-06 03:58:30 +08:00
r.RunWithCheck(ctx)
} else {
// 完整探测模式
go func() {
2024-07-22 16:27:07 +08:00
for t := range r.Tasks.tasks {
2022-12-02 19:59:15 +08:00
r.taskCh <- t
}
2022-12-02 19:59:15 +08:00
close(r.taskCh)
}()
2023-04-06 20:41:35 +08:00
if r.Count > 0 {
2024-07-24 04:21:43 +08:00
r.newBar(r.Count)
}
r.Pools, err = ants.NewPoolWithFunc(r.PoolSize, func(i interface{}) {
2022-12-02 19:59:15 +08:00
t := i.(*Task)
if t.origin != nil && t.origin.End == t.origin.Total {
2024-07-14 04:28:08 +08:00
r.saveStat(t.origin.Json())
r.Done()
return
}
config := r.PrepareConfig()
2022-12-02 19:59:15 +08:00
config.BaseURL = t.baseUrl
2024-07-14 04:08:50 +08:00
brutePool, err := pool.NewBrutePool(ctx, config)
if err != nil {
logs.Log.Error(err.Error())
2024-07-14 04:08:50 +08:00
brutePool.Cancel()
r.Done()
return
}
if t.origin != nil && len(r.Wordlist) == 0 {
// 如果是从断点续传中恢复的任务, 则自动设置word,dict与rule, 不过优先级低于命令行参数
2024-07-14 04:08:50 +08:00
brutePool.Statistor = pkg.NewStatistorFromStat(t.origin.Statistor)
brutePool.Worder, err = t.origin.InitWorder(r.Fns)
if err != nil {
logs.Log.Error(err.Error())
r.Done()
return
}
2024-07-14 04:08:50 +08:00
brutePool.Statistor.Total = t.origin.sum
} else {
2024-07-14 04:08:50 +08:00
brutePool.Statistor = pkg.NewStatistor(t.baseUrl)
brutePool.Worder = words.NewWorder(r.Wordlist)
brutePool.Worder.Fns = r.Fns
brutePool.Worder.Rules = r.Rules.Expressions
}
var limit int
2024-07-14 04:08:50 +08:00
if brutePool.Statistor.Total > r.Limit && r.Limit != 0 {
limit = r.Limit
} else {
2024-07-14 04:08:50 +08:00
limit = brutePool.Statistor.Total
}
2024-07-14 04:08:50 +08:00
brutePool.Bar = pkg.NewBar(config.BaseURL, limit-brutePool.Statistor.Offset, brutePool.Statistor, r.Progress)
logs.Log.Importantf("[pool] task: %s, total %d words, %d threads, proxy: %s", brutePool.BaseURL, limit-brutePool.Statistor.Offset, brutePool.Thread, brutePool.ProxyAddr)
err = brutePool.Init()
if err != nil {
2024-07-14 04:08:50 +08:00
brutePool.Statistor.Error = err.Error()
if !r.Force {
// 如果没开启force, init失败将会关闭pool
2024-07-14 04:08:50 +08:00
brutePool.Close()
r.PrintStat(brutePool)
r.Done()
return
}
}
2022-11-10 16:52:00 +08:00
2024-08-12 15:12:43 +08:00
brutePool.Run(ctx, brutePool.Statistor.Offset, limit)
2024-07-14 04:08:50 +08:00
if brutePool.IsFailed && len(brutePool.FailedBaselines) > 0 {
// 如果因为错误积累退出, end将指向第一个错误发生时, 防止resume时跳过大量目标
2024-07-14 04:08:50 +08:00
brutePool.Statistor.End = brutePool.FailedBaselines[0].Number
}
2024-07-14 04:08:50 +08:00
r.PrintStat(brutePool)
r.Done()
})
2024-08-06 03:58:30 +08:00
r.Run(ctx)
}
if err != nil {
return err
}
2024-08-06 03:58:30 +08:00
2022-09-08 15:57:17 +08:00
return nil
}
2022-11-10 16:52:00 +08:00
func (r *Runner) Run(ctx context.Context) {
Loop:
for {
select {
case <-ctx.Done():
if len(r.taskCh) > 0 {
for t := range r.taskCh {
stat := pkg.NewStatistor(t.baseUrl)
2024-07-14 04:28:08 +08:00
r.saveStat(stat.Json())
}
}
2024-07-14 04:16:12 +08:00
if r.StatFile != nil {
logs.Log.Importantf("already save all stat to %s", r.StatFile.Filename)
}
2022-11-10 16:52:00 +08:00
break Loop
2022-12-02 19:59:15 +08:00
case t, ok := <-r.taskCh:
2022-11-10 16:52:00 +08:00
if !ok {
break Loop
}
2022-12-11 00:24:28 +08:00
r.AddPool(t)
2022-11-10 16:52:00 +08:00
}
2022-09-08 15:57:17 +08:00
}
2022-11-10 16:52:00 +08:00
r.poolwg.Wait()
2024-02-10 18:23:50 +08:00
r.outwg.Wait()
2022-09-08 15:57:17 +08:00
}
func (r *Runner) RunWithCheck(ctx context.Context) {
stopCh := make(chan struct{})
r.poolwg.Add(1)
err := r.Pools.Invoke(struct{}{})
if err != nil {
return
}
go func() {
r.poolwg.Wait()
stopCh <- struct{}{}
}()
Loop:
for {
select {
case <-ctx.Done():
logs.Log.Error("cancel with deadline")
break Loop
case <-stopCh:
break Loop
}
}
2024-07-14 04:08:50 +08:00
r.outwg.Wait()
}
func (r *Runner) AddRecursive(bl *pkg.Baseline) {
// 递归新任务
task := &Task{
baseUrl: bl.UrlString,
depth: bl.RecuDepth + 1,
origin: NewOrigin(pkg.NewStatistor(bl.UrlString)),
}
2024-07-14 04:08:50 +08:00
r.AddPool(task)
}
func (r *Runner) AddPool(task *Task) {
// 递归新任务
if _, ok := r.PoolName[task.baseUrl]; ok {
logs.Log.Importantf("already added pool, skip %s", task.baseUrl)
return
}
task.depth++
r.poolwg.Add(1)
r.Pools.Invoke(task)
}
2024-07-24 04:21:43 +08:00
func (r *Runner) newBar(total int) {
if r.Progress == nil {
return
}
prompt := "total progressive:"
r.bar = r.Progress.AddBar(int64(total),
mpb.BarFillerClearOnComplete(), // 可选:当进度条完成时清除
mpb.PrependDecorators(
// 显示自定义的信息,比如下载速度和进度
decor.Name(prompt, decor.WC{W: len(prompt) + 1, C: decor.DindentRight}), // 这里调整了装饰器的参数
decor.OnComplete( // 当进度完成时显示的文本
decor.Counters(0, "% d/% d"), " done!",
),
),
mpb.AppendDecorators(
// 显示经过的时间
decor.Elapsed(decor.ET_STYLE_GO, decor.WC{W: 4}),
),
)
}
func (r *Runner) Done() {
if r.bar != nil {
r.bar.Increment()
}
r.poolwg.Done()
}
2024-02-10 18:23:50 +08:00
func (r *Runner) PrintStat(pool *pool.BrutePool) {
if r.Color {
logs.Log.Important(pool.Statistor.ColorString())
if pool.Statistor.Error == "" {
logs.Log.Log(pkg.LogVerbose, pool.Statistor.ColorCountString())
logs.Log.Log(pkg.LogVerbose, pool.Statistor.ColorSourceString())
}
} else {
logs.Log.Important(pool.Statistor.String())
if pool.Statistor.Error == "" {
logs.Log.Log(pkg.LogVerbose, pool.Statistor.CountString())
logs.Log.Log(pkg.LogVerbose, pool.Statistor.SourceString())
}
}
2024-07-14 04:28:08 +08:00
r.saveStat(pool.Statistor.Json())
}
func (r *Runner) saveStat(content string) {
if r.StatFile != nil {
2024-07-14 04:28:08 +08:00
r.StatFile.SafeWrite(content)
r.StatFile.SafeSync()
}
}
2024-08-26 00:04:44 +08:00
func (r *Runner) Output(bl *pkg.Baseline) {
var out string
if r.Option.Json {
out = bl.Jsonify()
} else if len(r.Probes) > 0 {
out = bl.Format(r.Probes)
} else if r.Color {
out = bl.ColorString()
} else {
2024-08-26 00:04:44 +08:00
out = bl.String()
}
2024-08-26 00:04:44 +08:00
if bl.IsFuzzy {
logs.Log.Console("[fuzzy] " + out + "\n")
} else {
2024-08-26 00:04:44 +08:00
logs.Log.Console(out + "\n")
}
2024-08-26 00:04:44 +08:00
if r.OutputFile != nil {
r.OutputFile.SafeWrite(bl.Jsonify() + "\n")
r.OutputFile.SafeSync()
}
2024-08-26 00:04:44 +08:00
}
2024-08-26 00:04:44 +08:00
func (r *Runner) OutputHandler() {
go func() {
for {
select {
2024-02-10 18:23:50 +08:00
case bl, ok := <-r.outputCh:
if !ok {
return
}
if r.DumpFile != nil {
r.DumpFile.SafeWrite(bl.Jsonify() + "\n")
r.DumpFile.SafeSync()
}
if bl.IsValid {
2024-08-26 00:04:44 +08:00
r.Output(bl)
2022-12-11 00:24:28 +08:00
if bl.Recu {
r.AddRecursive(bl)
2022-12-11 00:24:28 +08:00
}
} else {
2024-08-26 00:04:44 +08:00
if r.Color {
logs.Log.Debug(bl.ColorString())
} else {
logs.Log.Debug(bl.String())
}
}
2024-02-10 18:23:50 +08:00
r.outwg.Done()
}
}
}()
go func() {
for {
select {
2024-02-10 18:23:50 +08:00
case bl, ok := <-r.fuzzyCh:
if !ok {
return
}
2024-08-28 12:39:00 +08:00
if r.Fuzzy {
r.Output(bl)
r.outwg.Done()
}
2022-09-08 15:57:17 +08:00
}
}
}()
2022-09-08 15:57:17 +08:00
}