options.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package options
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/user"
  7. "strings"
  8. "github.com/zricethezav/gitleaks/v7/version"
  9. "github.com/go-git/go-git/v5"
  10. "github.com/go-git/go-git/v5/plumbing"
  11. "github.com/go-git/go-git/v5/plumbing/transport"
  12. "github.com/go-git/go-git/v5/plumbing/transport/http"
  13. "github.com/go-git/go-git/v5/plumbing/transport/ssh"
  14. "github.com/jessevdk/go-flags"
  15. log "github.com/sirupsen/logrus"
  16. )
  17. // Options stores values of command line options
  18. type Options struct {
  19. Verbose bool `short:"v" long:"verbose" description:"Show verbose output from scan"`
  20. Quiet bool `short:"q" long:"quiet" description:"Sets log level to error and only output leaks, one json object per line"`
  21. RepoURL string `short:"r" long:"repo-url" description:"Repository URL"`
  22. Path string `short:"p" long:"path" description:"Path to directory (repo if contains .git) or file"`
  23. ConfigPath string `short:"c" long:"config-path" description:"Path to config"`
  24. RepoConfigPath string `long:"repo-config-path" description:"Path to gitleaks config relative to repo root"`
  25. ClonePath string `long:"clone-path" description:"Path to clone repo to disk"`
  26. Version bool `long:"version" description:"Version number"`
  27. Username string `long:"username" description:"Username for git repo"`
  28. Password string `long:"password" description:"Password for git repo"`
  29. AccessToken string `long:"access-token" description:"Access token for git repo"`
  30. Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
  31. SSH string `long:"ssh-key" description:"Path to ssh key used for auth"`
  32. Unstaged bool `long:"unstaged" description:"Run gitleaks on unstaged code"`
  33. Branch string `long:"branch" description:"Branch to scan"`
  34. Redact bool `long:"redact" description:"Redact secrets from log messages and leaks"`
  35. Debug bool `long:"debug" description:"Log debug messages"`
  36. NoGit bool `long:"no-git" description:"Treat git repos as plain directories and scan those files"`
  37. CodeOnLeak int `long:"leaks-exit-code" default:"1" description:"Exit code when leaks have been encountered"`
  38. // Report Options
  39. Report string `short:"o" long:"report" description:"Report output path"`
  40. ReportFormat string `short:"f" long:"format" default:"json" description:"JSON, CSV, SARIF"`
  41. // Commit Options
  42. FilesAtCommit string `long:"files-at-commit" description:"Sha of commit to scan all files at commit"`
  43. Commit string `long:"commit" description:"Sha of commit to scan or \"latest\" to scan the last commit of the repository"`
  44. Commits string `long:"commits" description:"Comma separated list of a commits to scan"`
  45. CommitsFile string `long:"commits-file" description:"Path to file of line separated list of commits to scan"`
  46. CommitFrom string `long:"commit-from" description:"Commit to start scan from"`
  47. CommitTo string `long:"commit-to" description:"Commit to stop scan"`
  48. 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."`
  49. 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."`
  50. Depth int `long:"depth" description:"Number of commits to scan"`
  51. }
  52. // ParseOptions is responsible for parsing options passed in by cli. An Options struct
  53. // is returned if successful. This struct is passed around the program
  54. // and will determine how the program executes. If err, an err message or help message
  55. // will be displayed and the program will exit with code 0.
  56. func ParseOptions() (Options, error) {
  57. var opts Options
  58. parser := flags.NewParser(&opts, flags.Default)
  59. _, err := parser.Parse()
  60. if err != nil {
  61. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp {
  62. parser.WriteHelp(os.Stdout)
  63. }
  64. os.Exit(1)
  65. }
  66. if opts.Version {
  67. if version.Version == "" {
  68. fmt.Println("Gitleaks uses LDFLAGS to pull most recent version. Build with 'make build' for version")
  69. } else {
  70. fmt.Printf("%s\n", version.Version)
  71. }
  72. os.Exit(0)
  73. }
  74. if opts.Debug {
  75. log.SetLevel(log.DebugLevel)
  76. }
  77. if opts.Quiet {
  78. log.SetLevel(log.ErrorLevel)
  79. }
  80. return opts, nil
  81. }
  82. // Guard checks to makes sure there are no invalid options set.
  83. // If invalid sets of options are present, a descriptive error will return
  84. // else nil is returned
  85. func (opts Options) Guard() error {
  86. if !oneOrNoneSet(opts.RepoURL, opts.Path) {
  87. return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
  88. }
  89. if !oneOrNoneSet(opts.AccessToken, opts.Password) {
  90. log.Warn("both access-token and password are set. Only password will be attempted")
  91. }
  92. return nil
  93. }
  94. func oneOrNoneSet(optStr ...string) bool {
  95. c := 0
  96. for _, s := range optStr {
  97. if s != "" {
  98. c++
  99. }
  100. }
  101. if c <= 1 {
  102. return true
  103. }
  104. return false
  105. }
  106. // CloneOptions returns a git.cloneOptions pointer. The authentication method
  107. // is determined by what is passed in via command-Line options. If No
  108. // Username/PW or AccessToken is available and the repo target is not using the
  109. // git protocol then the repo must be a available via no auth.
  110. func (opts Options) CloneOptions() (*git.CloneOptions, error) {
  111. var err error
  112. progress := ioutil.Discard
  113. if opts.Verbose {
  114. progress = os.Stdout
  115. }
  116. cloneOpts := &git.CloneOptions{
  117. URL: opts.RepoURL,
  118. Progress: progress,
  119. }
  120. if opts.Depth != 0 {
  121. cloneOpts.Depth = opts.Depth
  122. }
  123. if opts.Branch != "" {
  124. cloneOpts.ReferenceName = plumbing.NewBranchReferenceName(opts.Branch)
  125. }
  126. var auth transport.AuthMethod
  127. if strings.HasPrefix(opts.RepoURL, "git") {
  128. // using git protocol so needs ssh auth
  129. auth, err = SSHAuth(opts)
  130. if err != nil {
  131. return nil, err
  132. }
  133. } else if opts.Password != "" && opts.Username != "" {
  134. // auth using username and password
  135. auth = &http.BasicAuth{
  136. Username: opts.Username,
  137. Password: opts.Password,
  138. }
  139. } else if opts.AccessToken != "" {
  140. auth = &http.BasicAuth{
  141. Username: "gitleaks_user",
  142. Password: opts.AccessToken,
  143. }
  144. } else if os.Getenv("GITLEAKS_ACCESS_TOKEN") != "" {
  145. auth = &http.BasicAuth{
  146. Username: "gitleaks_user",
  147. Password: os.Getenv("GITLEAKS_ACCESS_TOKEN"),
  148. }
  149. }
  150. if auth != nil {
  151. cloneOpts.Auth = auth
  152. }
  153. return cloneOpts, nil
  154. }
  155. // SSHAuth tried to generate ssh public keys based on what was passed via cli. If no
  156. // path was passed via cli then this will attempt to retrieve keys from the default
  157. // location for ssh keys, $HOME/.ssh/id_rsa. This function is only called if the
  158. // repo url using the git:// protocol.
  159. func SSHAuth(opts Options) (*ssh.PublicKeys, error) {
  160. if opts.SSH != "" {
  161. return ssh.NewPublicKeysFromFile("git", opts.SSH, "")
  162. }
  163. c, err := user.Current()
  164. if err != nil {
  165. return nil, err
  166. }
  167. defaultPath := fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  168. return ssh.NewPublicKeysFromFile("git", defaultPath, "")
  169. }
  170. // OpenLocal checks what options are set, if no remote targets are set
  171. // then return true
  172. func (opts Options) OpenLocal() bool {
  173. if opts.Unstaged || opts.Path != "" || opts.RepoURL == "" {
  174. return true
  175. }
  176. return false
  177. }
  178. // CheckUncommitted returns a boolean that indicates whether or not gitleaks should check unstaged pre-commit changes
  179. // or if gitleaks should check the entire git history
  180. func (opts Options) CheckUncommitted() bool {
  181. // check to make sure no remote shit is set
  182. if opts.Unstaged {
  183. return true
  184. }
  185. if opts == (Options{}) {
  186. return true
  187. }
  188. if opts.RepoURL != "" {
  189. return false
  190. }
  191. if opts.Path != "" {
  192. return false
  193. }
  194. return true
  195. }