github.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package gitleaks
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "github.com/google/go-github/github"
  12. log "github.com/sirupsen/logrus"
  13. "golang.org/x/oauth2"
  14. git "gopkg.in/src-d/go-git.v4"
  15. gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
  16. "gopkg.in/src-d/go-git.v4/storage/memory"
  17. )
  18. var githubPages = 100
  19. // auditPR audits a single github PR
  20. func auditGithubPR() ([]Leak, error) {
  21. var leaks []Leak
  22. ctx := context.Background()
  23. githubClient := github.NewClient(githubToken())
  24. splits := strings.Split(opts.GithubPR, "/")
  25. owner := splits[len(splits)-4]
  26. repo := splits[len(splits)-3]
  27. prNum, err := strconv.Atoi(splits[len(splits)-1])
  28. if err != nil {
  29. return nil, err
  30. }
  31. page := 1
  32. for {
  33. commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
  34. PerPage: githubPages,
  35. Page: page,
  36. })
  37. if err != nil {
  38. return leaks, err
  39. }
  40. for _, c := range commits {
  41. totalCommits = totalCommits + 1
  42. c, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *c.SHA)
  43. if err != nil {
  44. continue
  45. }
  46. files := c.Files
  47. for _, f := range files {
  48. skipFile := false
  49. if f.Patch == nil || f.Filename == nil {
  50. continue
  51. }
  52. for _, re := range config.WhiteList.files {
  53. if re.FindString(f.GetFilename()) != "" {
  54. log.Infof("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.GetFilename())
  55. skipFile = true
  56. break
  57. }
  58. }
  59. if skipFile {
  60. continue
  61. }
  62. commit := &commitInfo{
  63. sha: c.GetSHA(),
  64. content: *f.Patch,
  65. filePath: *f.Filename,
  66. repoName: repo,
  67. author: c.GetCommitter().GetLogin(),
  68. message: *c.Commit.Message,
  69. date: *c.Commit.Committer.Date,
  70. }
  71. leaks = append(leaks, inspect(commit)...)
  72. }
  73. }
  74. page = resp.NextPage
  75. if resp.LastPage == 0 {
  76. break
  77. }
  78. }
  79. return leaks, nil
  80. }
  81. // auditGithubRepos kicks off audits if --github-user or --github-org options are set.
  82. // First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
  83. // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
  84. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
  85. func auditGithubRepos() ([]Leak, error) {
  86. var (
  87. err error
  88. githubRepos []*github.Repository
  89. pagedGithubRepos []*github.Repository
  90. resp *github.Response
  91. githubOrgOptions *github.RepositoryListByOrgOptions
  92. githubOptions *github.RepositoryListOptions
  93. done bool
  94. leaks []Leak
  95. ownerDir string
  96. )
  97. ctx := context.Background()
  98. githubClient := github.NewClient(githubToken())
  99. if opts.GithubOrg != "" {
  100. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  101. ghURL, _ := url.Parse(opts.GithubURL)
  102. githubClient.BaseURL = ghURL
  103. }
  104. githubOrgOptions = &github.RepositoryListByOrgOptions{
  105. ListOptions: github.ListOptions{PerPage: 100},
  106. }
  107. } else if opts.GithubUser != "" {
  108. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  109. ghURL, _ := url.Parse(opts.GithubURL)
  110. githubClient.BaseURL = ghURL
  111. }
  112. githubOptions = &github.RepositoryListOptions{
  113. Affiliation: "owner",
  114. ListOptions: github.ListOptions{
  115. PerPage: 100,
  116. },
  117. }
  118. }
  119. for {
  120. if done {
  121. break
  122. }
  123. if opts.GithubUser != "" {
  124. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
  125. if err != nil {
  126. done = true
  127. }
  128. githubOptions.Page = resp.NextPage
  129. githubRepos = append(githubRepos, pagedGithubRepos...)
  130. if resp.NextPage == 0 {
  131. done = true
  132. }
  133. } else if opts.GithubOrg != "" {
  134. pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
  135. if err != nil {
  136. done = true
  137. }
  138. githubOrgOptions.Page = resp.NextPage
  139. githubRepos = append(githubRepos, pagedGithubRepos...)
  140. if resp.NextPage == 0 {
  141. done = true
  142. }
  143. }
  144. if opts.Log == "Debug" || opts.Log == "debug" {
  145. for _, githubRepo := range pagedGithubRepos {
  146. log.Debugf("staging repos %s", *githubRepo.Name)
  147. }
  148. }
  149. }
  150. if opts.Disk {
  151. ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
  152. }
  153. for _, githubRepo := range githubRepos {
  154. repoD, err := cloneGithubRepo(githubRepo)
  155. if err != nil {
  156. log.Warn(err)
  157. continue
  158. }
  159. leaksFromRepo, err := repoD.audit()
  160. if opts.Disk {
  161. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  162. }
  163. if len(leaksFromRepo) == 0 {
  164. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  165. } else {
  166. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  167. }
  168. if err != nil {
  169. log.Warn(err)
  170. }
  171. leaks = append(leaks, leaksFromRepo...)
  172. }
  173. return leaks, nil
  174. }
  175. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  176. // will be cloned to disk if --disk is set.
  177. func cloneGithubRepo(githubRepo *github.Repository) (*RepoInfo, error) {
  178. var (
  179. repo *git.Repository
  180. err error
  181. )
  182. githubToken := os.Getenv("GITHUB_TOKEN")
  183. if opts.ExcludeForks && githubRepo.GetFork() {
  184. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  185. }
  186. for _, re := range config.WhiteList.repos {
  187. if re.FindString(*githubRepo.Name) != "" {
  188. return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
  189. }
  190. }
  191. log.Infof("cloning: %s", *githubRepo.Name)
  192. if opts.Disk {
  193. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  194. if err != nil {
  195. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  196. }
  197. if config.sshAuth != nil && githubToken == "" {
  198. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  199. URL: *githubRepo.SSHURL,
  200. Auth: config.sshAuth,
  201. })
  202. } else if githubToken != "" {
  203. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  204. URL: *githubRepo.CloneURL,
  205. Auth: &gitHttp.BasicAuth{
  206. Username: "fakeUsername", // yes, this can be anything except an empty string
  207. Password: githubToken,
  208. },
  209. })
  210. } else {
  211. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  212. URL: *githubRepo.CloneURL,
  213. })
  214. }
  215. } else {
  216. if config.sshAuth != nil && githubToken == "" {
  217. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  218. URL: *githubRepo.SSHURL,
  219. Auth: config.sshAuth,
  220. })
  221. } else if githubToken != "" {
  222. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  223. URL: *githubRepo.CloneURL,
  224. Auth: &gitHttp.BasicAuth{
  225. Username: "fakeUsername", // yes, this can be anything except an empty string
  226. Password: githubToken,
  227. },
  228. })
  229. } else {
  230. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  231. URL: *githubRepo.CloneURL,
  232. })
  233. }
  234. }
  235. if err != nil {
  236. return nil, err
  237. }
  238. return &RepoInfo{
  239. repository: repo,
  240. name: *githubRepo.Name,
  241. }, nil
  242. }
  243. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  244. // if you are running audits with --github-user or --github-org
  245. func githubToken() *http.Client {
  246. githubToken := os.Getenv("GITHUB_TOKEN")
  247. if githubToken == "" {
  248. return nil
  249. }
  250. ts := oauth2.StaticTokenSource(
  251. &oauth2.Token{AccessToken: githubToken},
  252. )
  253. return oauth2.NewClient(context.Background(), ts)
  254. }