-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
main.go
227 lines (192 loc) · 6.31 KB
/
main.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
package main
import (
"fmt"
"os"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/paulbellamy/ratecounter"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
"github.com/trufflesecurity/trufflehog/v3/pkg/decoders"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/engine"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
"github.com/trufflesecurity/trufflehog/v3/pkg/sources"
"github.com/trufflesecurity/trufflehog/v3/pkg/sources/git"
)
var (
// CLI flags and commands
app = kingpin.New("Snifftest", "Test secret detectors against data sets.")
showDetectorsCmd = app.Command("show-detectors", "Shows the available detectors.")
scanCmd = app.Command("scan", "Scans data.")
scanCmdDetector = scanCmd.Flag("detector", "Detector to scan with. 'all', or a specific name.").Default("all").String()
scanCmdExclude = scanCmd.Flag("exclude", "Detector(s) to exclude").Strings()
scanCmdRepo = scanCmd.Flag("repo", "URI to .git repo.").Required().String()
scanThreshold = scanCmd.Flag("fail-threshold", "Result threshold that causes failure for a single scanner.").Int()
scanPrintRes = scanCmd.Flag("print", "Print results.").Bool()
scanPrintChunkRes = scanCmd.Flag("print-chunk", "Print chunks that have results.").Bool()
scanVerify = scanCmd.Flag("verify", "Verify found secrets.").Bool()
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Hour*2)
var cancelOnce sync.Once
defer cancelOnce.Do(cancel)
cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
switch cmd {
case scanCmd.FullCommand():
chunksChan := make(chan *sources.Chunk, 10000)
var wgChunkers sync.WaitGroup
sem := semaphore.NewWeighted(int64(runtime.NumCPU()))
selectedScanners := map[string]detectors.Detector{}
allScanners := getAllScanners()
decoders := decoders.DefaultDecoders()
input := strings.ToLower(*scanCmdDetector)
if input == "all" {
selectedScanners = allScanners
} else {
_, ok := allScanners[input]
if !ok {
log.Fatal("could not find scanner by that name")
}
selectedScanners[input] = allScanners[input]
}
if len(selectedScanners) == 0 {
log.Fatal("no detectors selected")
}
for _, excluded := range *scanCmdExclude {
delete(selectedScanners, excluded)
}
log.Infof("loaded %d secret detectors", len(selectedScanners)+3)
var wgScanners sync.WaitGroup
var chunkCounter uint64
go func() {
counter := ratecounter.NewRateCounter(60 * time.Second)
var prev uint64
for {
time.Sleep(60 * time.Second)
counter.Incr(int64(chunkCounter - prev))
prev = chunkCounter
log.Infof("chunk scan rate: %d/sec", counter.Rate()/60)
}
}()
resCounter := make(map[string]*uint64)
failed := false
for i := 0; i < runtime.NumCPU(); i++ {
wgScanners.Add(1)
go func() {
defer wgScanners.Done()
for chunk := range chunksChan {
for name, scanner := range selectedScanners {
for _, dec := range decoders {
decoded := dec.FromChunk(&sources.Chunk{Data: chunk.Data})
if decoded != nil {
foundKeyword := false
for _, kw := range scanner.Keywords() {
if strings.Contains(strings.ToLower(string(decoded.Data)), strings.ToLower(kw)) {
foundKeyword = true
}
}
if !foundKeyword {
continue
}
res, err := scanner.FromData(ctx, *scanVerify, decoded.Data)
if err != nil {
log.Fatal(err)
}
if len(res) > 0 {
if resCounter[name] == nil {
zero := uint64(0)
resCounter[name] = &zero
}
atomic.AddUint64(resCounter[name], uint64(len(res)))
if *scanThreshold != 0 && int(*resCounter[name]) > *scanThreshold {
log.WithField("scanner", name).Errorf("exceeded result threshold of %d", *scanThreshold)
failed = true
os.Exit(1)
}
if *scanPrintRes {
for _, r := range res {
logger := log.WithField("secret", name).WithField("meta", chunk.SourceMetadata).WithField("result", string(r.Raw))
if *scanPrintChunkRes {
logger = logger.WithField("chunk", string(decoded.Data))
}
logger.Info("result")
}
}
}
}
}
}
atomic.AddUint64(&chunkCounter, uint64(1))
}
}()
}
for _, repo := range strings.Split(*scanCmdRepo, ",") {
sem.Acquire(ctx, 1)
wgChunkers.Add(1)
go func(r string) {
defer sem.Release(1)
defer wgChunkers.Done()
log.Infof("cloning %s", r)
path, repo, err := git.CloneRepoUsingUnauthenticated(ctx, r)
if err != nil {
log.Fatal(err)
}
log.Infof("cloned %s", r)
s := git.NewGit(sourcespb.SourceType_SOURCE_TYPE_GIT, 0, 0, "snifftest", false, runtime.NumCPU(),
func(file, email, commit, timestamp, repository string, line int64) *source_metadatapb.MetaData {
return &source_metadatapb.MetaData{
Data: &source_metadatapb.MetaData_Git{
Git: &source_metadatapb.Git{
Commit: commit,
File: file,
Email: email,
Repository: repository,
Timestamp: timestamp,
},
},
}
})
log.Infof("scanning %s", r)
err = s.ScanRepo(ctx, repo, path, git.NewScanOptions(), chunksChan)
if err != nil {
log.Fatal(err)
}
log.Infof("scanned %s", r)
defer os.RemoveAll(path)
}(repo)
}
go func() {
wgChunkers.Wait()
close(chunksChan)
}()
wgScanners.Wait()
log.WithField("chunks", chunkCounter).Info("completed")
for scanner, resultsCount := range resCounter {
log.WithField("results", *resultsCount).Info(scanner)
}
if failed {
os.Exit(1)
}
case showDetectorsCmd.FullCommand():
for s := range getAllScanners() {
fmt.Println(s)
}
}
}
func getAllScanners() map[string]detectors.Detector {
allScanners := map[string]detectors.Detector{}
for _, s := range engine.DefaultDetectors() {
secretType := reflect.Indirect(reflect.ValueOf(s)).Type().PkgPath()
path := strings.Split(secretType, "/")[len(strings.Split(secretType, "/"))-1]
allScanners[path] = s
}
return allScanners
}