options.go 8.2 KB

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