mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-29 04:34:46 +01:00
Archive support (#1872)
* Start Files Source
* Keep cmd the same for now
* Get tests to pass
* s.MaxTargetMegaBytes -> s.MaxFileSize
* Tweak some log messages & use q semgroup for files
* Just call yield inside the semgroup
* Refactor a check and revert some log lines
* Move mg && misc tuning
* Add `make profile`
(Benchmark results are only added if tools are installed)
Example output:
```
========================================================================
generating profile data
------------------------------------------------------------------------
- mode: dir
benchmark:
tool: hyperfine
path: profile/1748019612/dir/benchmark.json
results:
mean: 1.12852930166
stddev: 0.12163775966037399
median: 1.07242928416
user: 3.9699382799999996
system: 0.04382341999999999
min: 1.03207673016
max: 1.3913475181600001
profile:
- mode: cpu
path: profile/1748019612/dir/cpu.pprof
view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/cpu.pprof
- mode: mem
path: profile/1748019612/dir/mem.pprof
view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/mem.pprof
- mode: trace
path: profile/1748019612/dir/trace.out
view: go tool trace profile/1748019612/dir/trace.out
- mode: git
...snip...
```
* Archive support for File based sources
* Move Git to Source interface
* Scan archives in git
* Misc linter fixes
* Exclude certain diffs: --diff-filter=tuxdb
* Add git archives tests
* Log error instead of fatal
* Fix spacing in test config
* Refine source comments/wording
* Make MB conversions more readable
* Format cmd
* Adjust DetectSource logging
* MiB -> MB in logs
* Add testdata/repos/archives/dotGit/refs/.gitkeep
Without it the refs folder gets deleted and the
and then it isn't detected as a git repo ¯\_(ツ)_/¯
So then the test starts scanning the whole gitleaks
repo instead :D
* Handle finding links for archives
* Working on archive depth
* Fixes from failfast test
* cmd max-archive-depth
* added comments, fixed warnings
* removed test print
* Update README.md
* Set archive depth for DetectFiles
* Tweak logs & pass max archive for readers
* Pass ctx to Fragments
* Add make lint target and address some issues
* Fix compat issue
* Report path in fragment errors
* Apply PR suggestions & misc changes
- Update blobReader.Close() to discard the buffer
- Misc logger issues & uses
- Tweak .golangci.yaml to default to none
- Discard remaining blobReader data on close
- Undo a De Morgan's Law suggestion (and disable QF1001)
* Add http mode for diagnostics
gitleaks --diagnostics=http ...
-----
From the net/http/pprof docs:
Use the pprof tool to look at the heap profile:
```
go tool pprof http://localhost:6060/debug/pprof/heap
```
Or to look at a 30-second CPU profile:
```
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
```
Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:
```
go tool pprof http://localhost:6060/debug/pprof/block
```
Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:
```
go tool pprof http://localhost:6060/debug/pprof/mutex
```
(For more info see https://pkg.go.dev/net/http/pprof)
---------
Co-authored-by: Alex Layne <alayne@redhat.com>
This commit is contained in:
1 parent
489d13c14e
commit
782f310478
77 files changed
+2975
-777
No files matched your search
@@ -0,0 +1,125 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/mholt/archives"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
const maxPeekSize = 25 * 1_000 // 10kb
|
||||
var isWhitespace [256]bool
|
||||
var isWindows = runtime.GOOS == "windows"
|
||||
|
||||
func init() {
|
||||
// define whitespace characters
|
||||
isWhitespace[' '] = true
|
||||
isWhitespace['\t'] = true
|
||||
isWhitespace['\n'] = true
|
||||
isWhitespace['\r'] = true
|
||||
}
|
||||
|
||||
// isArchive does a light check to see if the provided path is an archive or
|
||||
// compressed file. The File source already does this, so this exists mainly
|
||||
// to avoid expensive calls before sending things to the File source
|
||||
func isArchive(ctx context.Context, path string) bool {
|
||||
format, _, err := archives.Identify(ctx, path, nil)
|
||||
return err == nil && format != nil
|
||||
}
|
||||
|
||||
// shouldSkipPath checks a path against all the allowlists to see if it can
|
||||
// be skipped
|
||||
func shouldSkipPath(cfg *config.Config, path string) bool {
|
||||
if cfg == nil {
|
||||
logging.Trace().Str("path", path).Msg("not skipping path because config is nil")
|
||||
return false
|
||||
}
|
||||
|
||||
for _, a := range cfg.Allowlists {
|
||||
if a.PathAllowed(path) ||
|
||||
// TODO: Remove this in v9.
|
||||
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
|
||||
(isWindows && a.PathAllowed(filepath.ToSlash(path))) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// readUntilSafeBoundary consumes |f| until it finds two consecutive `\n` characters, up to |maxPeekSize|.
|
||||
// This hopefully avoids splitting. (https://github.com/gitleaks/gitleaks/issues/1651)
|
||||
func readUntilSafeBoundary(r *bufio.Reader, n int, maxPeekSize int, peekBuf *bytes.Buffer) error {
|
||||
if peekBuf.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Does the buffer end in consecutive newlines?
|
||||
var (
|
||||
data = peekBuf.Bytes()
|
||||
lastChar = data[len(data)-1]
|
||||
newlineCount = 0 // Tracks consecutive newlines
|
||||
)
|
||||
|
||||
if isWhitespace[lastChar] {
|
||||
for i := len(data) - 1; i >= 0; i-- {
|
||||
lastChar = data[i]
|
||||
if lastChar == '\n' {
|
||||
newlineCount++
|
||||
|
||||
// Stop if two consecutive newlines are found
|
||||
if newlineCount >= 2 {
|
||||
return nil
|
||||
}
|
||||
} else if isWhitespace[lastChar] {
|
||||
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
|
||||
// (Intentionally do nothing.)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If not, read ahead until we (hopefully) find some.
|
||||
newlineCount = 0
|
||||
for {
|
||||
data = peekBuf.Bytes()
|
||||
// Check if the last character is a newline.
|
||||
lastChar = data[len(data)-1]
|
||||
if lastChar == '\n' {
|
||||
newlineCount++
|
||||
|
||||
// Stop if two consecutive newlines are found
|
||||
if newlineCount >= 2 {
|
||||
break
|
||||
}
|
||||
} else if isWhitespace[lastChar] {
|
||||
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
|
||||
// (Intentionally do nothing.)
|
||||
} else {
|
||||
newlineCount = 0 // Reset if a non-newline character is found
|
||||
}
|
||||
|
||||
// Stop growing the buffer if it reaches maxSize
|
||||
if (peekBuf.Len() - n) >= maxPeekSize {
|
||||
break
|
||||
}
|
||||
|
||||
// Read additional data into a temporary buffer
|
||||
b, err := r.ReadByte()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return err
|
||||
}
|
||||
peekBuf.WriteByte(b)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_readUntilSafeBoundary(t *testing.T) {
|
||||
// Arrange
|
||||
cases := []struct {
|
||||
name string
|
||||
r io.Reader
|
||||
expected string
|
||||
}{
|
||||
// Current split is fine, exit early.
|
||||
{
|
||||
name: "safe original split - LF",
|
||||
r: strings.NewReader("abc\n\ndefghijklmnop\n\nqrstuvwxyz"),
|
||||
expected: "abc\n\n",
|
||||
},
|
||||
{
|
||||
name: "safe original split - CRLF",
|
||||
r: strings.NewReader("a\r\n\r\nbcdefghijklmnop\n"),
|
||||
expected: "a\r\n\r\n",
|
||||
},
|
||||
// Current split is bad, look for a better one.
|
||||
{
|
||||
name: "safe split - LF",
|
||||
r: strings.NewReader("abcdefg\nhijklmnop\n\nqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnop\n\n",
|
||||
},
|
||||
{
|
||||
name: "safe split - CRLF",
|
||||
r: strings.NewReader("abcdefg\r\nhijklmnop\r\n\r\nqrstuvwxyz"),
|
||||
expected: "abcdefg\r\nhijklmnop\r\n\r\n",
|
||||
},
|
||||
{
|
||||
name: "safe split - blank line",
|
||||
r: strings.NewReader("abcdefg\nhijklmnop\n\t \t\nqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnop\n\t \t\n",
|
||||
},
|
||||
// Current split is bad, exhaust options.
|
||||
{
|
||||
name: "no safe split",
|
||||
r: strings.NewReader("abcdefg\nhijklmnopqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnopqrstuvwx",
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
buf := make([]byte, 5)
|
||||
n, err := c.r.Read(buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Act
|
||||
reader := bufio.NewReader(c.r)
|
||||
peekBuf := bytes.NewBuffer(buf[:n])
|
||||
err = readUntilSafeBoundary(reader, n, 20, peekBuf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Assert
|
||||
t.Log(peekBuf.String())
|
||||
require.Equal(t, c.expected, peekBuf.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
type ScanTarget struct {
|
||||
Path string
|
||||
Symlink string
|
||||
}
|
||||
|
||||
var isWindows = runtime.GOOS == "windows"
|
||||
|
||||
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
|
||||
paths := make(chan ScanTarget)
|
||||
s.Go(func() error {
|
||||
defer close(paths)
|
||||
return filepath.Walk(source,
|
||||
func(path string, fInfo os.FileInfo, err error) error {
|
||||
logger := logging.With().Str("path", path).Logger()
|
||||
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
// This seems to only fail on directories at this stage.
|
||||
logger.Warn().Msg("Skipping directory: permission denied")
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Empty; nothing to do here.
|
||||
if fInfo.Size() == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unwrap symlinks, if |followSymlinks| is set.
|
||||
scanTarget := ScanTarget{
|
||||
Path: path,
|
||||
}
|
||||
if fInfo.Mode().Type() == fs.ModeSymlink {
|
||||
if !followSymlinks {
|
||||
logger.Debug().Msg("Skipping symlink")
|
||||
return nil
|
||||
}
|
||||
|
||||
realPath, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
realPathFileInfo, _ := os.Stat(realPath)
|
||||
if realPathFileInfo.IsDir() {
|
||||
logger.Warn().Str("target", realPath).Msg("Skipping symlinked directory")
|
||||
return nil
|
||||
}
|
||||
|
||||
scanTarget.Path = realPath
|
||||
scanTarget.Symlink = path
|
||||
}
|
||||
|
||||
// TODO: Also run this check against the resolved symlink?
|
||||
var skip bool
|
||||
for _, a := range allowlists {
|
||||
skip = a.PathAllowed(path) ||
|
||||
// TODO: Remove this in v9.
|
||||
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
|
||||
(isWindows && a.PathAllowed(filepath.ToSlash(path)))
|
||||
if skip {
|
||||
break
|
||||
}
|
||||
}
|
||||
if fInfo.IsDir() {
|
||||
// Directory
|
||||
if skip {
|
||||
logger.Debug().Msg("Skipping directory due to global allowlist")
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
||||
if fInfo.Name() == ".git" {
|
||||
// Don't scan .git directories.
|
||||
// TODO: Add this to the config allowlist, instead of hard-coding it.
|
||||
return filepath.SkipDir
|
||||
}
|
||||
} else {
|
||||
// File
|
||||
if skip {
|
||||
logger.Debug().Msg("Skipping file due to global allowlist")
|
||||
return nil
|
||||
}
|
||||
|
||||
paths <- scanTarget
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
return paths, nil
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/h2non/filetype"
|
||||
"github.com/mholt/archives"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
const defaultBufferSize = 100 * 1_000 // 100kb
|
||||
const InnerPathSeparator = "!"
|
||||
|
||||
type seekReaderAt interface {
|
||||
io.ReaderAt
|
||||
io.Seeker
|
||||
}
|
||||
|
||||
// File is a source for yielding fragments from a file or other reader
|
||||
type File struct {
|
||||
// Content provides a reader to the file's content
|
||||
Content io.Reader
|
||||
// Path is the resolved real path of the file
|
||||
Path string
|
||||
// Symlink represents a symlink to the file if that's how it was discovered
|
||||
Symlink string
|
||||
// Buffer is used for reading the content in chunks
|
||||
Buffer []byte
|
||||
// Config is the gitleaks config used for shouldSkipPath. If not set, then
|
||||
// shouldSkipPath is ignored
|
||||
Config *config.Config
|
||||
// outerPaths is the list of container paths (e.g. archives) that lead to
|
||||
// this file
|
||||
outerPaths []string
|
||||
// MaxArchiveDepth limits how deep the sources will explore nested archives
|
||||
MaxArchiveDepth int
|
||||
// archiveDepth is the current archive nesting depth
|
||||
archiveDepth int
|
||||
}
|
||||
|
||||
// Fragments yields fragments for the this source
|
||||
func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||
format, _, err := archives.Identify(ctx, s.Path, nil)
|
||||
// Process the file as an archive if there's no error && Identify returns
|
||||
// a format; but if there's an error or no format, just swallow the error
|
||||
// and fall back on treating it like a normal file and let fileFragments
|
||||
// decide what to do with it.
|
||||
if err == nil && format != nil {
|
||||
if s.archiveDepth+1 > s.MaxArchiveDepth {
|
||||
logging.Warn().Str(
|
||||
"path", s.FullPath(),
|
||||
).Int(
|
||||
"max_archive_depth", s.MaxArchiveDepth,
|
||||
).Msg("skipping archive: exceeds max archive depth")
|
||||
return nil
|
||||
}
|
||||
if extractor, ok := format.(archives.Extractor); ok {
|
||||
return s.extractorFragments(ctx, extractor, s.Content, yield)
|
||||
}
|
||||
if decompressor, ok := format.(archives.Decompressor); ok {
|
||||
return s.decompressorFragments(decompressor, s.Content, yield)
|
||||
}
|
||||
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
|
||||
}
|
||||
|
||||
return s.fileFragments(bufio.NewReader(s.Content), yield)
|
||||
}
|
||||
|
||||
// extractorFragments recursively crawls archives and yields fragments
|
||||
func (s *File) extractorFragments(ctx context.Context, extractor archives.Extractor, reader io.Reader, yield FragmentsFunc) error {
|
||||
if _, isSeekReaderAt := reader.(seekReaderAt); !isSeekReaderAt {
|
||||
switch extractor.(type) {
|
||||
case archives.SevenZip, archives.Zip:
|
||||
tmpfile, err := os.CreateTemp("", "gitleaks-archive-")
|
||||
if err != nil {
|
||||
logging.Error().Str("path", s.FullPath()).Msg("could not create tmp file")
|
||||
return nil
|
||||
}
|
||||
defer func() {
|
||||
_ = tmpfile.Close()
|
||||
_ = os.Remove(tmpfile.Name())
|
||||
}()
|
||||
|
||||
_, err = io.Copy(tmpfile, reader)
|
||||
if err != nil {
|
||||
logging.Error().Str("path", s.FullPath()).Msg("could not copy archive file")
|
||||
return nil
|
||||
}
|
||||
|
||||
reader = tmpfile
|
||||
}
|
||||
}
|
||||
|
||||
return extractor.Extract(ctx, reader, func(_ context.Context, d archives.FileInfo) error {
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
innerReader, err := d.Open()
|
||||
if err != nil {
|
||||
logging.Error().Err(err).Str("path", s.FullPath()).Msg("could not open archive inner file")
|
||||
return nil
|
||||
}
|
||||
defer innerReader.Close()
|
||||
path := filepath.Clean(d.NameInArchive)
|
||||
|
||||
if s.Config != nil && shouldSkipPath(s.Config, path) {
|
||||
logging.Debug().Str("path", s.FullPath()).Msg("skipping file: global allowlist")
|
||||
return nil
|
||||
}
|
||||
|
||||
file := &File{
|
||||
Content: innerReader,
|
||||
Path: path,
|
||||
Symlink: s.Symlink,
|
||||
outerPaths: append(s.outerPaths, filepath.ToSlash(s.Path)),
|
||||
MaxArchiveDepth: s.MaxArchiveDepth,
|
||||
archiveDepth: s.archiveDepth + 1,
|
||||
}
|
||||
|
||||
if err := file.Fragments(ctx, yield); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// decompressorFragments recursively crawls archives and yields fragments
|
||||
func (s *File) decompressorFragments(decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
|
||||
innerReader, err := decompressor.OpenReader(reader)
|
||||
if err != nil {
|
||||
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := s.fileFragments(bufio.NewReader(innerReader), yield); err != nil {
|
||||
_ = innerReader.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
_ = innerReader.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// fileFragments reads the file into fragments to yield
|
||||
func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
|
||||
// Create a buffer if the caller hasn't provided one
|
||||
if s.Buffer == nil {
|
||||
s.Buffer = make([]byte, defaultBufferSize)
|
||||
}
|
||||
|
||||
totalLines := 0
|
||||
for {
|
||||
fragment := Fragment{
|
||||
FilePath: s.FullPath(),
|
||||
}
|
||||
|
||||
n, err := reader.Read(s.Buffer)
|
||||
if n == 0 {
|
||||
if err != nil && err != io.EOF {
|
||||
return yield(fragment, fmt.Errorf("could not read file: %w", err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Only check the filetype at the start of file.
|
||||
if totalLines == 0 {
|
||||
// TODO: could other optimizations be introduced here?
|
||||
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
|
||||
return yield(
|
||||
fragment,
|
||||
fmt.Errorf("could not read file: could not determine type: %w", err),
|
||||
)
|
||||
} else if mimetype.MIME.Type == "application" {
|
||||
logging.Debug().
|
||||
Str("mime_type", mimetype.MIME.Value).
|
||||
Str("path", s.FullPath()).
|
||||
Msgf("skipping binary file")
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Try to split chunks across large areas of whitespace, if possible.
|
||||
peekBuf := bytes.NewBuffer(s.Buffer[:n])
|
||||
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
|
||||
return yield(
|
||||
fragment,
|
||||
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
|
||||
)
|
||||
}
|
||||
|
||||
fragment.Raw = peekBuf.String()
|
||||
fragment.Bytes = peekBuf.Bytes()
|
||||
fragment.StartLine = totalLines + 1
|
||||
|
||||
// Count the number of newlines in this chunk
|
||||
totalLines += strings.Count(fragment.Raw, "\n")
|
||||
|
||||
if len(s.Symlink) > 0 {
|
||||
fragment.SymlinkFile = s.Symlink
|
||||
}
|
||||
|
||||
if isWindows {
|
||||
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
|
||||
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
|
||||
fragment.WindowsFilePath = s.FullPath()
|
||||
}
|
||||
|
||||
// log errors but continue since there's content
|
||||
if err != nil && err != io.EOF {
|
||||
logging.Warn().Err(err).Msgf("issue reading file")
|
||||
}
|
||||
|
||||
// Done with the file!
|
||||
if err == io.EOF {
|
||||
return yield(fragment, nil)
|
||||
}
|
||||
|
||||
if err := yield(fragment, err); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FullPath returns the File.Path with any preceding outer paths
|
||||
func (s *File) FullPath() string {
|
||||
if len(s.outerPaths) > 0 {
|
||||
return strings.Join(
|
||||
// outerPaths have already been normalized to slash
|
||||
append(s.outerPaths, s.Path),
|
||||
InnerPathSeparator,
|
||||
)
|
||||
}
|
||||
|
||||
return s.Path
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
// TODO: remove this in v9 and have scanTargets yield file sources
|
||||
type ScanTarget struct {
|
||||
Path string
|
||||
Symlink string
|
||||
}
|
||||
|
||||
// Deprecated: Use Files and detector.DetectSource instead
|
||||
func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
|
||||
paths := make(chan ScanTarget)
|
||||
|
||||
// create a Files source
|
||||
files := Files{
|
||||
FollowSymlinks: followSymlinks,
|
||||
Path: sourcePath,
|
||||
Sema: s,
|
||||
Config: &config.Config{
|
||||
Allowlists: allowlists,
|
||||
},
|
||||
}
|
||||
|
||||
s.Go(func() error {
|
||||
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
|
||||
paths <- scanTarget
|
||||
return nil
|
||||
})
|
||||
close(paths)
|
||||
return err
|
||||
})
|
||||
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
// Files is a source for yielding fragments from a collection of files
|
||||
type Files struct {
|
||||
Config *config.Config
|
||||
FollowSymlinks bool
|
||||
MaxFileSize int
|
||||
Path string
|
||||
Sema *semgroup.Group
|
||||
MaxArchiveDepth int
|
||||
}
|
||||
|
||||
// scanTargets yields scan targets to a callback func
|
||||
func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
|
||||
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
|
||||
scanTarget := ScanTarget{Path: path}
|
||||
logger := logging.With().Str("path", path).Logger()
|
||||
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
// This seems to only fail on directories at this stage.
|
||||
logger.Warn().Err(errors.New("permission denied")).Msg("skipping directory")
|
||||
return filepath.SkipDir
|
||||
}
|
||||
logger.Warn().Err(err).Msg("skipping")
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
if d.IsDir() {
|
||||
logger.Error().Err(err).Msg("skipping directory: could not get info")
|
||||
return filepath.SkipDir
|
||||
}
|
||||
logger.Error().Err(err).Msg("skipping file: could not get info")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !d.IsDir() {
|
||||
// Empty; nothing to do here.
|
||||
if info.Size() == 0 {
|
||||
logger.Debug().Msg("skipping empty file")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Too large; nothing to do here.
|
||||
if s.MaxFileSize > 0 && info.Size() > int64(s.MaxFileSize) {
|
||||
logger.Warn().Msgf(
|
||||
"skipping file: too large max_size=%dMB, size=%dMB",
|
||||
s.MaxFileSize/1_000_000, info.Size()/1_000_000,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// set the initial scan target values
|
||||
if d.Type() == fs.ModeSymlink {
|
||||
if !s.FollowSymlinks {
|
||||
logger.Debug().Msg("skipping symlink: follow symlinks disabled")
|
||||
return nil
|
||||
}
|
||||
realPath, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("skipping symlink: could not evaluate")
|
||||
return nil
|
||||
}
|
||||
if realPathFileInfo, _ := os.Stat(realPath); realPathFileInfo.IsDir() {
|
||||
logger.Debug().Str("target", realPath).Msgf("skipping symlink: target is directory")
|
||||
return nil
|
||||
}
|
||||
scanTarget = ScanTarget{
|
||||
Path: realPath,
|
||||
Symlink: path,
|
||||
}
|
||||
}
|
||||
|
||||
// handle dir cases (mainly just see if it should be skipped
|
||||
if info.IsDir() {
|
||||
if shouldSkipPath(s.Config, path) {
|
||||
logger.Debug().Msg("skipping directory: global allowlist")
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if shouldSkipPath(s.Config, path) {
|
||||
logger.Debug().Msg("skipping file: global allowlist")
|
||||
return nil
|
||||
}
|
||||
|
||||
return yield(scanTarget, nil)
|
||||
})
|
||||
}
|
||||
|
||||
// Fragments yields fragments from files discovered under the path
|
||||
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
err := s.scanTargets(func(scanTarget ScanTarget, err error) error {
|
||||
wg.Add(1)
|
||||
s.Sema.Go(func() error {
|
||||
logger := logging.With().Str("path", scanTarget.Path).Logger()
|
||||
logger.Trace().Msg("scanning path")
|
||||
|
||||
f, err := os.Open(scanTarget.Path)
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
logger.Warn().Msg("skipping file: permission denied")
|
||||
}
|
||||
wg.Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert this to a file source
|
||||
file := File{
|
||||
Content: f,
|
||||
Path: scanTarget.Path,
|
||||
Symlink: scanTarget.Symlink,
|
||||
Config: s.Config,
|
||||
MaxArchiveDepth: s.MaxArchiveDepth,
|
||||
}
|
||||
|
||||
err = file.Fragments(ctx, yield)
|
||||
// Avoiding a defer in a hot loop
|
||||
_ = f.Close()
|
||||
wg.Done()
|
||||
return err
|
||||
})
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
wg.Wait()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package sources
|
||||
|
||||
// Fragment represents a fragment of a source with its meta data
|
||||
type Fragment struct {
|
||||
// Raw is the raw content of the fragment
|
||||
Raw string
|
||||
|
||||
Bytes []byte
|
||||
|
||||
// FilePath is the path to the file if applicable.
|
||||
// The path separator MUST be normalized to `/`.
|
||||
FilePath string
|
||||
SymlinkFile string
|
||||
// WindowsFilePath is the path with the original separator.
|
||||
// This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565.
|
||||
WindowsFilePath string `json:"-"` // TODO: remove this in v9.
|
||||
|
||||
// CommitSHA is the SHA of the commit if applicable
|
||||
CommitSHA string // TODO: remove this in v9 and use CommitInfo instead
|
||||
|
||||
// StartLine is the line number this fragment starts on
|
||||
StartLine int
|
||||
|
||||
// CommitInfo captures additional information about the git commit if applicable
|
||||
CommitInfo *CommitInfo
|
||||
}
|
||||
+301
-2
@@ -2,15 +2,24 @@ package sources
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
@@ -21,6 +30,33 @@ type GitCmd struct {
|
||||
cmd *exec.Cmd
|
||||
diffFilesCh <-chan *gitdiff.File
|
||||
errCh <-chan error
|
||||
repoPath string
|
||||
}
|
||||
|
||||
// blobReader provides a ReadCloser interface git cat-file blob to fetch
|
||||
// a blob from a repo
|
||||
type blobReader struct {
|
||||
io.ReadCloser
|
||||
cmd *exec.Cmd
|
||||
}
|
||||
|
||||
// Close closes the underlying reader and then waits for the command to complete,
|
||||
// releasing its resources.
|
||||
func (br *blobReader) Close() error {
|
||||
// Discard the remaining data from the pipe to avoid blocking
|
||||
_, drainErr := io.Copy(io.Discard, br)
|
||||
// Close the pipe (should signal the command to stop if it hasn't already)
|
||||
closeErr := br.ReadCloser.Close()
|
||||
// Wait to prevent zombie processes.
|
||||
waitErr := br.cmd.Wait()
|
||||
// Return the first error encountered
|
||||
if drainErr != nil {
|
||||
return drainErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
return waitErr
|
||||
}
|
||||
|
||||
// NewGitLogCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
|
||||
@@ -49,7 +85,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
cmd = exec.Command("git", args...)
|
||||
} else {
|
||||
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
|
||||
"--full-history", "--all")
|
||||
"--full-history", "--all", "--diff-filter=tuxdb")
|
||||
}
|
||||
|
||||
logging.Debug().Msgf("executing: %s", cmd.String())
|
||||
@@ -78,6 +114,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
cmd: cmd,
|
||||
diffFilesCh: gitdiffFiles,
|
||||
errCh: errCh,
|
||||
repoPath: sourceClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -118,6 +155,7 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
|
||||
cmd: cmd,
|
||||
diffFilesCh: gitdiffFiles,
|
||||
errCh: errCh,
|
||||
repoPath: sourceClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -135,10 +173,31 @@ func (c *GitCmd) ErrCh() <-chan error {
|
||||
// stdin or copying from stdout or stderr to complete.
|
||||
//
|
||||
// Wait also closes underlying stdout and stderr.
|
||||
func (c *GitCmd) Wait() (err error) {
|
||||
func (c *GitCmd) Wait() error {
|
||||
return c.cmd.Wait()
|
||||
}
|
||||
|
||||
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
|
||||
// within the git repo used to create the GitCmd.
|
||||
//
|
||||
// The caller is responsible for closing the reader.
|
||||
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
|
||||
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
|
||||
cmd := exec.Command("git", gitArgs...)
|
||||
cmd.Stderr = io.Discard
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get stdout pipe: %w", err)
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("failed to start git command: %w", err)
|
||||
}
|
||||
return &blobReader{
|
||||
ReadCloser: stdout,
|
||||
cmd: cmd,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// listenForStdErr listens for stderr output from git, prints it to stdout,
|
||||
// sends to errCh and closes it.
|
||||
func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
@@ -187,3 +246,243 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// RemoteInfo provides the info needed for reconstructing links from findings
|
||||
type RemoteInfo struct {
|
||||
Platform scm.Platform
|
||||
Url string
|
||||
}
|
||||
|
||||
// Git is a source for yielding fragments from a git repo
|
||||
type Git struct {
|
||||
Cmd *GitCmd
|
||||
Config *config.Config
|
||||
Remote *RemoteInfo
|
||||
Sema *semgroup.Group
|
||||
MaxArchiveDepth int
|
||||
}
|
||||
|
||||
// CommitInfo captures metadata about the commit
|
||||
type CommitInfo struct {
|
||||
AuthorEmail string
|
||||
AuthorName string
|
||||
Date string
|
||||
Message string
|
||||
Remote *RemoteInfo
|
||||
SHA string
|
||||
}
|
||||
|
||||
// Fragments yields fragments from a git repo
|
||||
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
|
||||
defer func() {
|
||||
_ = s.Cmd.Wait()
|
||||
}()
|
||||
|
||||
var (
|
||||
diffFilesCh = s.Cmd.DiffFilesCh()
|
||||
errCh = s.Cmd.ErrCh()
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
|
||||
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
|
||||
for diffFilesCh != nil || errCh != nil {
|
||||
select {
|
||||
case gitdiffFile, open := <-diffFilesCh:
|
||||
if !open {
|
||||
diffFilesCh = nil
|
||||
break
|
||||
}
|
||||
|
||||
if gitdiffFile.IsDelete {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip non-archive binary files
|
||||
yieldAsArchive := false
|
||||
if gitdiffFile.IsBinary {
|
||||
if !isArchive(ctx, gitdiffFile.NewName) {
|
||||
continue
|
||||
}
|
||||
yieldAsArchive = true
|
||||
}
|
||||
|
||||
// Check if commit is allowed
|
||||
commitSHA := ""
|
||||
var commitInfo *CommitInfo
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
for _, a := range s.Config.Allowlists {
|
||||
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
|
||||
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
commitInfo = &CommitInfo{
|
||||
Date: gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339),
|
||||
Message: gitdiffFile.PatchHeader.Message(),
|
||||
Remote: s.Remote,
|
||||
SHA: commitSHA,
|
||||
}
|
||||
|
||||
if gitdiffFile.PatchHeader.Author != nil {
|
||||
commitInfo.AuthorName = gitdiffFile.PatchHeader.Author.Name
|
||||
commitInfo.AuthorEmail = gitdiffFile.PatchHeader.Author.Email
|
||||
}
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
s.Sema.Go(func() error {
|
||||
defer wg.Done()
|
||||
|
||||
if yieldAsArchive {
|
||||
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
|
||||
if err != nil {
|
||||
logging.Error().Err(err).Msg("could not read archive blob")
|
||||
return nil
|
||||
}
|
||||
|
||||
file := File{
|
||||
Content: blob,
|
||||
Path: gitdiffFile.NewName,
|
||||
MaxArchiveDepth: s.MaxArchiveDepth,
|
||||
Config: s.Config,
|
||||
}
|
||||
|
||||
// enrich and yield fragments
|
||||
err = file.Fragments(ctx, func(fragment Fragment, err error) error {
|
||||
fragment.CommitSHA = commitSHA
|
||||
fragment.CommitInfo = commitInfo
|
||||
return yield(fragment, err)
|
||||
})
|
||||
|
||||
// Close the blob reader and log any issues
|
||||
if err := blob.Close(); err != nil {
|
||||
logging.Debug().Err(err).Msg("blobReader.Close() returned an error")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, textFragment := range gitdiffFile.TextFragments {
|
||||
if textFragment == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
fragment := Fragment{
|
||||
CommitSHA: commitSHA,
|
||||
FilePath: gitdiffFile.NewName,
|
||||
Raw: textFragment.Raw(gitdiff.OpAdd),
|
||||
StartLine: int(textFragment.NewPosition),
|
||||
CommitInfo: commitInfo,
|
||||
}
|
||||
|
||||
if err := yield(fragment, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
case err, open := <-errCh:
|
||||
if !open {
|
||||
errCh = nil
|
||||
break
|
||||
}
|
||||
|
||||
return yield(Fragment{}, err)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewRemoteInfo builds a new RemoteInfo for generating finding links
|
||||
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
|
||||
if platform == scm.NoPlatform {
|
||||
return &RemoteInfo{Platform: platform}
|
||||
}
|
||||
|
||||
remoteUrl, err := getRemoteUrl(source)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "No remote configured") {
|
||||
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
|
||||
platform = scm.NoPlatform
|
||||
} else {
|
||||
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
|
||||
}
|
||||
goto End
|
||||
}
|
||||
|
||||
if platform == scm.UnknownPlatform {
|
||||
platform = platformFromHost(remoteUrl)
|
||||
if platform == scm.UnknownPlatform {
|
||||
logging.Info().
|
||||
Str("host", remoteUrl.Hostname()).
|
||||
Msg("Unknown SCM platform. Use --platform to include links in findings.")
|
||||
} else {
|
||||
logging.Debug().
|
||||
Str("host", remoteUrl.Hostname()).
|
||||
Str("platform", platform.String()).
|
||||
Msg("SCM platform parsed from host")
|
||||
}
|
||||
}
|
||||
|
||||
End:
|
||||
var rUrl string
|
||||
if remoteUrl != nil {
|
||||
rUrl = remoteUrl.String()
|
||||
}
|
||||
return &RemoteInfo{
|
||||
Platform: platform,
|
||||
Url: rUrl,
|
||||
}
|
||||
}
|
||||
|
||||
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
|
||||
|
||||
func getRemoteUrl(source string) (*url.URL, error) {
|
||||
// This will return the first remote — typically, "origin".
|
||||
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
|
||||
if source != "." {
|
||||
cmd.Dir = source
|
||||
}
|
||||
|
||||
stdout, err := cmd.Output()
|
||||
if err != nil {
|
||||
var exitError *exec.ExitError
|
||||
if errors.As(err, &exitError) {
|
||||
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
remoteUrl := string(bytes.TrimSpace(stdout))
|
||||
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
|
||||
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
|
||||
}
|
||||
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
|
||||
|
||||
parsedUrl, err := url.Parse(remoteUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
|
||||
}
|
||||
|
||||
// Remove any user info.
|
||||
parsedUrl.User = nil
|
||||
return parsedUrl, nil
|
||||
}
|
||||
|
||||
func platformFromHost(u *url.URL) scm.Platform {
|
||||
switch strings.ToLower(u.Hostname()) {
|
||||
case "github.com":
|
||||
return scm.GitHubPlatform
|
||||
case "gitlab.com":
|
||||
return scm.GitLabPlatform
|
||||
case "dev.azure.com", "visualstudio.com":
|
||||
return scm.AzureDevOpsPlatform
|
||||
default:
|
||||
return scm.UnknownPlatform
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package sources
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// FragmentsFunc is the type of function called by Fragments to yield the next
|
||||
// fragment
|
||||
type FragmentsFunc func(fragment Fragment, err error) error
|
||||
|
||||
// Source is a thing that can yield fragments
|
||||
type Source interface {
|
||||
// Fragments provides a filepath.WalkDir like interface for scanning the
|
||||
// fragments in the source
|
||||
Fragments(ctx context.Context, yield FragmentsFunc) error
|
||||
}
|
||||
Reference in new issue
Block a user