mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-28 20:24:22 +01:00
first pass at archive handling
This commit is contained in:
1 parent
b6cc71aa3a
commit
770baf7458
12 files changed
+679
-105
No files matched your search
@@ -0,0 +1,100 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/archives"
|
||||
"github.com/zricethezav/gitleaks/v8/sources"
|
||||
)
|
||||
|
||||
// IsArchive asks archives.Identify (with a nil stream, so only the filename)
|
||||
// whether this file would be handled by an Extractor. If Identify returns
|
||||
// a Format implementing archives.Extractor, we treat it as an archive.
|
||||
func IsArchive(path string) bool {
|
||||
format, _, err := archives.Identify(context.Background(), path, nil)
|
||||
if err != nil {
|
||||
// no matching format at all
|
||||
return false
|
||||
}
|
||||
_, ok := format.(archives.Extractor)
|
||||
return ok
|
||||
}
|
||||
|
||||
// ExtractArchive extracts all files from archivePath into a temp dir.
|
||||
// Returns the list of ScanTargets (with real file paths) and the temp dir for cleanup.
|
||||
func ExtractArchive(archivePath string) ([]sources.ScanTarget, string, error) {
|
||||
// 1. Create a temp dir
|
||||
tmpDir, err := os.MkdirTemp("", "gitleaks-archive-")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// 2. Open the archive
|
||||
f, err := os.Open(archivePath)
|
||||
if err != nil {
|
||||
os.RemoveAll(tmpDir)
|
||||
return nil, "", err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// 3. Identify format (name-based + header peek)
|
||||
ctx := context.Background()
|
||||
format, stream, err := archives.Identify(ctx, archivePath, f)
|
||||
if err != nil {
|
||||
os.RemoveAll(tmpDir)
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// 4. Ensure it's extractable
|
||||
extractor, ok := format.(archives.Extractor)
|
||||
if !ok {
|
||||
os.RemoveAll(tmpDir)
|
||||
return nil, "", fmt.Errorf("format %T is not extractable", format)
|
||||
}
|
||||
|
||||
// 5. Walk and extract
|
||||
var targets []sources.ScanTarget
|
||||
err = extractor.Extract(ctx, stream, func(ctx context.Context, file archives.FileInfo) error {
|
||||
name := file.Name()
|
||||
// skip macOS metadata and __MACOSX folders
|
||||
// TODO add more exceptions here if needed
|
||||
base := filepath.Base(name)
|
||||
if strings.HasPrefix(base, "._") || strings.HasPrefix(name, "__MACOSX/") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if file.IsDir() {
|
||||
return nil
|
||||
}
|
||||
// open and copy out
|
||||
r, err := file.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
outPath := filepath.Join(tmpDir, file.Name())
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
outFile, err := os.Create(outPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
if _, err := io.Copy(outFile, r); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targets = append(targets, sources.ScanTarget{Path: outPath})
|
||||
return nil
|
||||
})
|
||||
|
||||
return targets, tmpDir, err
|
||||
}
|
||||
@@ -799,6 +799,28 @@ func TestFromFiles(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "archive"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "aws-access-key",
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
StartColumn: 16,
|
||||
EndColumn: 35,
|
||||
Line: "\n\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "archive.zip/main.go",
|
||||
SymlinkFile: "",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
Fingerprint: "archive.zip/main.go:aws-access-key:20",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
+135
-94
@@ -17,112 +17,153 @@ import (
|
||||
|
||||
const maxPeekSize = 25 * 1_000 // 10kb
|
||||
|
||||
// DetectFiles schedules each ScanTarget—file or archive—for concurrent scanning.
|
||||
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
|
||||
for pa := range paths {
|
||||
pa := pa // capture
|
||||
d.Sema.Go(func() error {
|
||||
logger := logging.With().Str("path", pa.Path).Logger()
|
||||
logger.Trace().Msg("Scanning path")
|
||||
|
||||
f, err := os.Open(pa.Path)
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
logger.Warn().Msg("Skipping file: permission denied")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
// Get file size
|
||||
fileInfo, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fileSize := fileInfo.Size()
|
||||
if d.MaxTargetMegaBytes > 0 {
|
||||
rawLength := fileSize / 1000000
|
||||
if rawLength > int64(d.MaxTargetMegaBytes) {
|
||||
logger.Debug().
|
||||
Int64("size", rawLength).
|
||||
Msg("Skipping file: exceeds --max-target-megabytes")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
// Buffer to hold file chunks
|
||||
reader = bufio.NewReaderSize(f, chunkSize)
|
||||
buf = make([]byte, chunkSize)
|
||||
totalLines = 0
|
||||
)
|
||||
for {
|
||||
n, err := reader.Read(buf)
|
||||
|
||||
// "Callers should always process the n > 0 bytes returned before considering the error err."
|
||||
// https://pkg.go.dev/io#Reader
|
||||
if n > 0 {
|
||||
// Only check the filetype at the start of file.
|
||||
if totalLines == 0 {
|
||||
// TODO: could other optimizations be introduced here?
|
||||
if mimetype, err := filetype.Match(buf[:n]); err != nil {
|
||||
return nil
|
||||
} else if mimetype.MIME.Type == "application" {
|
||||
return nil // skip binary files
|
||||
}
|
||||
}
|
||||
|
||||
// Try to split chunks across large areas of whitespace, if possible.
|
||||
peekBuf := bytes.NewBuffer(buf[:n])
|
||||
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
|
||||
// Count the number of newlines in this chunk
|
||||
chunk := peekBuf.String()
|
||||
linesInChunk := strings.Count(chunk, "\n")
|
||||
totalLines += linesInChunk
|
||||
fragment := Fragment{
|
||||
Raw: chunk,
|
||||
Bytes: peekBuf.Bytes(),
|
||||
}
|
||||
if pa.Symlink != "" {
|
||||
fragment.SymlinkFile = pa.Symlink
|
||||
}
|
||||
if isWindows {
|
||||
fragment.FilePath = filepath.ToSlash(pa.Path)
|
||||
fragment.SymlinkFile = filepath.ToSlash(fragment.SymlinkFile)
|
||||
fragment.WindowsFilePath = pa.Path
|
||||
} else {
|
||||
fragment.FilePath = pa.Path
|
||||
}
|
||||
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
// need to add 1 since line counting starts at 1
|
||||
finding.StartLine += (totalLines - linesInChunk) + 1
|
||||
finding.EndLine += (totalLines - linesInChunk) + 1
|
||||
d.AddFinding(finding)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return d.DetectScanTarget(pa)
|
||||
})
|
||||
}
|
||||
|
||||
if err := d.Sema.Wait(); err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
|
||||
return d.findings, nil
|
||||
}
|
||||
|
||||
// DetectScanTarget handles one ScanTarget: it unpacks archives recursively
|
||||
// or scans a regular file, always using VirtualPath for reporting.
|
||||
// TODO maybe find a better solution for this? relying on `scanTarget` seems off.
|
||||
func (d *Detector) DetectScanTarget(scanTarget sources.ScanTarget) error {
|
||||
// Choose display path: either VirtualPath (archive chain) or on-disk path.
|
||||
display := scanTarget.Path
|
||||
if scanTarget.VirtualPath != "" {
|
||||
display = scanTarget.VirtualPath
|
||||
}
|
||||
logger := logging.With().Str("path", display).Logger()
|
||||
logger.Trace().Msg("Scanning path")
|
||||
|
||||
// --- Archive branch: extract and reschedule children ---
|
||||
if IsArchive(scanTarget.Path) {
|
||||
logger.Info().Msg("Found archive")
|
||||
|
||||
targets, tmpdir, err := ExtractArchive(scanTarget.Path)
|
||||
if err != nil {
|
||||
logger.Warn().Err(err).Msg("Failed to extract archive")
|
||||
return nil
|
||||
}
|
||||
// Schedule each extracted file for its own scan, carrying forward VirtualPath.
|
||||
for _, t := range targets {
|
||||
t := t
|
||||
// compute path INSIDE this archive
|
||||
rel, rerr := filepath.Rel(tmpdir, t.Path)
|
||||
if rerr != nil {
|
||||
rel = filepath.Base(t.Path)
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
|
||||
// prepend existing chain or archive base name
|
||||
if scanTarget.VirtualPath != "" {
|
||||
t.VirtualPath = scanTarget.VirtualPath + "/" + rel
|
||||
} else {
|
||||
t.VirtualPath = filepath.Base(scanTarget.Path) + "/" + rel
|
||||
}
|
||||
|
||||
d.Sema.Go(func() error {
|
||||
return d.DetectScanTarget(t)
|
||||
})
|
||||
}
|
||||
|
||||
// cleanup extraction directory
|
||||
// if err := os.RemoveAll(tmpdir); err != nil {
|
||||
// logger.Warn().Err(err).Msg("Failed to remove tempdir")
|
||||
// }
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Regular file branch ---
|
||||
f, err := os.Open(scanTarget.Path)
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
logger.Warn().Msg("Skipping file: permission denied")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Skip binary files by sniffing header
|
||||
head := make([]byte, 261)
|
||||
if n, _ := io.ReadFull(f, head); n > 0 {
|
||||
if kind, _ := filetype.Match(head[:n]); kind != filetype.Unknown {
|
||||
logger.Debug().Str("kind", kind.Extension).Msg("Skipping binary")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(f)
|
||||
buf := make([]byte, chunkSize)
|
||||
totalLines := 0
|
||||
|
||||
for {
|
||||
n, err := reader.Read(buf)
|
||||
if n > 0 {
|
||||
peekBuf := bytes.NewBuffer(buf[:n])
|
||||
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
|
||||
chunk := peekBuf.String()
|
||||
linesInChunk := strings.Count(chunk, "\n")
|
||||
|
||||
// build fragment and set FilePath to our display chain
|
||||
fragment := Fragment{
|
||||
Raw: chunk,
|
||||
Bytes: peekBuf.Bytes(),
|
||||
}
|
||||
fragment.FilePath = display
|
||||
|
||||
// if this file was itself a symlink
|
||||
if scanTarget.Symlink != "" {
|
||||
fragment.SymlinkFile = scanTarget.Symlink
|
||||
}
|
||||
if isWindows {
|
||||
fragment.WindowsFilePath = scanTarget.Path
|
||||
}
|
||||
|
||||
// run detection and adjust line numbers
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
finding.StartLine += totalLines + 1
|
||||
finding.EndLine += totalLines + 1
|
||||
|
||||
// We have to augment the finding if the source is coming
|
||||
// from a archive committed in Git
|
||||
if scanTarget.Source == "github-archive" {
|
||||
finding.Author = scanTarget.GitInfo.Author
|
||||
finding.Commit = scanTarget.GitInfo.Commit
|
||||
finding.Email = scanTarget.GitInfo.Email
|
||||
finding.Date = scanTarget.GitInfo.Date
|
||||
finding.Message = scanTarget.GitInfo.Message
|
||||
}
|
||||
|
||||
d.AddFinding(finding)
|
||||
}
|
||||
totalLines += linesInChunk
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
+57
-7
@@ -5,9 +5,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
|
||||
@@ -32,13 +35,6 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
|
||||
diffFilesCh = nil
|
||||
break
|
||||
}
|
||||
|
||||
// skip binary files
|
||||
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if commit is allowed
|
||||
commitSHA := ""
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
@@ -47,6 +43,60 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if IsArchive(gitdiffFile.NewName) {
|
||||
// Check if commit is allowed
|
||||
d.Sema.Go(func() error {
|
||||
// Check out the archive blob to disk
|
||||
archivePath, err := cmd.CheckoutBlob(commitSHA, gitdiffFile.NewName)
|
||||
if err != nil {
|
||||
logging.Warn().Err(err).Str("file", gitdiffFile.NewName).Msg("failed to checkout blob")
|
||||
return nil
|
||||
}
|
||||
defer os.Remove(archivePath)
|
||||
|
||||
targets, tmpDir, err := ExtractArchive(archivePath)
|
||||
if err != nil {
|
||||
os.RemoveAll(tmpDir)
|
||||
logging.Warn().Err(err).Msg("failed to extract archive")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Scan each extracted file just as you would in directory mode
|
||||
for _, t := range targets {
|
||||
// build the “inside-archive” path
|
||||
rel, _ := filepath.Rel(tmpDir, t.Path)
|
||||
rel = filepath.ToSlash(rel)
|
||||
// chain onto any existing VirtualPath (nested archives)
|
||||
if t.VirtualPath != "" {
|
||||
t.VirtualPath = t.VirtualPath + "/" + rel
|
||||
} else {
|
||||
t.VirtualPath = filepath.Base(gitdiffFile.NewName) + "/" + rel
|
||||
}
|
||||
|
||||
// TODO this isn't a great solution, and it would be nice to
|
||||
// have a better way to handle this.
|
||||
// update taget to include git information:
|
||||
t.Source = "github-archive"
|
||||
t.GitInfo.Author = gitdiffFile.PatchHeader.Author.Name
|
||||
t.GitInfo.Commit = commitSHA
|
||||
|
||||
t.GitInfo.Date = gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
|
||||
t.GitInfo.Message = gitdiffFile.PatchHeader.Message()
|
||||
t.GitInfo.Email = gitdiffFile.PatchHeader.Author.Email
|
||||
|
||||
d.DetectScanTarget(t)
|
||||
}
|
||||
os.RemoveAll(tmpDir)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// skip binary files
|
||||
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
|
||||
continue
|
||||
}
|
||||
|
||||
d.addCommit(commitSHA)
|
||||
|
||||
d.Sema.Go(func() error {
|
||||
|
||||
Reference in new issue
Block a user