options.go 9.1 KB

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