/
github.go
241 lines (190 loc) · 6.89 KB
/
github.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
package github
//Package github is used to interface with a github server host as the FileRepository source. Github repositories are downloaded as zip archives and scanned on the local filesystem.
import (
"bytes"
"fmt"
"github.com/google/go-github/github"
"github.com/intuit/gitdetect/defect"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/intuit/gitdetect/filerepo/scanner"
"github.com/intuit/gitdetect/secret"
)
const (
//PUBLIC_HOSTNAME default github hostname
PUBLIC_HOSTNAME = "github.com"
)
//FileRepository represents a Github FileRepository source
type FileRepository struct {
accessToken string
lastModifiedScanCutoff time.Time
repoOwner string //set if we're scanning a distinct repository
repoName string //set if we're scanning a distinct repository
repoBranch string //optionally set if we're scanning a distinct repository
gitClient *github.Client
fileScanner scanner.FileScanner
rootDir string
scannedReposCounter int
hostname string
}
//NewGithubFileRepository returns a new GithubFileRepository structure used to scan any number of repositories on the given github host.
func NewGithubFileRepository(githubHostname string, accessToken string, lastModifiedScanCutoff int, repoNameFQ string, workingDir string, fileScanner scanner.FileScanner) *FileRepository {
githubRepository := FileRepository{hostname: githubHostname, accessToken: accessToken, fileScanner: fileScanner, rootDir: workingDir}
if repoNameFQ != "" {
repoNameArray := strings.Split(repoNameFQ, "/")
githubRepository.repoOwner = repoNameArray[0]
githubRepository.repoName = repoNameArray[1]
if len(repoNameArray) == 3 {
githubRepository.repoBranch = repoNameArray[2]
}
}
if lastModifiedScanCutoff > 0 {
githubRepository.lastModifiedScanCutoff = time.Now().AddDate(0, 0, -lastModifiedScanCutoff)
}
githubRepository.gitClient = githubRepository.initClient()
return &githubRepository
}
//Scan scans this repoOwner/repoBranch when repoOwner & repoBranch are set. When not set, all repositories on this hostname accessible by this accessToken are scanned
func (this *FileRepository) Scan(defectReport *defect.Report) (err error) {
if this.repoName != "" {
var repository *github.Repository
repository, _, err = this.gitClient.Repositories.Get(context.Background(), this.repoOwner, this.repoName)
if err == nil {
err = this.scanRepo(repository, defectReport)
}
} else {
err = this.scanRepos(defectReport)
log.Printf("Total number of github repositories scanned: -%d-\n", this.scannedReposCounter)
}
return
}
func (this *FileRepository) scanRepos(defectReport *defect.Report) error {
opt := &github.RepositoryListAllOptions{
Since: 0,
}
gClient := this.gitClient
for {
repos, _, err := gClient.Repositories.ListAll(context.Background(), opt)
if err != nil {
return err
}
if len(repos) == 0 {
break
}
for _, repoElement := range repos {
//this repoElement will have more meta data than the one being paged through
repoElement, _, err = gClient.Repositories.GetByID(context.Background(), repoElement.GetID())
if err != nil {
log.Println("ERROR: failed getting detailed repository data for " + repoElement.GetName() + ", skipping this repository.")
continue
}
//If this is an incremental run WRT repository update activity, check last update for this repository
if !repoElement.GetPushedAt().After(this.lastModifiedScanCutoff) {
continue
}
err = this.scanRepo(repoElement, defectReport)
if err != nil {
log.Println("ERROR: scan failed on " + repoElement.GetName() + ", skipping this repository.")
continue
}
}
opt.Since = repos[len(repos)-1].GetID()
}
return nil
}
func (this *FileRepository) scanRepo(repository *github.Repository, defectReport *defect.Report) (err error) {
log.Printf("scanning repo id %d %s", repository.GetID(), repository.GetName())
localRepoDir, err := this.downloadRepoArchive(repository.GetArchiveURL(), repository.GetName(), this.repoBranch)
if err != nil {
err = fmt.Errorf("Error downloading %s, %s, skipping this repository", repository.GetArchiveURL(), err.Error())
return
}
repoSecrets := this.scanFiles(localRepoDir)
this.scannedReposCounter++
if len(repoSecrets) > 0 {
defects := defectReport.ReduceAndExploit(repoSecrets, localRepoDir)
repoDetails := this.getRepoDetails(repository)
defectReport.AddDefects(repoDetails, defects)
defectReport.Save()
}
os.RemoveAll(localRepoDir)
return
}
func (this *FileRepository) getRepoDetails(repoElement *github.Repository) (repoReport defect.FileRepo) {
//Basic data available from repository handle
repoReport = defect.FileRepo{
Name: repoElement.GetName(),
ID: repoElement.GetID(),
Org: repoElement.GetOwner().GetLogin(),
Branch: repoElement.GetDefaultBranch(),
LastPush: repoElement.GetPushedAt().Time.Format("2006-01-02"),
}
branch, _, err := this.gitClient.Repositories.GetBranch(context.Background(), repoElement.GetOwner().GetLogin(), repoElement.GetName(), repoElement.GetDefaultBranch())
if err != nil {
log.Printf("Failed getting head commit id for repository %s", repoElement.GetName())
return
}
repoReport.Head = branch.GetCommit().GetSHA()
return
}
func (this *FileRepository) initClient() *github.Client {
var gClient *github.Client
//enterprise github
endpoint := this.hostname
path := "/api/v3/"
//public github
if this.hostname == PUBLIC_HOSTNAME {
endpoint = "api." + this.hostname
path = "/"
}
if this.accessToken == "" {
gClient = github.NewClient(nil)
} else {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: this.accessToken},
)
tc := oauth2.NewClient(ctx, ts)
gClient = github.NewClient(tc)
}
githubURL := url.URL{
Scheme: "https",
Host: endpoint,
Path: path,
}
gClient.BaseURL = &githubURL
return gClient
}
func (this *FileRepository) downloadRepoArchive(archiveURL string, repoName string, repoBranch string) (string, error) {
archiveURL = strings.Replace(archiveURL, "{archive_format}{/ref}", "zipball/"+repoBranch, 1)
endpoint := archiveURL
if this.accessToken != "" {
endpoint += "?access_token=" + this.accessToken
}
response, err := http.Get(endpoint)
if err != nil {
return "", err
}
defer response.Body.Close()
outputBuffer, err := ioutil.ReadAll(response.Body)
//_, err = io.Copy(output, response.Body)
if err != nil {
return "", err
}
newReader := bytes.NewReader(outputBuffer)
rootDir, err := Unzip(newReader, int64(len(outputBuffer)), this.rootDir+string(filepath.Separator))
localRepoDir := filepath.Join(this.rootDir, rootDir)
return localRepoDir, err
}
func (this *FileRepository) scanFiles(localDir string) (repoSecrets []secret.Secret) {
this.fileScanner.RootDir = localDir
return this.fileScanner.Scan()
}