options.go 7.5 KB

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