options.go 7.2 KB

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