-
Notifications
You must be signed in to change notification settings - Fork 5
/
git.go
353 lines (331 loc) · 9.11 KB
/
git.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package main
import (
"gopkg.in/libgit2/git2go.v26"
"io/ioutil"
"os"
"errors"
"encoding/json"
"net/http"
"fmt"
"strings"
"bytes"
"github.com/fatih/color"
"strconv"
)
type GitFile struct {
Name string
Filepath string
CommitId string
RepoUrl string
}
const GITHUB_API_VERSION = "application/vnd.github.v3+json"
const INVALID_PLAINTEXT_CREDS = -10
const INVALID_SSH_CREDS= -11
func gitHubPerformRequest(urlString string) ([]string, error) {
var urls = []string{}
client := &http.Client{}
req, err := http.NewRequest("GET", urlString, nil)
if err != nil {
return urls, err
}
req.Header.Set("Accept", GITHUB_API_VERSION)
//TODO: Add auth here
//req.SetBasicAuth(Github.Username, Github.AccessToken)
resp, err := client.Do(req)
if err != nil {
return urls, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
switch resp.StatusCode {
case 200:
var data []interface{}
err := json.Unmarshal(body, &data)
if err != nil {
return urls, err
}
for _, repo := range data{
url := repo.(map[string]interface{})["html_url"]
urls = append(urls, url.(string))
}
return urls, nil
case 400:
return urls, errors.New("Bad request sent to Github")
case 422:
return urls, errors.New("Invalid fields sent to Github")
case 403:
return urls, errors.New("Github API Rate Limiting detected")
case 404:
return urls, errors.New("Organization doesn't exist")
default:
return urls, errors.New(string(body))
}
return urls, nil
}
func getAllOrganizationsRepoUrls(orgName string) ([]string, error){
urlString := fmt.Sprintf("https://api.github.com/orgs/%s/repos",
orgName)
if *ignoreForkRepos{
urlString+="?type=sources" //Read Github API Documentation for details
}
urls, err := gitHubPerformRequest(urlString)
if err!= nil {
return nil, err
}
return urls, err
}
func credentialsCallback(url string, username string, allowedTypes git.CredType) (git.ErrorCode, *git.Cred) {
git_user := os.Getenv("GIT_USER")
git_pass := os.Getenv("GIT_PASS")
git_priv := os.Getenv("GIT_PRIV_KEY")
git_pub := os.Getenv("GIT_PUB_KEY")
git_passphrase := os.Getenv("GIT_PASSPHRASE")
switch *useGitCredentials{
case "ssh":
if len(git_user) == 0 || len(git_pub) ==0 || len(git_priv) == 0{
return git.ErrorCode(INVALID_SSH_CREDS), nil
}
ret, cred := git.NewCredSshKey(git_user,
git_pub,
git_priv,
git_passphrase)
return git.ErrorCode(ret), &cred
case "plaintext":
if len(git_user) == 0 || len(git_pass) == 0{
return git.ErrorCode(INVALID_PLAINTEXT_CREDS), nil
}
ret, cred := git.NewCredUserpassPlaintext(git_user, git_pass)
return git.ErrorCode(ret), &cred
default:
return git.ErrorCode(-1), nil
}
}
func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {
//TODO: Fix lol
return 0
}
func searchBlobContents(contents []byte) (bool, Pattern, string, int){
lines := bytes.Split(contents, []byte("\n"))
for _, pattern := range fileContentRegexes {
lineNumb := 0
for _, line := range lines {
lineNumb++
if pattern.Regex.Match(line) {
return true, pattern, string(line), lineNumb
}
}
}
return false, Pattern{}, "", -1
/*
This is matching on things it shouldn't
for _, pattern := range fileContentLiterals{
if bytes.Contains([]byte(pattern.Value), contents){
fmt.Println(pattern.Value)
fmt.Println(string(contents))
return true, pattern
}
}
*/
}
func gitRepoSearch(repoUrl string) ([]*Match, error){
var results = []*Match{}
files, matches, err := getRepoFilenames(repoUrl)
if err != nil {
return results, err
}
results = append(results, gitSecretFilenameLiteralSearch(files)...)
results = append(results, gitSecretFilenameRegexSearch(files)...)
results = append(results, matches...)
return results, nil
}
func getOrgRepo(url string, matchChan chan[]*Match){
matches, err := gitRepoSearch(url)
if err != nil{
color.Red(err.Error())
}
matchChan <- matches
}
func searchAllBranches(repo *git.Repository, walk *git.RevWalk) error{
itr, err := repo.NewBranchIterator(git.BranchRemote)
defer itr.Free()
if err != nil{
return err
}
var f = func(b *git.Branch, t git.BranchType) error {
walk.Push(b.Target())
return nil
}
itr.ForEach(f)
return nil
}
func getRepoFilenames(repoUrl string) ([]GitFile, []*Match, error){
var table = make(map[string]*Match)
var filenames []GitFile
var matches []*Match
dir, err := ioutil.TempDir("", "PwnDelorean")
if err != nil {
return filenames, matches, err
}
defer os.RemoveAll(dir)
cloneOptions := &git.CloneOptions{}
if len(*useGitCredentials) !=0 {
cloneOptions.FetchOptions = &git.FetchOptions{
RemoteCallbacks: git.RemoteCallbacks{
CredentialsCallback: credentialsCallback,
CertificateCheckCallback: certificateCheckCallback,
},
}
}
repo, err := git.Clone(repoUrl, dir, cloneOptions)
if err != nil {
if err.(*git.GitError).Code == INVALID_PLAINTEXT_CREDS{
return filenames, matches,
errors.New("Please check your GIT_USER and GIT_PASS Environment variables")
} else if len(*useGitCredentials) ==0 {
return filenames, matches, errors.New(
"-creds flag not in use, the repo may be private or doesn't exist")
} else {
return filenames, matches, errors.New("Git repo appears to not exist")
}
}
defer repo.Free()
head, err := repo.Head()
if err != nil{
return filenames, matches, err
}
defer head.Free()
walk, err := repo.Walk()
if err != nil{
return filenames, matches, err
}
defer walk.Free()
walk.Sorting(git.SortTopological)
walk.Push(head.Target())
searchAllBranches(repo, walk)
gi := head.Target()
for {
err := walk.Next(gi)
if err != nil {
break
}
commit, err := repo.LookupCommit(gi)
tree, err := commit.Tree()
err = tree.Walk(func(td string, te *git.TreeEntry) int {
if te.Type == git.ObjectBlob && te.Filemode == git.FilemodeBlob{
gitFile := GitFile{te.Name,
td, commit.Id().String(), repoUrl}
if !*fileNamesOnlyFlag && checkIfInsideIgnoredDirectory(td){
blob, err := repo.LookupBlob(te.Id)
if err == nil {
match, pattern, line, lineNum := searchBlobContents(blob.Contents())
if match {
appendGitMatch(pattern, gitFile, line, lineNum, table)
}
}
}
filenames = append(filenames, gitFile)
}
return 0
})
}
var results []*Match
for _, values := range table {
results = append(results, values)
}
return filenames, results, nil
}
func appendGitMatch(pattern Pattern, filename GitFile,
lineMatched string, lineNumb int, table map[string]*Match) {
//You can't assume a file hasn't moved directories in history
// which is why you use the filepath + filename for uniqueness
path := filename.Filepath
if len(path) == 0 {
path = "/" + filename.Name
} else {
path += filename.Name
}
_, exists := table[path]
if exists {
table[path].CommitIds = append(table[path].CommitIds, filename.CommitId)
} else {
table[path] = &Match{filename.Name, path,
[]string{filename.CommitId}, pattern.Description,
pattern.Value, lineMatched, lineNumb}
fmt.Print(color.BlueString("Found match %s %s ", pattern.Description, pattern.Value))
if lineNumb == NO_LINE_NUMBER_APPLICABLE{
color.Green("%s %s", path, filename.RepoUrl)
} else{
color.Green("%s:%d %s", path, lineNumb, filename.RepoUrl)
}
}
}
func gitSecretFilenameLiteralSearch(files []GitFile) []*Match {
var table = make(map[string]*Match)
for _, pattern := range secretFileNameLiterals {
for _, filename := range files {
if strings.Contains(filename.Name, pattern.Value) {
appendGitMatch(pattern, filename, IS_FILENAME_MATCH, NO_LINE_NUMBER_APPLICABLE, table)
}
}
}
var results []*Match
for _, values := range table {
results = append(results, values)
}
return results
}
func gitSecretFilenameRegexSearch(files []GitFile) []*Match {
var table = make(map[string]*Match)
for _, filename := range files {
for _, pattern := range secretFileNameRegexes {
if pattern.Regex.MatchString(filename.Name) {
appendGitMatch(pattern, filename, IS_FILENAME_MATCH, NO_LINE_NUMBER_APPLICABLE, table)
break
}
}
}
var results []*Match
for _, values := range table {
results = append(results, values)
}
return results
}
func outputCSVGitRepo(matches []*Match){
records := [][]string{{"Filename", "Description", "Filepath", "CommitID", "Value", "Line Number"}}
for _, match := range matches {
records = append(records, []string{match.Filename, match.Description, match.Filepath,
strings.Join(match.CommitIds, "|"),
match.Value, strconv.Itoa(match.LineNumber)})
}
outputCSV(*outputCSVFlag, records)
}
func startGitRepoScan(){
results, err := gitRepoSearch(*repoToScanFlag)
if err != nil{
color.Red(err.Error())
}
if len(*outputCSVFlag) != 0 {
outputCSVGitRepo(results)
}
}
func startGitOrganizationScan(){
var results = []*Match{}
urls, err := getAllOrganizationsRepoUrls(*organizationFlag)
if err!= nil {
color.Red(err.Error())
os.Exit(-1)
}
matchChan := make(chan []*Match, len(urls))
for _, url := range urls{
go getOrgRepo(url, matchChan)
}
for i:= 0; i < len(urls); i++{
select {
case matches := <-matchChan:
results = append(results, matches...)
}
}
if len(*outputCSVFlag) != 0 {
outputCSVGitRepo(results)
}
}