-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
scan_secrets.go
229 lines (200 loc) · 6.88 KB
/
scan_secrets.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
// Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http:https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"fmt"
"io"
"os"
"path"
"github.com/harness/gitness/errors"
"github.com/harness/gitness/git/api"
"github.com/harness/gitness/git/sharedrepo"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
const (
DefaultGitleaksIgnorePath = ".gitleaksignore"
)
type ScanSecretsParams struct {
ReadParams
BaseRev string // optional to scan for secrets on diff between baseRev and Rev
Rev string
GitleaksIgnorePath string // optional, keep empty to skip using .gitleaksignore file.
}
type ScanSecretsOutput struct {
Findings []ScanSecretsFinding
}
type ScanSecretsFinding struct {
Description string `json:"description"`
StartLine int64 `json:"start_line"`
EndLine int64 `json:"end_line"`
StartColumn int64 `json:"start_column"`
EndColumn int64 `json:"end_column"`
Match string `json:"match"`
Secret string `json:"secret"`
File string `json:"file"`
SymlinkFile string `json:"symlink_file"`
Commit string `json:"commit"`
Entropy float64 `json:"entropy"`
Author string `json:"author"`
Email string `json:"email"`
Date string `json:"date"`
Message string `json:"message"`
Tags []string `json:"tags"`
RuleID string `json:"rule_id"`
// Fingerprint is the unique identifier of the secret that can be used in .gitleaksignore files.
Fingerprint string `json:"fingerprint"`
}
func (s *Service) ScanSecrets(ctx context.Context, params *ScanSecretsParams) (*ScanSecretsOutput, error) {
if err := params.Validate(); err != nil {
return nil, err
}
repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID)
var findings []ScanSecretsFinding
err := sharedrepo.Run(ctx, nil, s.tmpDir, repoPath, func(sharedRepo *sharedrepo.SharedRepo) error {
fsGitleaksIgnorePath, err := s.setupGitleaksIgnoreInSharedRepo(
ctx,
sharedRepo,
params.Rev,
params.GitleaksIgnorePath,
)
if err != nil {
return fmt.Errorf("failed to setup .gitleaksignore file in share repo: %w", err)
}
detector, err := detect.NewDetectorDefaultConfig()
if err != nil {
return fmt.Errorf("failed to create a new gitleaks detector with default config: %w", err)
}
if fsGitleaksIgnorePath != "" {
if err := detector.AddGitleaksIgnore(fsGitleaksIgnorePath); err != nil {
return fmt.Errorf("failed to load .gitleaksignore file from path %q: %w", fsGitleaksIgnorePath, err)
}
}
// TODO: fix issue where secrets in second-parent commits are not detected
logOpts := fmt.Sprintf("--no-merges --first-parent %s", params.Rev)
if params.BaseRev != "" {
logOpts = fmt.Sprintf("--no-merges --first-parent %s..%s", params.BaseRev, params.Rev)
}
gitCmd, err := sources.NewGitLogCmd(sharedRepo.Directory(), logOpts)
if err != nil {
return fmt.Errorf("failed to create a new git log cmd with diff: %w", err)
}
res, err := detector.DetectGit(gitCmd)
if err != nil {
return fmt.Errorf("failed to detect git leaks on diff: %w", err)
}
findings = mapFindings(res)
return nil
}, params.AlternateObjectDirs...)
if err != nil {
return nil, fmt.Errorf("failed to get leaks on diff: %w", err)
}
return &ScanSecretsOutput{
Findings: findings,
}, nil
}
func (s *Service) setupGitleaksIgnoreInSharedRepo(
ctx context.Context,
sharedRepo *sharedrepo.SharedRepo,
rev string,
treePath string,
) (string, error) {
if treePath == "" {
log.Ctx(ctx).Debug().Msgf("no path to .gitleaksignore file provided, run without")
return "", nil
}
// ensure file exists in tree for the provided revision, otherwise ignore and continue
node, err := s.git.GetTreeNode(ctx, sharedRepo.Directory(), rev, treePath)
if errors.IsNotFound(err) {
log.Ctx(ctx).Debug().Msgf("no .gitleaksignore file found at %q, run without", treePath)
return "", nil
}
if err != nil {
return "", fmt.Errorf("failed to get tree node for .gitleaksignore file at path %q: %w", treePath, err)
}
// if node isn't of type blob it won't contain any gitleaks related content - run without .gitleaksignore.
// NOTE: We don't do any further checks for binary files or handle symlinks.
if node.NodeType != api.TreeNodeTypeBlob {
log.Ctx(ctx).Warn().Msgf(
"tree node at path %q is of type %d instead of %d (blob), run without .gitleaksignore",
treePath,
node.NodeType,
api.TreeNodeTypeBlob,
)
return "", nil
}
log.Ctx(ctx).Debug().Msgf(".gitleaksignore file found in tree at %q", treePath)
// read blob data from bare repo
blob, err := api.GetBlob(
ctx,
sharedRepo.Directory(),
nil,
node.SHA,
0,
)
if err != nil {
return "", fmt.Errorf(
"failed to get blob for .gitleaksignore file at path %q sha %q: %w", treePath, node.SHA, err)
}
defer func() {
if err := blob.Content.Close(); err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader for .gitleaksignore file")
}
}()
// write file to root of .git folder of the shared repo for easy cleanup (it's a bare repo so otherwise no impact)
filePath := path.Join(sharedRepo.Directory(), DefaultGitleaksIgnorePath)
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return "", fmt.Errorf("failed to create tmp .gitleaksignore file: %w", err)
}
defer func() {
if err := f.Close(); err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf("failed to close tmp .gitleaksignore file at %q", filePath)
}
}()
_, err = io.Copy(f, blob.Content)
if err != nil {
return "", fmt.Errorf("failed to copy .gitleaksignore file from blob to %q: %w", filePath, err)
}
return filePath, nil
}
func mapFindings(reports []report.Finding) []ScanSecretsFinding {
var findings []ScanSecretsFinding
for _, f := range reports {
findings = append(findings, ScanSecretsFinding{
Description: f.Description,
StartLine: int64(f.StartLine),
EndLine: int64(f.EndLine),
StartColumn: int64(f.StartColumn),
EndColumn: int64(f.EndColumn),
Match: f.Match,
Secret: f.Secret,
File: f.File,
SymlinkFile: f.SymlinkFile,
Commit: f.Commit,
Entropy: float64(f.Entropy),
Author: f.Author,
Email: f.Email,
Date: f.Date,
Message: f.Message,
Tags: f.Tags,
RuleID: f.RuleID,
Fingerprint: f.Fingerprint,
})
}
return findings
}