/
git.go
388 lines (348 loc) · 10.4 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Package core represents the core functionality of all commands
package core
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"sync"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/utils/merkletrie"
)
// Set easier names to refer to
const (
TargetTypeUser = "User"
TargetTypeOrganization = "Organization"
)
// GithubRepository holds the necessary information for a repository,
// this data is specific to Github.
type GithubRepository struct {
Owner *string
ID *int64
Name *string
FullName *string
CloneURL *string
URL *string
DefaultBranch *string
Description *string
Homepage *string
}
// CloneConfiguration holds the configurations for cloning a repo
type CloneConfiguration struct {
InMemClone *bool
URL *string
Username *string
Token *string
Branch *string
Depth *int
}
// Owner holds the info that we want for a repo owner
type Owner struct {
Login *string
ID *int64
Type *string
Name *string
AvatarURL *string
URL *string
Company *string
Blog *string
Location *string
Email *string
Bio *string
}
// Repository holds the info we want for a repo itself
type Repository struct {
Owner *string
ID *int64
Name *string
FullName *string
CloneURL *string
URL *string
DefaultBranch *string
Description *string
Homepage *string
}
// EmptyTreeCommit is a dummy commit id used as a placeholder and for testing
const (
EmptyTreeCommitID = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
)
// GetParentCommit will get the parent commit from a specific point. If the current commit
// has no parents then it will create a dummy commit.
func getParentCommit(commit *object.Commit, repo *git.Repository) (*object.Commit, error) {
if commit.NumParents() == 0 {
parentCommit, err := repo.CommitObject(plumbing.NewHash(EmptyTreeCommitID))
if err != nil {
return nil, err
}
return parentCommit, nil
}
parentCommit, err := commit.Parents().Next()
if err != nil {
return nil, err
}
return parentCommit, nil
}
// GetRepositoryHistory gets the commit history of a repository
func GetRepositoryHistory(repository *git.Repository) ([]*object.Commit, error) {
var commits []*object.Commit
ref, err := repository.Head()
if err != nil {
return nil, err
}
cIter, err := repository.Log(&git.LogOptions{From: ref.Hash()})
if err != nil {
return nil, err
}
_ = cIter.ForEach(func(c *object.Commit) error {
commits = append(commits, c)
return nil
})
return commits, nil
}
// GetChanges will get the changes between to specific commits. It grabs the parent commit of
// the one being passed and uses that to fetch the tree for that commit. If no commit is found,
// it will create a fake on. It then takes that parent tree along with the tree for the commit
// passed in and does a diff
func GetChanges(commit *object.Commit, repo *git.Repository) (object.Changes, error) {
parentCommit, err := getParentCommit(commit, repo)
if err != nil {
return nil, err
}
commitTree, err := commit.Tree()
if err != nil {
return nil, err
}
parentCommitTree, err := parentCommit.Tree()
if err != nil {
return nil, err
}
changes, err := object.DiffTree(parentCommitTree, commitTree)
if err != nil {
return nil, err
}
return changes, nil
}
// GetChangeAction returns a more condensed and user friendly action for further reference
func GetChangeAction(change *object.Change) string {
action, err := change.Action()
if err != nil {
return "Unknown"
}
switch action {
case merkletrie.Insert:
return "Insert"
case merkletrie.Modify:
return "Modify"
case merkletrie.Delete:
return "Delete"
default:
return "Unknown"
}
}
// GetChangePath will set the action of the commit for further action
func GetChangePath(change *object.Change) string {
action, err := change.Action()
if err != nil {
return change.To.Name
}
if action == merkletrie.Delete {
return change.From.Name
}
return change.To.Name
}
// GetChangeContent will get the contents of a git change or patch.
func GetChangeContent(change *object.Change) (result string, contentError error) {
//temporary response to: https://github.com/sergi/go-diff/issues/89
defer func() {
if err := recover(); err != nil {
contentError = errors.New("panic occurred while retrieving change content: ")
}
}()
patch, err := change.Patch()
if err != nil {
return "", err
}
for _, filePatch := range patch.FilePatches() {
if filePatch.IsBinary() {
continue
}
for _, chunk := range filePatch.Chunks() {
result += chunk.Content()
}
}
return result, nil
}
// GatherGitlabRepositories will gather all repositories associated with a given target during a scan session.
// This is done using threads, whose count is set via commandline flag. Care much be taken to avoid rate
// limiting associated with suspected DOS attacks.
func GatherGitlabRepositories(sess *Session) {
var ch = make(chan *Owner, len(sess.Targets))
sess.Out.Debug("Number of targets: %d\n", len(sess.Targets))
var wg sync.WaitGroup
var threadNum int
if len(sess.Targets) == 1 {
threadNum = 1
} else if len(sess.Targets) <= sess.Threads {
threadNum = len(sess.Targets) - 1
} else {
threadNum = sess.Threads
}
wg.Add(threadNum)
sess.Out.Debug("Threads for repository gathering: %d\n", threadNum)
for i := 0; i < threadNum; i++ {
go func() {
for {
target, ok := <-ch
if !ok {
wg.Done()
return
}
repos, err := sess.Client.GetRepositoriesFromOwner(*target)
if err != nil {
sess.Out.Error(" Failed to retrieve repositories from %s: %s\n", *target.Login, err)
}
if len(repos) == 0 {
continue
}
for _, repo := range repos {
sess.Out.Debug(" Retrieved repository: %s\n", *repo.CloneURL)
sess.AddRepository(repo)
}
sess.Out.Info(" Retrieved %d %s from %s\n", len(repos), Pluralize(len(repos), "repository", "repositories"), *target.Login)
}
}()
}
for _, target := range sess.Targets {
ch <- target
}
close(ch)
wg.Wait()
}
// InitGitClient will create a new github client of the type given by the input string. Currently Enterprise and github.com are supported
func (s *Session) InitGitClient() {
// TODO need to make this a switch
if s.ScanType == "github-enterprise" {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
sslcli := &http.Client{Transport: tr}
ctx := context.Background()
ctx = context.WithValue(ctx, oauth2.HTTPClient, sslcli)
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: s.GithubAccessToken},
)
tc := oauth2.NewClient(ctx, ts)
baseURL := ""
uploadURL := ""
if s.GithubEnterpriseURL != "" {
_, err := url.Parse(s.GithubEnterpriseURL)
if err != nil {
s.Out.Error("Unable to parse --github-enterprise-url: <%s>", s.GithubEnterpriseURL)
} else {
baseURL = fmt.Sprintf("%s/api/v3", s.GithubEnterpriseURL)
uploadURL = fmt.Sprintf("%s/api/uploads", s.GithubEnterpriseURL)
}
}
s.GithubClient, _ = github.NewEnterpriseClient(baseURL, uploadURL, tc)
}
if s.ScanType == "github" {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
sslcli := &http.Client{Transport: tr}
ctx := context.Background()
ctx = context.WithValue(ctx, oauth2.HTTPClient, sslcli)
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: s.GithubAccessToken},
)
tc := oauth2.NewClient(ctx, ts)
if s.GithubURL != "" {
_, err := url.Parse(s.GithubURL)
if err != nil {
s.Out.Error("Unable to parse --github-url: <%s>", s.GithubURL)
}
}
s.GithubClient = github.NewClient(tc)
}
if s.ScanType == "gitlab" { // TODO need to refactor all this
CheckGitlabAPIToken(s.GitlabAccessToken, s) // TODO move this out
var err error
// TODO need to add in the bits to parse the url here as well
// TODO set this to some sort of consistent client, look to github for ideas
s.Client, err = gitlabClient.NewClient(gitlabClient{}, s.GitlabAccessToken, s.Out)
if err != nil {
s.Out.Fatal("Error initializing GitLab client: %s", err)
}
}
}
// cloneRepository will clone a given repository based upon a configured set or options a user provides.
// This is a catchall for all different types of repos and create a single entry point for cloning a repo.
func cloneRepository(sess *Session, repo *Repository, threadID int) (*git.Repository, string, error) {
sess.Out.Debug("[THREAD #%d][%s] Cloning repository...\n", threadID, *repo.CloneURL)
var clone *git.Repository
var path string
var err error
switch sess.ScanType {
case "github":
cloneConfig := CloneConfiguration{
URL: repo.CloneURL,
Branch: repo.DefaultBranch,
Depth: &sess.CommitDepth,
InMemClone: &sess.InMemClone,
Token: &sess.GithubAccessToken,
}
// Clone a github repo
clone, path, err = cloneGithub(&cloneConfig)
case "github-enterprise":
cloneConfig := CloneConfiguration{
URL: repo.CloneURL,
Branch: repo.DefaultBranch,
Depth: &sess.CommitDepth,
InMemClone: &sess.InMemClone,
Token: &sess.GithubAccessToken,
}
// Clone a github repo
clone, path, err = cloneGithub(&cloneConfig)
case "gitlab":
userName := "oauth2"
cloneConfig := CloneConfiguration{
URL: repo.CloneURL,
Branch: repo.DefaultBranch,
Depth: &sess.CommitDepth,
Token: &sess.GitlabAccessToken, // TODO Is this need since we already have a client?
InMemClone: &sess.InMemClone,
Username: &userName,
}
// Clone a gitlab repo
clone, path, err = cloneGitlab(&cloneConfig)
case "localGit":
cloneConfig := CloneConfiguration{
URL: repo.CloneURL,
Branch: repo.DefaultBranch,
Depth: &sess.CommitDepth,
InMemClone: &sess.InMemClone,
}
// Clone a local repo
clone, path, err = cloneLocal(&cloneConfig)
}
if err != nil {
switch err.Error() {
case "remote repository is empty":
sess.Out.Error("Repository %s is empty: %s\n", *repo.CloneURL, err)
sess.Stats.IncrementRepositoriesCloned()
return nil, "", err
default:
sess.Out.Error("Error cloning repository %s: %s\n", *repo.CloneURL, err)
return nil, "", err
}
}
sess.Stats.IncrementRepositoriesCloned()
sess.Out.Debug("[THREAD #%d][%s] Cloned repository to: %s\n", threadID, *repo.CloneURL, path)
return clone, path, err
}