go mod and even more work

This commit is contained in:
zach rice committed 2019-03-27 17:26:27 -05:00
1 parent 1c14586cde
commit e79ffc6ae8
62 files changed
+1003 -8132

No files matched your search

+226
View File
@@ -0,0 +1,226 @@
package gitleaks
import (
"fmt"
"os"
"os/user"
"regexp"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
type entropyRange struct {
v1 float64
v2 float64
}
type Regex struct {
description string
regex *regexp.Regexp
}
// TomlConfig is used for loading gitleaks configs from a toml file
type TomlConfig struct {
Regexes []struct {
Description string
Regex string
}
Entropy struct {
LineRegexes []string
}
Whitelist struct {
Files []string
Regexes []string
Commits []string
Repos []string
}
Misc struct {
Entropy []string
}
}
// Config contains gitleaks config
type Config struct {
Regexes []Regex
WhiteList struct {
regexes []*regexp.Regexp
files []*regexp.Regexp
commits map[string]bool
repos []*regexp.Regexp
}
Entropy struct {
entropyRanges []*entropyRange
regexes []*regexp.Regexp
}
sshAuth *ssh.PublicKeys
}
// loadToml loads of the toml config containing regexes and whitelists.
// This function will first look if the configPath is set and load the config
// from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
// env var. If that is not set, then gitleaks will continue with the default configs
// specified by the const var at the top `defaultConfig`
func newConfig() (*Config, error) {
var (
tomlConfig TomlConfig
configPath string
config Config
)
if opts.ConfigPath != "" {
configPath = opts.ConfigPath
_, err := os.Stat(configPath)
if err != nil {
return nil, fmt.Errorf("no gitleaks config at %s", configPath)
}
} else {
configPath = os.Getenv("GITLEAKS_CONFIG")
}
if configPath != "" {
if _, err := toml.DecodeFile(configPath, &tomlConfig); err != nil {
return nil, fmt.Errorf("problem loading config: %v", err)
}
} else {
_, err := toml.Decode(defaultConfig, &tomlConfig)
if err != nil {
return nil, fmt.Errorf("problem loading default config: %v", err)
}
}
sshAuth, err := getSSHAuth()
if err != nil {
return nil, err
}
config.sshAuth = sshAuth
err = config.update(tomlConfig)
if err != nil {
return nil, err
}
return &config, err
}
// updateConfig will update a the global config values
func (config *Config) update(tomlConfig TomlConfig) error {
if len(tomlConfig.Misc.Entropy) != 0 {
err := config.updateEntropyRanges(tomlConfig.Misc.Entropy)
if err != nil {
return err
}
}
for _, regex := range tomlConfig.Entropy.LineRegexes {
config.Entropy.regexes = append(config.Entropy.regexes, regexp.MustCompile(regex))
}
if singleSearchRegex != nil {
config.Regexes = append(config.Regexes, Regex{
description: "single search",
regex: singleSearchRegex,
})
} else {
for _, regex := range tomlConfig.Regexes {
config.Regexes = append(config.Regexes, Regex{
description: regex.Description,
regex: regexp.MustCompile(regex.Regex),
})
}
}
config.WhiteList.commits = make(map[string]bool)
for _, commit := range tomlConfig.Whitelist.Commits {
config.WhiteList.commits[commit] = true
}
for _, regex := range tomlConfig.Whitelist.Files {
config.WhiteList.files = append(config.WhiteList.files, regexp.MustCompile(regex))
}
for _, regex := range tomlConfig.Whitelist.Regexes {
config.WhiteList.regexes = append(config.WhiteList.regexes, regexp.MustCompile(regex))
}
for _, regex := range tomlConfig.Whitelist.Repos {
config.WhiteList.repos = append(config.WhiteList.repos, regexp.MustCompile(regex))
}
return nil
}
// entropyRanges hydrates entropyRanges which allows for fine tuning entropy checking
func (config *Config) updateEntropyRanges(entropyLimitStr []string) error {
for _, span := range entropyLimitStr {
split := strings.Split(span, "-")
v1, err := strconv.ParseFloat(split[0], 64)
if err != nil {
return err
}
v2, err := strconv.ParseFloat(split[1], 64)
if err != nil {
return err
}
if v1 > v2 {
return fmt.Errorf("entropy range must be ascending")
}
r := &entropyRange{
v1: v1,
v2: v2,
}
if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
}
config.Entropy.entropyRanges = append(config.Entropy.entropyRanges, r)
}
return nil
}
// externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
// from a remote or local repo. Use the --repo-config option to trigger this.
func (config *Config) updateFromRepo(repo *RepoDescriptor) error {
var tomlConfig TomlConfig
wt, err := repo.repository.Worktree()
if err != nil {
return err
}
f, err := wt.Filesystem.Open(".gitleaks.toml")
if err != nil {
return err
}
if _, err := toml.DecodeReader(f, &config); err != nil {
return fmt.Errorf("problem loading config: %v", err)
}
f.Close()
if err != nil {
return err
}
return config.update(tomlConfig)
}
// getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
// If --ssh-key is set then it will attempt to load the key from that path. If not,
// gitleaks will use the default $HOME/.ssh/id_rsa key
func getSSHAuth() (*ssh.PublicKeys, error) {
var (
sshKeyPath string
)
if opts.SSHKey != "" {
sshKeyPath = opts.SSHKey
} else {
// try grabbing default
c, err := user.Current()
if err != nil {
return nil, nil
}
sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
}
sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
if err != nil {
if strings.HasPrefix(opts.Repo, "git") {
// if you are attempting to clone a git repo via ssh and supply a bad ssh key,
// the clone will fail.
return nil, fmt.Errorf("unable to generate ssh key: %v", err)
}
}
return sshAuth, nil
}
+1
View File
@@ -0,0 +1 @@
package gitleaks
+77
View File
@@ -0,0 +1,77 @@
package gitleaks
const version = "1.24.0"
const defaultGithubURL = "https://api.github.com/"
const defaultThreadNum = 1
const errExit = 2
const leakExit = 1
const defaultConfig = `
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
# configurations from that path. Gitleaks does not whitelist anything by default.
title = "gitleaks config"
# add regexes to the regex table
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
description = "PKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
description = "PGP"
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Twitter"
regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
[[regexes]]
description = "Github"
regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
[entropy]
lineregexes = [
"api",
"key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
[whitelist]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
#commits = [
# "BADHA5H1",
# "BADHA5H2",
#]
#repos = [
# "mygoodrepo"
#]
[misc]
#entropy = [
# "3.3-4.30"
# "6.0-8.0
#]
`
+141
View File
@@ -0,0 +1,141 @@
package gitleaks
import (
"io/ioutil"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/google/go-github/github"
"github.com/hako/durafmt"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
// Leak represents a leaked secret or regex match.
type Leak struct {
Line string `json:"line"`
Commit string `json:"commit"`
Offender string `json:"offender"`
Type string `json:"reason"`
Message string `json:"commitMsg"`
Author string `json:"author"`
File string `json:"file"`
Repo string `json:"repo"`
Date time.Time `json:"date"`
}
type gitDiff struct {
content string
commit *object.Commit
filePath string
repoName string
githubCommit *github.RepositoryCommit
sha string
message string
author string
date time.Time
}
var (
opts *Options
config *Config
singleSearchRegex *regexp.Regexp
dir string
threads int
totalCommits int64
commitMap = make(map[string]bool)
cMutex = &sync.Mutex{}
auditDone bool
)
func init() {
log.SetOutput(os.Stdout)
threads = defaultThreadNum
}
// Run is the entry point for gitleaks
func Run() {
var (
leaks []Leak
err error
)
opts, err = setupOpts()
if err != nil {
log.Fatal(err)
}
config, err = newConfig()
if err != nil {
log.Fatal(err)
}
now := time.Now()
if opts.Disk {
// temporary directory where all the gitleaks plain clones will reside
dir, err = ioutil.TempDir("", "gitleaks")
defer os.RemoveAll(dir)
if err != nil {
goto postAudit
}
}
// start audits
if opts.Repo != "" || opts.RepoPath != "" {
repoD, err := newRepoD()
if err != nil {
goto postAudit
}
err = repoD.clone()
if err != nil {
goto postAudit
}
leaks, err = repoD.audit()
} else if opts.OwnerPath != "" {
repoDs, err := discoverRepos(opts.OwnerPath)
if err != nil {
goto postAudit
}
for _, repoD := range repoDs {
err = repoD.clone()
if err != nil {
continue
}
leaksFromRepo, err := repoD.audit()
if err != nil {
log.Warnf("error occured auditing repo: %s, continuing", repoD.name)
}
leaks = append(leaksFromRepo, leaks...)
}
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
leaks, err = auditGithubRepos()
} else if opts.GitLabOrg != "" || opts.GitLabUser != "" {
leaks, err = auditGitlabRepos()
} else if opts.GithubPR != "" {
leaks, err = auditGithubPR()
}
postAudit:
if err != nil {
if strings.Contains(err.Error(), "whitelisted") {
log.Info(err.Error())
os.Exit(0)
}
log.Error(err)
os.Exit(errExit)
}
if opts.Report != "" {
writeReport(leaks)
}
if len(leaks) != 0 {
log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
os.Exit(leakExit)
} else {
log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
}
}
+51
View File
@@ -0,0 +1,51 @@
package gitleaks
import "math"
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
func getShannonEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
charCounts := make(map[rune]int)
for _, char := range data {
charCounts[char]++
}
invLength := 1.0 / float64(len(data))
for _, count := range charCounts {
freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
}
func entropyIsHighEnough(entropy float64) bool {
if entropy >= opts.Entropy && len(config.Entropy.entropyRanges) == 0 {
return true
}
for _, eR := range config.Entropy.entropyRanges {
if entropy > eR.v1 && entropy < eR.v2 {
return true
}
}
return false
}
func highEntropyLineIsALeak(line string) bool {
if !opts.NoiseReduction {
return true
}
for _, re := range config.Entropy.regexes {
if re.FindString(line) != "" {
return true
}
}
return false
}
+269
View File
@@ -0,0 +1,269 @@
package gitleaks
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/google/go-github/github"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
git "gopkg.in/src-d/go-git.v4"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
var githubPages = 100
// auditPR audits a single github PR
func auditGithubPR() ([]Leak, error) {
var leaks []Leak
ctx := context.Background()
githubClient := github.NewClient(githubToken())
splits := strings.Split(opts.GithubPR, "/")
owner := splits[len(splits)-4]
repo := splits[len(splits)-3]
prNum, err := strconv.Atoi(splits[len(splits)-1])
if err != nil {
return nil, err
}
page := 1
for {
commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
PerPage: githubPages,
Page: page,
})
if err != nil {
return leaks, err
}
for _, commit := range commits {
totalCommits = totalCommits + 1
commit, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *commit.SHA)
if err != nil {
continue
}
files := commit.Files
for _, f := range files {
skipFile := false
if f.Patch == nil || f.Filename == nil {
continue
}
for _, re := range config.WhiteList.files {
if re.FindString(f.GetFilename()) != "" {
log.Infof("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.GetFilename())
skipFile = true
break
}
}
if skipFile {
continue
}
diff := gitDiff{
sha: commit.GetSHA(),
content: *f.Patch,
filePath: *f.Filename,
repoName: repo,
githubCommit: commit,
author: commit.GetCommitter().GetLogin(),
message: *commit.Commit.Message,
date: *commit.Commit.Committer.Date,
}
leaks = append(leaks, inspect(diff)...)
}
}
page = resp.NextPage
if resp.LastPage == 0 {
break
}
}
return leaks, nil
}
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
func auditGithubRepos() ([]Leak, error) {
var (
err error
githubRepos []*github.Repository
pagedGithubRepos []*github.Repository
resp *github.Response
githubOrgOptions *github.RepositoryListByOrgOptions
githubOptions *github.RepositoryListOptions
done bool
leaks []Leak
ownerDir string
)
ctx := context.Background()
githubClient := github.NewClient(githubToken())
if opts.GithubOrg != "" {
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL
}
githubOrgOptions = &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 100},
}
} else if opts.GithubUser != "" {
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL
}
githubOptions = &github.RepositoryListOptions{
Affiliation: "owner",
ListOptions: github.ListOptions{
PerPage: 100,
},
}
}
for {
if done {
break
}
if opts.GithubUser != "" {
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
if err != nil {
done = true
}
githubOptions.Page = resp.NextPage
githubRepos = append(githubRepos, pagedGithubRepos...)
if resp.NextPage == 0 {
done = true
}
} else if opts.GithubOrg != "" {
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
if err != nil {
done = true
}
githubOrgOptions.Page = resp.NextPage
githubRepos = append(githubRepos, pagedGithubRepos...)
if resp.NextPage == 0 {
done = true
}
}
if opts.Log == "Debug" || opts.Log == "debug" {
for _, githubRepo := range pagedGithubRepos {
log.Debugf("staging repos %s", *githubRepo.Name)
}
}
}
if opts.Disk {
ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
}
for _, githubRepo := range githubRepos {
repoD, err := cloneGithubRepo(githubRepo)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoD.audit()
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", *githubRepo.Name)
} else {
log.Warnf("leaks found for repo %s", *githubRepo.Name)
}
if err != nil {
log.Warn(err)
}
leaks = append(leaks, leaksFromRepo...)
}
return leaks, nil
}
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
// will be cloned to disk if --disk is set.
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
var (
repo *git.Repository
err error
)
githubToken := os.Getenv("GITHUB_TOKEN")
if opts.ExcludeForks && githubRepo.GetFork() {
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
}
for _, re := range config.WhiteList.repos {
if re.FindString(*githubRepo.Name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
}
}
log.Infof("cloning: %s", *githubRepo.Name)
if opts.Disk {
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
if err != nil {
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if config.sshAuth != nil && githubToken == "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: config.sshAuth,
})
} else if githubToken != "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
})
}
} else {
if config.sshAuth != nil && githubToken == "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: config.sshAuth,
})
} else if githubToken != "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
})
}
}
if err != nil {
return nil, err
}
return &RepoDescriptor{
repository: repo,
name: *githubRepo.Name,
}, nil
}
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
// if you are running audits with --github-user or --github-org
func githubToken() *http.Client {
githubToken := os.Getenv("GITHUB_TOKEN")
if githubToken == "" {
return nil
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
return oauth2.NewClient(context.Background(), ts)
}
+164
View File
@@ -0,0 +1,164 @@
package gitleaks
import (
"fmt"
"io/ioutil"
"os"
log "github.com/sirupsen/logrus"
"github.com/xanzy/go-gitlab"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// gitlabPages number of records per request
const gitlabPages = 100
// auditGitlabRepos kicks off audits if --gitlab-user or --gitlab-org options are set.
// Getting all repositories from the GitLab API and run audit. If an error occurs during an audit of a repo,
// that error is logged.
func auditGitlabRepos() ([]Leak, error) {
var (
ps []*gitlab.Project
resp *gitlab.Response
leaks []Leak
tempDir string
err error
)
repos := make([]*gitlab.Project, 0, gitlabPages)
page := 1
cl := gitlab.NewClient(nil, os.Getenv("GITLAB_TOKEN"))
// if self hosted GitLab server
if url := os.Getenv("GITLAB_URL"); url != "" {
cl.SetBaseURL(url)
}
for {
if opts.GitLabOrg != "" {
opt := &gitlab.ListGroupProjectsOptions{
ListOptions: gitlab.ListOptions{
PerPage: gitlabPages,
Page: page,
},
}
ps, resp, err = cl.Groups.ListGroupProjects(opts.GitLabOrg, opt)
} else if opts.GitLabUser != "" {
opt := &gitlab.ListProjectsOptions{
ListOptions: gitlab.ListOptions{
PerPage: gitlabPages,
Page: page,
},
}
ps, resp, err = cl.Projects.ListUserProjects(opts.GitLabUser, opt)
}
if err != nil {
log.Fatal("error listing projects: ", err) // exit when can't make API call
}
repos = append(repos, ps...)
if page >= resp.TotalPages {
break // exit when we've seen all pages
}
page = resp.NextPage
}
log.Debugf("found projects: %d", len(repos))
if opts.Disk {
if tempDir, err = createGitlabTempDir(); err != nil {
log.Fatal("error creating temp directory: ", err)
}
}
for _, p := range repos {
repoD, err := cloneGitlabRepo(tempDir, p)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoD.audit()
if err != nil {
log.Warn(err)
}
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%d", tempDir, p.ID))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", p.Name)
} else {
log.Warnf("leaks found for repo %s", p.Name)
}
leaks = append(leaks, leaksFromRepo...)
}
return leaks, nil
}
func createGitlabTempDir() (string, error) {
pathName := opts.GitLabUser
if opts.GitLabOrg != "" {
pathName = opts.GitLabOrg
}
os.RemoveAll(fmt.Sprintf("%s/%s", dir, pathName))
ownerDir, err := ioutil.TempDir(dir, pathName)
if err != nil {
return "", err
}
return ownerDir, nil
}
func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*RepoDescriptor, error) {
var (
repo *git.Repository
err error
)
if opts.ExcludeForks && p.ForkedFromProject != nil {
return nil, fmt.Errorf("skipping %s, excluding forks", p.Name)
}
for _, re := range config.WhiteList.repos {
if re.FindString(p.Name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", p.Name)
}
}
opt := &git.CloneOptions{
URL: p.HTTPURLToRepo,
}
if config.sshAuth != nil {
opt.URL = p.SSHURLToRepo
opt.Auth = config.sshAuth
}
log.Infof("cloning: %s", p.Name)
if opts.Disk {
repo, err = git.PlainClone(fmt.Sprintf("%s/%d", tempDir, p.ID), false, opt)
} else {
repo, err = git.Clone(memory.NewStorage(), nil, opt)
}
if err != nil {
return nil, err
}
return &RepoDescriptor{
repository: repo,
name: p.Name,
}, nil
}
+169
View File
@@ -0,0 +1,169 @@
package gitleaks
import (
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
)
// Options for gitleaks
type Options struct {
// remote target options
Repo string `short:"r" long:"repo" description:"Repo url to audit"`
GithubUser string `long:"github-user" description:"Github user to audit"`
GithubOrg string `long:"github-org" description:"Github organization to audit"`
GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
GitLabUser string `long:"gitlab-user" description:"GitLab user ID to audit"`
GitLabOrg string `long:"gitlab-org" description:"GitLab group ID to audit"`
CommitStop string `long:"commit-stop" description:"sha of commit to stop at"`
Commit string `long:"commit" description:"sha of commit to audit"`
Depth int64 `long:"depth" description:"maximum commit depth"`
// local target option
RepoPath string `long:"repo-path" description:"Path to repo"`
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
// Process options
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
ConfigPath string `long:"config" description:"path to gitleaks config"`
SSHKey string `long:"ssh-key" description:"path to ssh key"`
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
// Output options
Log string `short:"l" long:"log" description:"log level"`
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
Version bool `long:"version" description:"version number"`
SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
}
func setupOpts() (*Options, error) {
var opts Options
parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
}
}
if len(os.Args) == 1 {
// TODO: this will be a feature, check locally
parser.WriteHelp(os.Stdout)
os.Exit(0)
}
if opts.Version {
fmt.Println(version)
os.Exit(0)
}
if opts.SampleConfig {
fmt.Println(defaultConfig)
os.Exit(0)
}
opts.setLogs()
err = opts.guard()
if err != nil {
return nil, err
}
return &opts, err
}
// optsGuard prevents invalid options
func (opts *Options) guard() error {
var err error
if opts.GithubOrg != "" && opts.GithubUser != "" {
return fmt.Errorf("github user and organization set")
} else if opts.GithubOrg != "" && opts.OwnerPath != "" {
return fmt.Errorf("github organization set and local owner path")
} else if opts.GithubUser != "" && opts.OwnerPath != "" {
return fmt.Errorf("github user set and local owner path")
}
if opts.Threads > runtime.GOMAXPROCS(0) {
return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
}
// do the URL Parse and error checking here, so we can skip it later
// empty string is OK, it will default to the public github URL.
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
if !strings.HasSuffix(opts.GithubURL, "/") {
opts.GithubURL += "/"
}
ghURL, err := url.Parse(opts.GithubURL)
if err != nil {
return err
}
tcpPort := "443"
if ghURL.Scheme == "http" {
tcpPort = "80"
}
timeout := time.Duration(1 * time.Second)
_, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
if err != nil {
return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
}
}
if opts.SingleSearch != "" {
singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
if err != nil {
return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
}
}
if opts.Entropy > 8 {
return fmt.Errorf("The maximum level of entropy is 8")
}
if opts.Report != "" {
if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
return fmt.Errorf("Report should be a .json or .csv file")
}
dirPath := filepath.Dir(opts.Report)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return fmt.Errorf("%s does not exist", dirPath)
}
}
return nil
}
// setLogLevel sets log level for gitleaks. Default is Warning
func (opts *Options) setLogs() {
switch opts.Log {
case "info":
log.SetLevel(log.InfoLevel)
case "debug":
log.SetLevel(log.DebugLevel)
case "warn":
log.SetLevel(log.WarnLevel)
default:
log.SetLevel(log.InfoLevel)
}
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
}
+319
View File
@@ -0,0 +1,319 @@
package gitleaks
import (
"crypto/md5"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
log "github.com/sirupsen/logrus"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
diffType "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// RepoDescriptor contains a src-d git repository and other data about the repo
type RepoDescriptor struct {
path string
url string
name string
repository *git.Repository
err error
}
func newRepoD() (*RepoDescriptor, error) {
for _, re := range config.WhiteList.repos {
if re.FindString(opts.Repo) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
}
}
return &RepoDescriptor{
path: opts.RepoPath,
url: opts.Repo,
name: filepath.Base(opts.Repo),
}, nil
}
func (repoD *RepoDescriptor) clone() error {
var (
err error
repo *git.Repository
)
// check if cloning to disk
if opts.Disk {
log.Infof("cloning %s to disk", opts.Repo)
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
if strings.HasPrefix(opts.Repo, "git") {
// private
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
// non-private
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
} else if repoD.path != "" {
log.Infof("opening %s", opts.RepoPath)
repo, err = git.PlainOpen(repoD.path)
} else {
// cloning to memory
log.Infof("cloning %s", opts.Repo)
if strings.HasPrefix(opts.Repo, "git") {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
}
repoD.repository = repo
repoD.err = err
return err
}
func (repoD *RepoDescriptor) audit() ([]Leak, error) {
var (
err error
leaks []Leak
)
for _, re := range config.WhiteList.repos {
if re.FindString(repoD.name) != "" {
return leaks, fmt.Errorf("skipping %s, whitelisted", repoD.name)
}
}
// check if target contains an external gitleaks toml
if opts.RepoConfig {
err := config.updateFromRepo(repoD)
if err != nil {
return leaks, nil
}
}
// clear commit cache
commitMap = make(map[string]bool)
refs, err := repoD.repository.Storer.IterReferences()
if err != nil {
return leaks, err
}
err = refs.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().IsTag() {
return nil
}
branchLeaks := repoD.auditRef(ref)
for _, leak := range branchLeaks {
leaks = append(leaks, leak)
}
return nil
})
return leaks, err
}
// auditGitReference beings the audit for a git reference. This function will
// traverse the git reference and audit each line of each diff.
func (repoD *RepoDescriptor) auditRef(ref *plumbing.Reference) []Leak {
var (
err error
repoName string
leaks []Leak
commitCount int64
commitWg sync.WaitGroup
mutex = &sync.Mutex{}
semaphore chan bool
)
if auditDone {
return nil
}
repoName = repoD.name
if opts.Threads != 0 {
threads = opts.Threads
}
if opts.RepoPath != "" {
threads = 1
}
semaphore = make(chan bool, threads)
cIter, err := repoD.repository.Log(&git.LogOptions{From: ref.Hash()})
if err != nil {
return nil
}
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil || (opts.Depth != 0 && commitCount == opts.Depth) || auditDone {
if commitCount == opts.Depth {
auditDone = true
}
return storer.ErrStop
}
commitCount = commitCount + 1
if config.WhiteList.commits[c.Hash.String()] {
log.Infof("skipping commit: %s\n", c.Hash.String())
return nil
}
// commits w/o parent (root of git the git ref) or option for single commit is not empty str
if len(c.ParentHashes) == 0 || opts.Commit == c.Hash.String() {
if commitMap[c.Hash.String()] {
return nil
}
if opts.Commit == c.Hash.String() {
auditDone = true
}
cMutex.Lock()
commitMap[c.Hash.String()] = true
cMutex.Unlock()
totalCommits = totalCommits + 1
fIter, err := c.Files()
if err != nil {
return nil
}
err = fIter.ForEach(func(f *object.File) error {
bin, err := f.IsBinary()
if bin || err != nil {
return nil
}
for _, re := range config.WhiteList.files {
if re.FindString(f.Name) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
return nil
}
}
content, err := f.Contents()
if err != nil {
return nil
}
diff := gitDiff{
repoName: repoName,
filePath: f.Name,
content: content,
sha: c.Hash.String(),
author: c.Author.String(),
message: strings.Replace(c.Message, "\n", " ", -1),
date: c.Author.When,
}
fileLeaks := inspect(diff)
mutex.Lock()
leaks = append(leaks, fileLeaks...)
mutex.Unlock()
return nil
})
return nil
}
// single commit
if opts.Commit != "" {
return nil
}
skipCount := false
err = c.Parents().ForEach(func(parent *object.Commit) error {
// check if we've seen this diff before
if commitMap[c.Hash.String()+parent.Hash.String()] {
return nil
}
cMutex.Lock()
commitMap[c.Hash.String()+parent.Hash.String()] = true
cMutex.Unlock()
if !skipCount {
totalCommits = totalCommits + 1
skipCount = true
}
commitWg.Add(1)
semaphore <- true
go func(c *object.Commit, parent *object.Commit) {
var (
filePath string
skipFile bool
)
defer func() {
commitWg.Done()
<-semaphore
if r := recover(); r != nil {
log.Warnf("recovering from panic on commit %s, likely large diff causing panic", c.Hash.String())
}
}()
patch, err := c.Patch(parent)
if err != nil {
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
return
}
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
skipFile = false
from, to := f.Files()
filePath = "???"
if from != nil {
filePath = from.Path()
} else if to != nil {
filePath = to.Path()
}
for _, re := range config.WhiteList.files {
if re.FindString(filePath) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
skipFile = true
break
}
}
if skipFile {
continue
}
chunks := f.Chunks()
for _, chunk := range chunks {
if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
diff := gitDiff{
repoName: repoName,
filePath: filePath,
content: chunk.Content(),
sha: c.Hash.String(),
author: c.Author.String(),
message: strings.Replace(c.Message, "\n", " ", -1),
date: c.Author.When,
}
chunkLeaks := inspect(diff)
for _, leak := range chunkLeaks {
mutex.Lock()
leaks = append(leaks, leak)
mutex.Unlock()
}
}
}
}
}(c, parent)
return nil
})
// stop audit if we are at commitStop
if c.Hash.String() == opts.CommitStop {
auditDone = true
return storer.ErrStop
}
return nil
})
commitWg.Wait()
return leaks
}
+189
View File
@@ -0,0 +1,189 @@
package gitleaks
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// writeReport writes a report to a file specified in the --report= option.
// Default format for report is JSON. You can use the --csv option to write the report as a csv
func writeReport(leaks []Leak) error {
if len(leaks) == 0 {
return nil
}
log.Infof("writing report to %s", opts.Report)
if strings.HasSuffix(opts.Report, ".csv") {
f, err := os.Create(opts.Report)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "date"})
for _, leak := range leaks {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Date.Format(time.RFC3339)})
}
w.Flush()
} else {
f, err := os.Create(opts.Report)
if err != nil {
return err
}
defer f.Close()
encoder := json.NewEncoder(f)
encoder.SetIndent("", "\t")
if _, err := f.WriteString("[\n"); err != nil {
return err
}
for i := 0; i < len(leaks); i++ {
if err := encoder.Encode(leaks[i]); err != nil {
return err
}
// for all but the last leak, seek back and overwrite the newline appended by Encode() with comma & newline
if i+1 < len(leaks) {
if _, err := f.Seek(-1, 1); err != nil {
return err
}
if _, err := f.WriteString(",\n"); err != nil {
return err
}
}
}
if _, err := f.WriteString("]"); err != nil {
return err
}
if err := f.Sync(); err != nil {
log.Error(err)
return err
}
}
return nil
}
// inspect will parse each line of the git diff's content against a set of regexes or
// a set of regexes set by the config (see gitleaks.toml for example). This function
// will skip lines that include a whitelisted regex. A list of leaks is returned.
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
func inspect(diff gitDiff) []Leak {
var (
leaks []Leak
skipLine bool
)
lines := strings.Split(diff.content, "\n")
for _, line := range lines {
skipLine = false
for _, re := range config.Regexes {
match := re.regex.FindString(line)
if match == "" {
continue
}
if skipLine = isLineWhitelisted(line); skipLine {
break
}
leaks = addLeak(leaks, line, match, re.description, diff)
}
if !skipLine && (opts.Entropy > 0 || len(config.Entropy.entropyRanges) != 0) {
words := strings.Fields(line)
for _, word := range words {
entropy := getShannonEntropy(word)
// Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
// was found above, since regex checks are expensive.
if !entropyIsHighEnough(entropy) {
continue
}
// If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
// then we can skip checking the rest of the line for high entropy words.
if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
break
}
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
}
}
}
return leaks
}
// isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
func isLineWhitelisted(line string) bool {
for _, wRe := range config.WhiteList.regexes {
whitelistMatch := wRe.FindString(line)
if whitelistMatch != "" {
return true
}
}
return false
}
// addLeak is helper for func inspect() to append leaks if found during a diff check.
func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
leak := Leak{
Line: line,
Commit: diff.sha,
Offender: offender,
Type: leakType,
Author: diff.author,
File: diff.filePath,
Repo: diff.repoName,
Message: diff.message,
Date: diff.date,
}
if opts.Redact {
leak.Offender = "REDACTED"
leak.Line = strings.Replace(line, offender, "REDACTED", -1)
}
if opts.Verbose {
leak.log()
}
leaks = append(leaks, leak)
return leaks
}
// discoverRepos walks all the children of `path`. If a child directory
// contain a .git subdirectory then that repo will be added to the list of repos returned
func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
var (
err error
repoDs []*RepoDescriptor
)
files, err := ioutil.ReadDir(ownerPath)
if err != nil {
return repoDs, err
}
for _, f := range files {
repoPath := path.Join(ownerPath, f.Name())
if f.IsDir() && containsGit(repoPath) {
repoDs = append(repoDs, &RepoDescriptor{
name: f.Name(),
path: repoPath,
})
}
}
return repoDs, err
}
func (leak Leak) log() {
b, _ := json.MarshalIndent(leak, "", " ")
fmt.Println(string(b))
}
func containsGit(repoPath string) bool {
if _, err := os.Stat(repoPath); os.IsNotExist(err) {
// path/to/whatever does not exist
return false
}
return true
}