internal/leaks/scan.go
243 lines · 6896 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 defer cmd.Wait() // after cancel, which ends git on an early return
181 // Fed from another goroutine: the pipe holds fewer names than a large
182 // push has, and git blocks writing output nobody is reading yet.
183 go func() {
184 defer stdin.Close()
185 w := bufio.NewWriter(stdin)
186 for _, oid := range oids {
187 if _, err := fmt.Fprintln(w, oid); err != nil {
188 return
189 }
190 }
191 w.Flush()
192 }()
193 r := bufio.NewReader(stdout)
194 var total int64
195 for range oids {
196 header, err := r.ReadString('\n')
197 if err != nil {
198 if ctx.Err() != nil {
199 return true, nil
200 }
201 return true, fmt.Errorf("cat-file --batch: %w", err)
202 }
203 f := strings.Fields(header)
204 if len(f) == 2 && f[1] == "missing" {
205 continue
206 }
207 if len(f) != 3 {
208 return true, fmt.Errorf("cat-file --batch: unexpected %q", strings.TrimSpace(header))
209 }
210 size, err := strconv.ParseInt(f[2], 10, 64)
211 if err != nil {
212 return true, fmt.Errorf("cat-file --batch: bad size in %q", strings.TrimSpace(header))
213 }
214 if size > MaxBlobBytes {
215 if _, err := r.Discard(int(size) + 1); err != nil {
216 return true, readErr(ctx, err)
217 }
218 continue
219 }
220 if total += size; total > MaxScanBytes {
221 return true, nil
222 }
223 data := make([]byte, size)
224 if _, err := io.ReadFull(r, data); err != nil {
225 return true, readErr(ctx, err)
226 }
227 if _, err := r.Discard(1); err != nil {
228 return true, readErr(ctx, err)
229 }
230 if !fn(f[0], data) {
231 return true, nil
232 }
233 }
234 return false, nil
235}
236
237// readErr is nil when the deadline caused the failed read: a truncation.
238func readErr(ctx context.Context, err error) error {
239 if ctx.Err() != nil || errors.Is(err, context.Canceled) {
240 return nil
241 }
242 return fmt.Errorf("cat-file --batch: %w", err)
243}