options.go 7.9 KB

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