options.go 7.4 KB

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