options.go 7.4 KB

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