options.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package options
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/user"
  7. "strings"
  8. "github.com/zricethezav/gitleaks/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. // Hosts
  50. Host string `long:"host" description:"git hosting service like gitlab or github. Supported hosts include: Github, Gitlab"`
  51. 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."`
  52. Organization string `long:"org" description:"organization to audit"`
  53. User string `long:"user" description:"user to audit"` //work
  54. PullRequest string `long:"pr" description:"pull/merge request url"`
  55. }
  56. // ParseOptions is responsible for parsing options passed in by cli. An Options struct
  57. // is returned if successful. This struct is passed around the program
  58. // and will determine how the program executes. If err, an err message or help message
  59. // will be displayed and the program will exit with code 0.
  60. func ParseOptions() (Options, error) {
  61. var opts Options
  62. parser := flags.NewParser(&opts, flags.Default)
  63. _, err := parser.Parse()
  64. if err != nil {
  65. if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp {
  66. parser.WriteHelp(os.Stdout)
  67. }
  68. os.Exit(0)
  69. }
  70. if opts.Version {
  71. if version.Version == "" {
  72. fmt.Println("Gitleaks uses LDFLAGS to pull most recent version. Build with 'make build' for version")
  73. } else {
  74. fmt.Printf("%s\n", version.Version)
  75. }
  76. os.Exit(Success)
  77. }
  78. if opts.Debug {
  79. log.SetLevel(log.DebugLevel)
  80. }
  81. return opts, nil
  82. }
  83. // Guard checks to makes sure there are no invalid options set.
  84. // If invalid sets of options are present, a descriptive error will return
  85. // else nil is returned
  86. func (opts Options) Guard() error {
  87. if !oneOrNoneSet(opts.Repo, opts.OwnerPath, opts.RepoPath, opts.Host) {
  88. return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
  89. }
  90. if !oneOrNoneSet(opts.Organization, opts.User, opts.PullRequest) {
  91. return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
  92. }
  93. if !oneOrNoneSet(opts.AccessToken, opts.Password) {
  94. log.Warn("both access-token and password are set. Only password will be attempted")
  95. }
  96. return nil
  97. }
  98. func oneOrNoneSet(optStr ...string) bool {
  99. c := 0
  100. for _, s := range optStr {
  101. if s != "" {
  102. c++
  103. }
  104. }
  105. if c <= 1 {
  106. return true
  107. }
  108. return false
  109. }
  110. // CloneOptions returns a git.cloneOptions pointer. The authentication method
  111. // is determined by what is passed in via command-Line options. If No
  112. // Username/PW or AccessToken is available and the repo target is not using the
  113. // git protocol then the repo must be a available via no auth.
  114. func (opts Options) CloneOptions() (*git.CloneOptions, error) {
  115. progress := ioutil.Discard
  116. if opts.Verbose {
  117. progress = os.Stdout
  118. }
  119. if strings.HasPrefix(opts.Repo, "git") {
  120. // using git protocol so needs ssh auth
  121. auth, err := SSHAuth(opts)
  122. if err != nil {
  123. return nil, err
  124. }
  125. return &git.CloneOptions{
  126. URL: opts.Repo,
  127. Auth: auth,
  128. Progress: progress,
  129. }, nil
  130. }
  131. if opts.Password != "" && opts.Username != "" {
  132. // auth using username and password
  133. return &git.CloneOptions{
  134. URL: opts.Repo,
  135. Auth: &http.BasicAuth{
  136. Username: opts.Username,
  137. Password: opts.Password,
  138. },
  139. Progress: progress,
  140. }, nil
  141. }
  142. if opts.AccessToken != "" {
  143. return &git.CloneOptions{
  144. URL: opts.Repo,
  145. Auth: &http.BasicAuth{
  146. Username: "gitleaks_user",
  147. Password: opts.AccessToken,
  148. },
  149. Progress: progress,
  150. }, nil
  151. }
  152. if os.Getenv("GITLEAKS_ACCESS_TOKEN") != "" {
  153. return &git.CloneOptions{
  154. URL: opts.Repo,
  155. Auth: &http.BasicAuth{
  156. Username: "gitleaks_user",
  157. Password: os.Getenv("GITLEAKS_ACCESS_TOKEN"),
  158. },
  159. Progress: progress,
  160. }, nil
  161. }
  162. // No Auth, publicly available
  163. return &git.CloneOptions{
  164. URL: opts.Repo,
  165. Progress: progress,
  166. }, nil
  167. }
  168. // SSHAuth tried to generate ssh public keys based on what was passed via cli. If no
  169. // path was passed via cli then this will attempt to retrieve keys from the default
  170. // location for ssh keys, $HOME/.ssh/id_rsa. This function is only called if the
  171. // repo url using the git:// protocol.
  172. func SSHAuth(opts Options) (*ssh.PublicKeys, error) {
  173. if opts.SSH != "" {
  174. return ssh.NewPublicKeysFromFile("git", opts.SSH, "")
  175. }
  176. c, err := user.Current()
  177. if err != nil {
  178. return nil, err
  179. }
  180. defaultPath := fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
  181. return ssh.NewPublicKeysFromFile("git", defaultPath, "")
  182. }
  183. // OpenLocal checks what options are set, if no remote targets are set
  184. // then return true
  185. func (opts Options) OpenLocal() bool {
  186. if opts.Uncommited || opts.RepoPath != "" || opts.Repo == "" {
  187. return true
  188. }
  189. return false
  190. }
  191. // CheckUncommitted returns a boolean that indicates whether or not gitleaks should check unstaged pre-commit changes
  192. // or if gitleaks should check the entire git history
  193. func (opts Options) CheckUncommitted() bool {
  194. // check to make sure no remote shit is set
  195. if opts.Uncommited {
  196. return true
  197. }
  198. if opts == (Options{}) {
  199. return true
  200. }
  201. if opts.Repo != "" {
  202. return false
  203. }
  204. if opts.RepoPath != "" {
  205. return false
  206. }
  207. if opts.OwnerPath != "" {
  208. return false
  209. }
  210. if opts.Host != "" {
  211. return false
  212. }
  213. return true
  214. }
  215. // GetAccessToken accepts options and returns a string which is the access token to a git host.
  216. // Setting this option or environment var is necessary if performing an audit with any of the git hosting providers
  217. // in the host pkg. The access token set by cli options takes precedence over env vars.
  218. func GetAccessToken(opts Options) string {
  219. if opts.AccessToken != "" {
  220. return opts.AccessToken
  221. }
  222. return os.Getenv("GITLEAKS_ACCESS_TOKEN")
  223. }