-
Notifications
You must be signed in to change notification settings - Fork 59
/
mutator.go
326 lines (304 loc) · 9.32 KB
/
mutator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package alterx
import (
"bytes"
"context"
"fmt"
"io"
"regexp"
"strings"
"time"
"github.com/projectdiscovery/fasttemplate"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/utils/dedupe"
errorutil "github.com/projectdiscovery/utils/errors"
sliceutil "github.com/projectdiscovery/utils/slice"
)
var (
extractNumbers = regexp.MustCompile(`[0-9]+`)
extractWords = regexp.MustCompile(`[a-zA-Z0-9]+`)
extractWordsOnly = regexp.MustCompile(`[a-zA-Z]{3,}`)
DedupeResults = true // Dedupe all results (default: true)
)
// Mutator Options
type Options struct {
// list of Domains to use as base
Domains []string
// list of words to use while creating permutations
// if empty DefaultWordList is used
Payloads map[string][]string
// list of pattersn to use while creating permutations
// if empty DefaultPatterns are used
Patterns []string
// Limits output results (0 = no limit)
Limit int
// Enrich when true alterx extra possible words from input
// and adds them to default payloads word,number
Enrich bool
// MaxSize limits output data size
MaxSize int
}
// Mutator
type Mutator struct {
Options *Options
payloadCount int
Inputs []*Input // all processed inputs
timeTaken time.Duration
// internal or unexported variables
maxkeyLenInBytes int
}
// New creates and returns new mutator instance from options
func New(opts *Options) (*Mutator, error) {
if len(opts.Domains) == 0 {
return nil, fmt.Errorf("no input provided to calculate permutations")
}
if len(opts.Payloads) == 0 {
opts.Payloads = map[string][]string{}
if len(DefaultConfig.Payloads) == 0 {
return nil, fmt.Errorf("something went wrong, `DefaultWordList` and input wordlist are empty")
}
opts.Payloads = DefaultConfig.Payloads
}
if len(opts.Patterns) == 0 {
if len(DefaultConfig.Patterns) == 0 {
return nil, fmt.Errorf("something went wrong,`DefaultPatters` and input patterns are empty")
}
opts.Patterns = DefaultConfig.Patterns
}
// purge duplicates if any
for k, v := range opts.Payloads {
dedupe := sliceutil.Dedupe(v)
if len(v) != len(dedupe) {
gologger.Warning().Msgf("%v duplicate payloads found in %v. purging them..", len(v)-len(dedupe), k)
opts.Payloads[k] = dedupe
}
}
m := &Mutator{
Options: opts,
}
if err := m.validatePatterns(); err != nil {
return nil, err
}
if err := m.prepareInputs(); err != nil {
return nil, err
}
if opts.Enrich {
m.enrichPayloads()
}
return m, nil
}
// Execute calculates all permutations using input wordlist and patterns
// and writes them to a string channel
func (m *Mutator) Execute(ctx context.Context) <-chan string {
var maxBytes int
if DedupeResults {
count := m.EstimateCount()
maxBytes = count * m.maxkeyLenInBytes
}
results := make(chan string, len(m.Options.Patterns))
go func() {
now := time.Now()
for _, v := range m.Inputs {
varMap := getSampleMap(v.GetMap(), m.Options.Payloads)
for _, pattern := range m.Options.Patterns {
if err := checkMissing(pattern, varMap); err == nil {
statement := Replace(pattern, v.GetMap())
select {
case <-ctx.Done():
return
default:
m.clusterBomb(statement, results)
}
} else {
gologger.Warning().Msgf("%v : failed to evaluate pattern %v. skipping", err.Error(), pattern)
}
}
}
m.timeTaken = time.Since(now)
close(results)
}()
if DedupeResults {
// drain results
d := dedupe.NewDedupe(results, maxBytes)
d.Drain()
return d.GetResults()
}
return results
}
// ExecuteWithWriter executes Mutator and writes results directly to type that implements io.Writer interface
func (m *Mutator) ExecuteWithWriter(Writer io.Writer) error {
if Writer == nil {
return errorutil.NewWithTag("alterx", "writer destination cannot be nil")
}
resChan := m.Execute(context.TODO())
m.payloadCount = 0
maxFileSize := m.Options.MaxSize
for {
value, ok := <-resChan
if !ok {
gologger.Info().Msgf("Generated %v permutations in %v", m.payloadCount, m.Time())
return nil
}
if m.Options.Limit > 0 && m.payloadCount == m.Options.Limit {
// we can't early exit, due to abstraction we have to conclude the elaboration to drain all dedupers
continue
}
if maxFileSize <= 0 {
// drain all dedupers when max-file size reached
continue
}
if strings.HasPrefix(value, "-") {
continue
}
outputData := []byte(value + "\n")
if len(outputData) > maxFileSize {
maxFileSize = 0
continue
}
n, err := Writer.Write(outputData)
if err != nil {
return err
}
// update maxFileSize limit after each write
maxFileSize -= n
m.payloadCount++
}
}
// EstimateCount estimates number of payloads that will be created
// without actually executing/creating permutations
func (m *Mutator) EstimateCount() int {
counter := 0
for _, v := range m.Inputs {
varMap := getSampleMap(v.GetMap(), m.Options.Payloads)
for _, pattern := range m.Options.Patterns {
if err := checkMissing(pattern, varMap); err == nil {
// if say patterns is {{sub}}.{{sub1}}-{{word}}.{{root}}
// and input domain is api.scanme.sh its clear that {{sub1}} here will be empty/missing
// in such cases `alterx` silently skips that pattern for that specific input
// this way user can have a long list of patterns but they are only used if all required data is given (much like self-contained templates)
statement := Replace(pattern, v.GetMap())
bin := unsafeToBytes(statement)
if m.maxkeyLenInBytes < len(bin) {
m.maxkeyLenInBytes = len(bin)
}
varsUsed := getAllVars(statement)
if len(varsUsed) == 0 {
counter += 1
} else {
tmpCounter := 1
for _, word := range varsUsed {
tmpCounter *= len(m.Options.Payloads[word])
}
counter += tmpCounter
}
}
}
}
return counter
}
// DryRun executes payloads without storing and returns number of payloads created
// this value is also stored in variable and can be accessed via getter `PayloadCount`
func (m *Mutator) DryRun() int {
m.payloadCount = 0
err := m.ExecuteWithWriter(io.Discard)
if err != nil {
gologger.Error().Msgf("alterx: got %v", err)
}
return m.payloadCount
}
// clusterBomb calculates all payloads of clusterbomb attack and sends them to result channel
func (m *Mutator) clusterBomb(template string, results chan string) {
// Early Exit: this is what saves clusterBomb from stackoverflows and reduces
// n*len(n) iterations and n recursions
varsUsed := getAllVars(template)
if len(varsUsed) == 0 {
// clusterBomb is not required
// just send existing template as result and exit
results <- template
return
}
payloadSet := map[string][]string{}
// instead of sending all payloads only send payloads that are used
// in template/statement
for _, v := range varsUsed {
payloadSet[v] = []string{}
for _, word := range m.Options.Payloads[v] {
if !strings.Contains(template, word) {
// skip all words that are already present in template/sub , it is highly unlikely
// we will ever find api-api.example.com
payloadSet[v] = append(payloadSet[v], word)
}
}
}
payloads := NewIndexMap(payloadSet)
// in clusterBomb attack no of payloads generated are
// len(first_set)*len(second_set)*len(third_set)....
callbackFunc := func(varMap map[string]interface{}) {
results <- Replace(template, varMap)
}
ClusterBomb(payloads, callbackFunc, []string{})
}
// prepares input and patterns and calculates estimations
func (m *Mutator) prepareInputs() error {
var errors []string
// prepare input
var allInputs []*Input
for _, v := range m.Options.Domains {
i, err := NewInput(v)
if err != nil {
errors = append(errors, err.Error())
continue
}
allInputs = append(allInputs, i)
}
m.Inputs = allInputs
if len(errors) > 0 {
gologger.Warning().Msgf("errors found when preparing inputs got: %v : skipping errored inputs", strings.Join(errors, " : "))
}
return nil
}
// validates all patterns by compiling them
func (m *Mutator) validatePatterns() error {
for _, v := range m.Options.Patterns {
// check if all placeholders are correctly used and are valid
if _, err := fasttemplate.NewTemplate(v, ParenthesisOpen, ParenthesisClose); err != nil {
return err
}
}
return nil
}
// enrichPayloads extract possible words and adds them to default wordlist
func (m *Mutator) enrichPayloads() {
var temp bytes.Buffer
for _, v := range m.Inputs {
temp.WriteString(v.Sub + " ")
if len(v.MultiLevel) > 0 {
temp.WriteString(strings.Join(v.MultiLevel, " "))
}
}
numbers := extractNumbers.FindAllString(temp.String(), -1)
extraWords := extractWords.FindAllString(temp.String(), -1)
extraWordsOnly := extractWordsOnly.FindAllString(temp.String(), -1)
if len(extraWordsOnly) > 0 {
extraWords = append(extraWords, extraWordsOnly...)
extraWords = sliceutil.Dedupe(extraWords)
}
if len(m.Options.Payloads["word"]) > 0 {
extraWords = append(extraWords, m.Options.Payloads["word"]...)
m.Options.Payloads["word"] = sliceutil.Dedupe(extraWords)
}
if len(m.Options.Payloads["number"]) > 0 {
numbers = append(numbers, m.Options.Payloads["number"]...)
m.Options.Payloads["number"] = sliceutil.Dedupe(numbers)
}
}
// PayloadCount returns total estimated payloads count
func (m *Mutator) PayloadCount() int {
if m.payloadCount == 0 {
return m.EstimateCount()
}
return m.payloadCount
}
// Time returns time taken to create permutations in seconds
func (m *Mutator) Time() string {
return fmt.Sprintf("%.4fs", m.timeTaken.Seconds())
}