internal/leaks/scan.go
249 lines · 7036 bytes
1package leaks
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os/exec"
10 "sort"
11 "strconv"
12 "strings"
13
14 "gitbay.org/gitbay/internal/toolpath"
15)
16
17// Bounds on one scan. A push or a history bigger than these is scanned in
18// part and reported as truncated rather than holding the push open: the
19// hook runs while the pusher waits.
20const (
21 MaxBlobBytes = 1 << 20 // a larger file is skipped: generated, vendored, or data
22 MaxScanBytes = 64 << 20 // total content read
23 MaxBlobs = 20000
24 MaxFindings = 100
25)
26
27// Finding is one match: which commit added the content, where, and which
28// rule matched. Never the matched text.
29type Finding struct {
30 Commit string `json:"commit"`
31 Path string `json:"path"`
32 Line int `json:"line"`
33 Rule string `json:"rule"`
34}
35
36// Report is the outcome of one scan. Truncated means a bound or the
37// deadline stopped it before every blob was read; Error that git failed.
38type Report struct {
39 Findings []Finding `json:"findings"`
40 Blobs int `json:"blobs"`
41 Truncated bool `json:"truncated,omitempty"`
42 Error string `json:"error,omitempty"`
43}
44
45type origin struct{ commit, path string }
46
47// Scan reads the blobs the commits selected by revs add or change, as
48// `git log` arguments (`<tip> --not --all` for a push, `--all` for a
49// history), and reports where they match a rule. Merge commits are not
50// diffed, so a secret introduced only in a conflict resolution is missed.
51// The deadline on ctx ends the scan early as a truncation, not an error.
52func Scan(ctx context.Context, dir string, revs ...string) Report {
53 oids, origins, truncated, err := changedBlobs(ctx, dir, revs)
54 rep := Report{Truncated: truncated}
55 if err != nil {
56 rep.Error = err.Error()
57 return rep
58 }
59 if len(oids) == 0 {
60 return rep
61 }
62 more, err := readBlobs(ctx, dir, oids, func(oid string, data []byte) bool {
63 rep.Blobs++
64 if binary(data) {
65 return true
66 }
67 o := origins[oid]
68 for _, h := range Find(data) {
69 if len(rep.Findings) >= MaxFindings {
70 rep.Truncated = true
71 return false
72 }
73 rep.Findings = append(rep.Findings, Finding{Commit: o.commit, Path: o.path, Line: h.Line, Rule: h.Rule})
74 }
75 return true
76 })
77 rep.Truncated = rep.Truncated || more
78 if err != nil {
79 rep.Error = err.Error()
80 }
81 sort.Slice(rep.Findings, func(i, j int) bool {
82 a, b := rep.Findings[i], rep.Findings[j]
83 if a.Path != b.Path {
84 return a.Path < b.Path
85 }
86 return a.Line < b.Line
87 })
88 return rep
89}
90
91// changedBlobs lists the distinct blobs the selected commits add or
92// modify, with the commit and path each was first seen under. Symlinks and
93// submodules carry no content worth reading.
94func changedBlobs(ctx context.Context, dir string, revs []string) ([]string, map[string]origin, bool, error) {
95 args := append([]string{"-C", dir, "-c", "core.quotePath=false", "log", "--raw", "--no-abbrev",
96 "--no-renames", "--format=commit %H"}, revs...)
97 cmd := exec.CommandContext(ctx, toolpath.Look("git"), args...)
98 stdout, err := cmd.StdoutPipe()
99 if err != nil {
100 return nil, nil, false, err
101 }
102 if err := cmd.Start(); err != nil {
103 return nil, nil, false, fmt.Errorf("git log: %w", err)
104 }
105 var (
106 oids []string
107 origins = map[string]origin{}
108 commit string
109 truncated bool
110 )
111 sc := bufio.NewScanner(stdout)
112 sc.Buffer(make([]byte, 64<<10), 1<<20)
113 for sc.Scan() {
114 line := sc.Text()
115 if sha, ok := strings.CutPrefix(line, "commit "); ok {
116 commit = sha
117 continue
118 }
119 meta, path, ok := strings.Cut(line, "\t")
120 if !ok || !strings.HasPrefix(meta, ":") {
121 continue
122 }
123 f := strings.Fields(meta)
124 if len(f) != 5 || f[4] == "D" || (f[1] != "100644" && f[1] != "100755") {
125 continue
126 }
127 if strings.HasPrefix(path, `"`) {
128 if p, err := strconv.Unquote(path); err == nil {
129 path = p
130 }
131 }
132 oid := f[3]
133 if _, seen := origins[oid]; seen {
134 continue
135 }
136 if len(oids) >= MaxBlobs {
137 truncated = true
138 break
139 }
140 origins[oid] = origin{commit, path}
141 oids = append(oids, oid)
142 }
143 // Stopping early leaves git writing into a pipe nobody reads; killing it
144 // is how the early stop ends it, so that exit is not an error.
145 if truncated {
146 cmd.Process.Kill()
147 }
148 waitErr := cmd.Wait()
149 switch {
150 case ctx.Err() != nil:
151 return oids, origins, true, nil
152 case truncated:
153 return oids, origins, true, nil
154 case sc.Err() != nil:
155 return nil, nil, false, sc.Err()
156 case waitErr != nil:
157 return nil, nil, false, fmt.Errorf("git log: %w", waitErr)
158 }
159 return oids, origins, false, nil
160}
161
162// readBlobs streams oids through one `cat-file --batch`, handing each blob
163// within MaxBlobBytes to fn until fn returns false. It reports whether it
164// stopped before the end, on a bound or the deadline.
165func readBlobs(ctx context.Context, dir string, oids []string, fn func(oid string, data []byte) bool) (bool, error) {
166 ctx, cancel := context.WithCancel(ctx)
167 defer cancel()
168 cmd := exec.CommandContext(ctx, toolpath.Look("git"), "-C", dir, "cat-file", "--batch")
169 stdin, err := cmd.StdinPipe()
170 if err != nil {
171 return false, err
172 }
173 stdout, err := cmd.StdoutPipe()
174 if err != nil {
175 return false, err
176 }
177 if err := cmd.Start(); err != nil {
178 return false, fmt.Errorf("cat-file --batch: %w", err)
179 }
180 // Cancel before Wait, in one defer: on an early return git is blocked
181 // writing output nobody reads, and Wait alone would wait for the
182 // deadline to kill it.
183 defer func() {
184 cancel()
185 cmd.Wait()
186 }()
187 // Fed from another goroutine: the pipe holds fewer names than a large
188 // push has, and git blocks writing output nobody is reading yet.
189 go func() {
190 defer stdin.Close()
191 w := bufio.NewWriter(stdin)
192 for _, oid := range oids {
193 if _, err := fmt.Fprintln(w, oid); err != nil {
194 return
195 }
196 }
197 w.Flush()
198 }()
199 r := bufio.NewReader(stdout)
200 var total int64
201 for range oids {
202 header, err := r.ReadString('\n')
203 if err != nil {
204 if ctx.Err() != nil {
205 return true, nil
206 }
207 return true, fmt.Errorf("cat-file --batch: %w", err)
208 }
209 f := strings.Fields(header)
210 if len(f) == 2 && f[1] == "missing" {
211 continue
212 }
213 if len(f) != 3 {
214 return true, fmt.Errorf("cat-file --batch: unexpected %q", strings.TrimSpace(header))
215 }
216 size, err := strconv.ParseInt(f[2], 10, 64)
217 if err != nil {
218 return true, fmt.Errorf("cat-file --batch: bad size in %q", strings.TrimSpace(header))
219 }
220 if size > MaxBlobBytes {
221 if _, err := r.Discard(int(size) + 1); err != nil {
222 return true, readErr(ctx, err)
223 }
224 continue
225 }
226 if total += size; total > MaxScanBytes {
227 return true, nil
228 }
229 data := make([]byte, size)
230 if _, err := io.ReadFull(r, data); err != nil {
231 return true, readErr(ctx, err)
232 }
233 if _, err := r.Discard(1); err != nil {
234 return true, readErr(ctx, err)
235 }
236 if !fn(f[0], data) {
237 return true, nil
238 }
239 }
240 return false, nil
241}
242
243// readErr is nil when the deadline caused the failed read: a truncation.
244func readErr(ctx context.Context, err error) error {
245 if ctx.Err() != nil || errors.Is(err, context.Canceled) {
246 return nil
247 }
248 return fmt.Errorf("cat-file --batch: %w", err)
249}