Compare commits

..
2 Commits
Author SHA1 Message Date
Zachary Rice fe0778828e Create index.md 2021-11-19 08:34:24 -06:00
Zachary Rice 655ae6a957 Set theme jekyll-theme-minimal 2021-11-19 08:33:55 -06:00
8 changed files with 38 additions and 350 deletions

No files matched your search

-26
View File
@@ -1,26 +0,0 @@
# GitLeaks
#### Check git repos for secrets and keys
##### Features:
* Search all commits on all branches in topological order
* Regex/Entropy checks
##### Installing:
```
$ go get github.com/zricethezav/gitleaks
```
##### Usage and Explanation:
![Alt Text](https://github.com/zricethezav/gifs/blob/master/gitleaks.gif)
```
$ ./gitleaks {git url}
```
This will clone the target `{git url}` and run a diff on all commits. A report will be output to `{repo_name}.json`
Gitleaks scans all lines of all commit diffs and checks if there are any regular expression matches. The regexs are defined in `main.go`. For example if a line in a commit diff like `AWS_KEY='AKAI...'` exists then the value after the assignment operator will be checked for entropy. If the value is above a certain entropy threshold then we assume that the line contains a key/secret. Work largely based on https://people.eecs.berkeley.edu/~rohanpadhye/files/key_leaks-msr15.pdf
#### TODO
- Specify a target branch
- Support for custom regex
- Filter regex
- Modify entropy cutoff
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-minimal
-54
View File
@@ -1,54 +0,0 @@
package main
import (
"github.com/nbutton23/zxcvbn-go"
"strings"
)
// check each line of a diff and see if there are any potential secrets
// [1] https://people.eecs.berkeley.edu/~rohanpadhye/files/key_leaks-msr15.pdf
func checkRegex(diff string) []string {
var match string
var results []string
lines := strings.Split(diff, "\n")
for _, line := range lines {
// doubtful a leak would be on a line > 120 characters
if len(line) == 0 || len(line) > 120 {
continue
}
for _, re := range regexes {
match = re.FindString(line)
if len(match) == 0 {
continue
}
results = append(results, line)
}
}
return results
}
// checkEntropy determines whether target contains enough
// entropy for a hash
// TODO remove stop words:
// setting(s), config(s), property(s), etc
func checkEntropy(target string) bool {
index := assignRegex.FindStringIndex(target)
if len(index) == 0 {
return false
}
// TODO check for stop words here
target = strings.Trim(target[index[1]:len(target)], " ")
if len(target) > 70 {
return false
}
entropy := zxcvbn.PasswordStrength(target, nil).Entropy
// tune this/make option
if entropy > 70 {
return true
}
return false
}
-46
View File
@@ -1,46 +0,0 @@
package main
import (
"testing"
)
func TestCheckRegex(t *testing.T) {
var secretsPresent bool
var results []string
checks := map[string]bool{
"github.com": false,
"github.com/user/": false,
"github.com/user -- Sys": false,
"github_api_client = \"sample key\"": true,
"aws=\"afewafewafewafewaf\"": true,
"aws\"afewafewafewafewaf\"": false,
"heroku := \"afewafewafewafewaf\"": true,
"heroku_client_secret := \"afewafewafewafewaf\"": true,
"reddit_api_secreit = \"Fwe4fa431FgklreF\"": true,
}
for k, v := range checks {
results, secretsPresent = checkRegex(k)
if v != secretsPresent {
t.Errorf("regexCheck failed on string %s. Expected secretsPresent: %t, got %t, %v", k, v, secretsPresent, results)
}
}
}
func TestEntropy(t *testing.T) {
var enoughEntropy bool
checks := map[string]bool{
"heroku_client_secret = settings.HEROKU_CLIENT": false,
"heroku_client_secret = conf.heroku": false,
"reddit_secret = settings.REDDIT_API": false,
"reddit_api_secret = \"Fwe4fa431FgklreF\"": true,
"aws_secret= \"AKIAIMNOJVGFDXXXE4OA\"": true,
}
for k, v := range checks {
enoughEntropy = checkEntropy(k)
if v != enoughEntropy {
t.Errorf("checkEntropy failed for %s. Expected %t, got %t", k, v, enoughEntropy)
}
}
}
+37
View File
@@ -0,0 +1,37 @@
## Welcome to GitHub Pages
You can use the [editor on GitHub](https://github.com/zricethezav/gitleaks/edit/gh-pages/index.md) to maintain and preview the content for your website in Markdown files.
Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
### Markdown
Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for
```markdown
Syntax highlighted code block
# Header 1
## Header 2
### Header 3
- Bulleted
- List
1. Numbered
2. List
**Bold** and _Italic_ and `Code` text
[Link](url) and ![Image](src)
```
For more details see [Basic writing and formatting syntax](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax).
### Jekyll Themes
Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/zricethezav/gitleaks/settings/pages). The name of this theme is saved in the Jekyll `_config.yml` configuration file.
### Support or Contact
Having trouble with Pages? Check out our [documentation](https://docs.github.com/categories/github-pages-basics/) or [contact support](https://support.github.com/contact) and we’ll help you sort it out.
-119
View File
@@ -1,119 +0,0 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
)
type LeakElem struct {
Line string `json:"line"`
Commit string `json:"commit"`
}
func start(opts *Options, repoUrl string) {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
err := exec.Command("git", "clone", repoUrl).Run()
if err != nil {
log.Fatalf("failed to clone repo %v", err)
}
repoName := strings.Split(repoUrl, "/")[4]
if err := os.Chdir(repoName); err != nil {
log.Fatal(err)
}
go func() {
<-c
cleanup(repoName)
os.Exit(1)
}()
report := getLeaks(repoName)
cleanup(repoName)
reportJson, _ := json.MarshalIndent(report, "", "\t")
err = ioutil.WriteFile(fmt.Sprintf("%s_leaks.json", repoName), reportJson, 0644)
}
func cleanup(repoName string) {
if err := os.Chdir(appRoot); err != nil {
log.Fatalf("failed cleaning up repo. Does the repo exist? %v", err)
}
err := exec.Command("rm", "-rf", repoName).Run()
if err != nil {
log.Fatal(err)
}
}
func getLeaks(repoName string) []LeakElem {
var (
out []byte
err error
commitWG sync.WaitGroup
gitLeakReceiverWG sync.WaitGroup
concurrent = 100
semaphoreChan = make(chan struct{}, concurrent)
gitLeaks = make(chan LeakElem)
report []LeakElem
)
go func(commitWG *sync.WaitGroup, gitLeakReceiverWG *sync.WaitGroup) {
for gitLeak := range gitLeaks {
fmt.Println(gitLeak)
report = append(report, gitLeak)
gitLeakReceiverWG.Done()
}
}(&commitWG, &gitLeakReceiverWG)
out, err = exec.Command("git", "rev-list", "--all", "--remotes", "--topo-order").Output()
if err != nil {
log.Fatalf("error retrieving commits%v\n", err)
}
commits := bytes.Split(out, []byte("\n"))
commitWG.Add(len(commits))
for _, currCommitB := range commits {
currCommit := string(currCommitB)
go func(currCommit string, repoName string, commitWG *sync.WaitGroup, gitLeakReceiverWG *sync.WaitGroup) {
defer commitWG.Done()
var leakPrs bool
if err := os.Chdir(fmt.Sprintf("%s/%s", appRoot, repoName)); err != nil {
log.Fatal(err)
}
commitCmp := fmt.Sprintf("%s^!", currCommit)
semaphoreChan <- struct{}{}
out, err := exec.Command("git", "diff", commitCmp).Output()
<-semaphoreChan
if err != nil {
return
}
lines := checkRegex(string(out))
if len(lines) == 0 {
return
}
for _, line := range lines {
leakPrs = checkEntropy(line)
if leakPrs {
gitLeakReceiverWG.Add(1)
gitLeaks <- LeakElem{line, currCommit}
}
}
}(currCommit, repoName, &commitWG, &gitLeakReceiverWG)
}
commitWG.Wait()
gitLeakReceiverWG.Wait()
return report
}
-36
View File
@@ -1,36 +0,0 @@
package main
import (
"os"
"regexp"
)
var (
appRoot string
regexes map[string]*regexp.Regexp
assignRegex *regexp.Regexp
)
func init() {
appRoot, _ = os.Getwd()
// TODO update regex to look for things like:
// TODO ability to add/filter regex
// client("AKAI32fJ334...",
regexes = map[string]*regexp.Regexp{
"github": regexp.MustCompile(`[g|G][i|I][t|T][h|H][u|U][b|B].*(=|:|:=|<-).*\w+.*`),
"aws": regexp.MustCompile(`[a|A][w|W][s|S].*(=|:=|:|<-).*\w+.*`),
"heroku": regexp.MustCompile(`[h|H][e|E][r|R][o|O][k|K][u|U].*(=|:=|:|<-).*\w+.*`),
"facebook": regexp.MustCompile(`[f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*(=|:=|:|<-).*\w+.*`),
"twitter": regexp.MustCompile(`[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*(=|:=|:|<-).*\w+.*`),
"reddit": regexp.MustCompile(`[r|R][e|E][d|D][d|D][i|I][t|T].*(=|:=|:|<-).*\w+.*`),
"twilio": regexp.MustCompile(`[t|T][w|W][i|I][l|L][i|I][o|O].*(=|:=|:|<-).*\w+.*`),
}
assignRegex = regexp.MustCompile(`(=|:|:=|<-)`)
}
func main() {
args := os.Args[2:]
repoUrl := os.Args[1]
opts := parseOptions(args, repoUrl)
start(opts, repoUrl)
}
-69
View File
@@ -1,69 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
// TODO regex on type.. user/organization can be treated as the same:
// hittps://github.com/<user or org>
// hittps://github.com/<user or org>/repo
const usage = `usage: gitleaks [git link] [options]
Options:
-c Concurrency factor (potential number of git files open)
-h --help Display this message
`
type Options struct {
Concurrency int
}
func help() {
os.Stderr.WriteString(usage)
os.Exit(1)
}
func optionsNextInt(args []string, i *int) int {
if len(args) > *i+1 {
*i++
} else {
help()
}
argInt, err := strconv.Atoi(args[*i])
if err != nil {
fmt.Printf("Invalid %s option: %s\n", args[*i-1], args[*i])
help()
}
return argInt
}
func optionsNextString(args []string, i *int) string {
if len(args) > *i+1 {
*i++
} else {
help()
}
return args[*i]
}
func parseOptions(args []string, repoUrl string) *Options {
opts := &Options{}
for i := 0; i < len(args); i++ {
arg := args[i]
switch arg {
case "-c":
opts.Concurrency = optionsNextInt(args, &i)
case "-h", "--help":
help()
return nil
default:
fmt.Printf("Uknown option %s\n\n", arg)
help()
return nil
}
}
return opts
}