options.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package options
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/user"
  7. "strings"
  8. "github.com/zricethezav/gitleaks/v6/version"
  9. "github.com/go-git/go-git/v5"
  10. "github.com/go-git/go-git/v5/plumbing/transport/http"
  11. "github.com/go-git/go-git/v5/plumbing/transport/ssh"
  12. "github.com/jessevdk/go-flags"
  13. log "github.com/sirupsen/logrus"
  14. )
  15. // No leaks or early exit due to invalid options
  16. // This block defines the exit codes. Success
  17. const (
  18. // No leaks or early exit due to invalid options
  19. Success = 0
  20. LeaksPresent = 1
  21. ErrorEncountered = 2
  22. donateMessage = "👋 maintaining gitleaks takes a lot of work so consider sponsoring me or donating a little something\n❤️ https://github.com/sponsors/zricethezav\n💸 https://www.paypal.me/zricethezav\n₿ btc:3GndEzRZa6rJ8ZpkLureUcc5TDHMYfpDxn"
  23. )
  24. // Options stores values of command line options
  25. type Options struct {
  26. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from scan"`
  27. Repo string `short:"r" long:"repo" description:"Target repository"`
  28. Config string `long:"config" description:"config path"`
  29. Disk bool `long:"disk" description:"Clones repo(s) to disk"`
  30. Version bool `long:"version" description:"version number"`
  31. Username string `long:"username" description:"Username for git repo"`
  32. Password string `long:"password" description:"Password for git repo"`
  33. AccessToken string `long:"access-token" description:"Access token for git repo"`
  34. FilesAtCommit string `long:"files-at-commit" description:"sha of commit to scan all files at commit"`
  35. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  36. SSH string `long:"ssh-key" description:"path to ssh key used for auth"`
  37. Uncommited bool `long:"uncommitted" description:"run gitleaks on uncommitted code"`
  38. RepoPath string `long:"repo-path" description:"Path to repo"`
  39. OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
  40. Branch string `long:"branch" description:"Branch to scan"`
  41. Report string `long:"report" description:"path to write json leaks file"`
  42. ReportFormat string `long:"report-format" default:"json" description:"json, csv, sarif"`
  43. Redact bool `long:"redact" description:"redact secrets from log messages and leaks"`
  44. Debug bool `long:"debug" description:"log debug messages"`
  45. RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\" or \"gitleaks.toml\""`
  46. PrettyPrint bool `long:"pretty" description:"Pretty print json if leaks are present"`
  47. // Commit Options
  48. Commit string `long:"commit" description:"sha of commit to scan or \"latest\" to scan the last commit of the repository"`
  49. Commits string `long:"commits" description:"comma separated list of a commits to scan"`
  50. CommitsFile string `long:"commits-file" description:"file of new line separated list of a commits to scan"`
  51. CommitFrom string `long:"commit-from" description:"Commit to start scan from"`
  52. CommitTo string `long:"commit-to" description:"Commit to stop scan"`
  53. CommitSince string `long:"commit-since" description:"Scan commits more recent than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format."`
  54. CommitUntil string `long:"commit-until" description:"Scan commits older than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format."`
  55. Timeout string `long:"timeout" description:"Time allowed per scan. Ex: 10us, 30s, 1m, 1h10m1s"`
  56. Depth int `long:"depth" description:"Number of commits to scan"`
  57. Deletion bool `long:"include-deletion" description:"Scan for patch deletions in addition to patch additions"`
  58. // Hosts
  59. Host string `long:"host" description:"git hosting service like gitlab or github. Supported hosts include: Github, Gitlab"`
  60. BaseURL string `long:"baseurl" description:"Base URL for API requests. Defaults to the public GitLab or GitHub API, but can be set to a domain endpoint to use with a self hosted server."`
  61. Organization string `long:"org" description:"organization to scan"`
  62. User string `long:"user" description:"user to scan"`
  63. PullRequest string `long:"pr" description:"pull/merge request url"`
  64. ExcludeForks bool `long:"exclude-forks" description:"scan excludes forks"`
  65. }
  66. // ParseOptions is responsible for parsing options passed in by cli. An Options struct
  67. // is returned if successful. This struct is passed around the program
  68. // and will determine how the program executes. If err, an err message or help message
  69. // will be displayed and the program will exit with code 0.
  70. func ParseOptions() (Options, error) {
  71. var opts Options
  72. parser := flags.NewParser(&opts, flags.Default)
  73. _, err := parser.Parse()
  74. if err != nil {
  75. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp {
  76. parser.WriteHelp(os.Stdout)
  77. }
  78. fmt.Println(donateMessage)
  79. os.Exit(0)
  80. }
  81. if opts.Version {
  82. if version.Version == "" {
  83. fmt.Println("Gitleaks uses LDFLAGS to pull most recent version. Build with 'make build' for version")
  84. } else {
  85. fmt.Printf("%s\n", version.Version)
  86. }
  87. os.Exit(Success)
  88. }
  89. if opts.Debug {
  90. log.SetLevel(log.DebugLevel)
  91. }
  92. return opts, nil
  93. }
  94. // Guard checks to makes sure there are no invalid options set.
  95. // If invalid sets of options are present, a descriptive error will return
  96. // else nil is returned
  97. func (opts Options) Guard() error {
  98. if !oneOrNoneSet(opts.Repo, opts.OwnerPath, opts.RepoPath, opts.Host) {
  99. return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
  100. }
  101. if !oneOrNoneSet(opts.Organization, opts.User, opts.PullRequest) {
  102. return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
  103. }
  104. if !oneOrNoneSet(opts.AccessToken, opts.Password) {
  105. log.Warn("both access-token and password are set. Only password will be attempted")
  106. }
  107. return nil
  108. }
  109. func oneOrNoneSet(optStr ...string) bool {
  110. c := 0
  111. for _, s := range optStr {
  112. if s != "" {
  113. c++
  114. }
  115. }
  116. if c <= 1 {
  117. return true
  118. }
  119. return false
  120. }
  121. // CloneOptions returns a git.cloneOptions pointer. The authentication method
  122. // is determined by what is passed in via command-Line options. If No
  123. // Username/PW or AccessToken is available and the repo target is not using the
  124. // git protocol then the repo must be a available via no auth.
  125. func (opts Options) CloneOptions() (*git.CloneOptions, error) {
  126. progress := ioutil.Discard
  127. if opts.Verbose {
  128. progress = os.Stdout
  129. }
  130. if strings.HasPrefix(opts.Repo, "git") {
  131. // using git protocol so needs ssh auth
  132. auth, err := SSHAuth(opts)
  133. if err != nil {
  134. return nil, err
  135. }
  136. return &git.CloneOptions{
  137. URL: opts.Repo,
  138. Auth: auth,
  139. Progress: progress,
  140. }, nil
  141. }
  142. if opts.Password != "" && opts.Username != "" {
  143. // auth using username and password
  144. return &git.CloneOptions{
  145. URL: opts.Repo,
  146. Auth: &http.BasicAuth{
  147. Username: opts.Username,
  148. Password: opts.Password,
  149. },
  150. Progress: progress,
  151. }, nil
  152. }
  153. if opts.AccessToken != "" {
  154. return &git.CloneOptions{
  155. URL: opts.Repo,
  156. Auth: &http.BasicAuth{
  157. Username: "gitleaks_user",
  158. Password: opts.AccessToken,
  159. },
  160. Progress: progress,
  161. }, nil
  162. }
  163. if os.Getenv("GITLEAKS_ACCESS_TOKEN") != "" {
  164. return &git.CloneOptions{
  165. URL: opts.Repo,
  166. Auth: &http.BasicAuth{
  167. Username: "gitleaks_user",
  168. Password: os.Getenv("GITLEAKS_ACCESS_TOKEN"),
  169. },
  170. Progress: progress,
  171. }, nil
  172. }
  173. // No Auth, publicly available
  174. return &git.CloneOptions{
  175. URL: opts.Repo,
  176. Progress: progress,
  177. }, nil
  178. }
  179. // SSHAuth tried to generate ssh public keys based on what was passed via cli. If no
  180. // path was passed via cli then this will attempt to retrieve keys from the default
  181. // location for ssh keys, $HOME/.ssh/id_rsa. This function is only called if the
  182. // repo url using the git:// protocol.
  183. func SSHAuth(opts Options) (*ssh.PublicKeys, error) {
  184. if opts.SSH != "" {
  185. return ssh.NewPublicKeysFromFile("git", opts.SSH, "")
  186. }
  187. c, err := user.Current()
  188. if err != nil {
  189. return nil, err
  190. }
  191. defaultPath := fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  192. return ssh.NewPublicKeysFromFile("git", defaultPath, "")
  193. }
  194. // OpenLocal checks what options are set, if no remote targets are set
  195. // then return true
  196. func (opts Options) OpenLocal() bool {
  197. if opts.Uncommited || opts.RepoPath != "" || opts.Repo == "" {
  198. return true
  199. }
  200. return false
  201. }
  202. // CheckUncommitted returns a boolean that indicates whether or not gitleaks should check unstaged pre-commit changes
  203. // or if gitleaks should check the entire git history
  204. func (opts Options) CheckUncommitted() bool {
  205. // check to make sure no remote shit is set
  206. if opts.Uncommited {
  207. return true
  208. }
  209. if opts == (Options{}) {
  210. return true
  211. }
  212. if opts.Repo != "" {
  213. return false
  214. }
  215. if opts.RepoPath != "" {
  216. return false
  217. }
  218. if opts.OwnerPath != "" {
  219. return false
  220. }
  221. if opts.Host != "" {
  222. return false
  223. }
  224. return true
  225. }
  226. // GetAccessToken accepts options and returns a string which is the access token to a git host.
  227. // Setting this option or environment var is necessary if performing an scan with any of the git hosting providers
  228. // in the host pkg. The access token set by cli options takes precedence over env vars.
  229. func GetAccessToken(opts Options) string {
  230. if opts.AccessToken != "" {
  231. return opts.AccessToken
  232. }
  233. return os.Getenv("GITLEAKS_ACCESS_TOKEN")
  234. }