options.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. )
  10. const usage = `usage: gitleaks [options] <URL>/<path_to_repo>
  11. Options:
  12. Modes
  13. -u --user Git user mode
  14. -r --repo Git repo mode
  15. -o --org Git organization mode
  16. -l --local Local mode, gitleaks will look for local repo in <path>
  17. Logging
  18. -ll <INT> --log=<INT> 0: Debug, 1: Info, 3: Error
  19. -v --verbose Verbose mode, will output leaks as gitleaks finds them
  20. Locations
  21. --report_path=<STR> Report output, default $GITLEAKS_HOME/report
  22. --clone_path=<STR> Gitleaks will clone repos here, default $GITLEAKS_HOME/clones
  23. Other
  24. -t --temp Clone to temporary directory
  25. -c <INT> Upper bound on concurrent diffs
  26. --since=<STR> Commit to stop at
  27. --b64Entropy=<INT> Base64 entropy cutoff (default is 70)
  28. --hexEntropy=<INT> Hex entropy cutoff (default is 40)
  29. -e --entropy Enable entropy
  30. -h --help Display this message
  31. --token=<STR> Github API token
  32. --stopwords Enables stopwords
  33. --pretty Enables pretty printing for humans, otherwise you'll get logs'
  34. `
  35. // Options for gitleaks. need to support remote repo/owner
  36. // and local repo/owner mode
  37. type Options struct {
  38. URL string
  39. RepoPath string
  40. ReportPath string
  41. ClonePath string
  42. Concurrency int
  43. B64EntropyCutoff int
  44. HexEntropyCutoff int
  45. // MODES
  46. UserMode bool
  47. OrgMode bool
  48. RepoMode bool
  49. LocalMode bool
  50. // OPTS
  51. Strict bool
  52. Entropy bool
  53. SinceCommit string
  54. Persist bool
  55. IncludeForks bool
  56. Tmp bool
  57. ReportOut bool
  58. Token string
  59. // LOGS/REPORT
  60. LogLevel int
  61. PrettyPrint bool
  62. }
  63. // help prints the usage string and exits
  64. func help() {
  65. os.Stderr.WriteString(usage)
  66. }
  67. // optionsNextInt is a parseOptions helper that returns the value (int) of an option if valid
  68. func (opts *Options) nextInt(args []string, i *int) int {
  69. if len(args) > *i+1 {
  70. *i++
  71. } else {
  72. help()
  73. }
  74. argInt, err := strconv.Atoi(args[*i])
  75. if err != nil {
  76. opts.failF("Invalid %s option: %s\n", args[*i-1], args[*i])
  77. }
  78. return argInt
  79. }
  80. // optionsNextString is a parseOptions helper that returns the value (string) of an option if valid
  81. func (opts *Options) nextString(args []string, i *int) string {
  82. if len(args) > *i+1 {
  83. *i++
  84. } else {
  85. opts.failF("Invalid %s option: %s\n", args[*i-1], args[*i])
  86. }
  87. return args[*i]
  88. }
  89. // optInt grabs the string ...
  90. func (opts *Options) optString(arg string, prefixes ...string) (bool, string) {
  91. for _, prefix := range prefixes {
  92. if strings.HasPrefix(arg, prefix) {
  93. return true, arg[len(prefix):]
  94. }
  95. }
  96. return false, ""
  97. }
  98. // optInt grabs the int ...
  99. func (opts *Options) optInt(arg string, prefixes ...string) (bool, int) {
  100. for _, prefix := range prefixes {
  101. if strings.HasPrefix(arg, prefix) {
  102. i, err := strconv.Atoi(arg[len(prefix):])
  103. if err != nil {
  104. opts.failF("Invalid %s int option\n", prefix)
  105. }
  106. return true, i
  107. }
  108. }
  109. return false, 0
  110. }
  111. // newOpts generates opts and parses arguments
  112. func newOpts(args []string) *Options {
  113. opts, err := defaultOptions()
  114. if err != nil {
  115. opts.failF("%v", err)
  116. }
  117. err = opts.parseOptions(args)
  118. if err != nil {
  119. opts.failF("%v", err)
  120. }
  121. return opts
  122. }
  123. // deafultOptions provides the default options
  124. func defaultOptions() (*Options, error) {
  125. return &Options{
  126. Concurrency: 10,
  127. B64EntropyCutoff: 70,
  128. HexEntropyCutoff: 40,
  129. }, nil
  130. }
  131. // parseOptions
  132. func (opts *Options) parseOptions(args []string) error {
  133. if len(args) == 0 {
  134. opts.LocalMode = true
  135. opts.RepoPath, _ = os.Getwd()
  136. }
  137. for i := 0; i < len(args); i++ {
  138. arg := args[i]
  139. switch arg {
  140. case "-s":
  141. opts.SinceCommit = opts.nextString(args, &i)
  142. case "--strict":
  143. opts.Strict = true
  144. case "-b", "--b64Entropy":
  145. opts.B64EntropyCutoff = opts.nextInt(args, &i)
  146. case "-x", "--hexEntropy":
  147. opts.HexEntropyCutoff = opts.nextInt(args, &i)
  148. case "-e", "--entropy":
  149. opts.Entropy = true
  150. case "-c":
  151. opts.Concurrency = opts.nextInt(args, &i)
  152. case "-o", "--org":
  153. opts.OrgMode = true
  154. case "-u", "--user":
  155. opts.UserMode = true
  156. case "-r", "--repo":
  157. opts.RepoMode = true
  158. case "-l", "--local":
  159. opts.LocalMode = true
  160. case "--report-out":
  161. opts.ReportOut = true
  162. case "--pretty":
  163. opts.PrettyPrint = true
  164. case "-t", "--temp":
  165. opts.Tmp = true
  166. case "-ll":
  167. opts.LogLevel = opts.nextInt(args, &i)
  168. case "-h", "--help":
  169. help()
  170. os.Exit(EXIT_CLEAN)
  171. default:
  172. if match, value := opts.optString(arg, "--token="); match {
  173. opts.Token = value
  174. } else if match, value := opts.optString(arg, "--since="); match {
  175. opts.SinceCommit = value
  176. } else if match, value := opts.optString(arg, "--report-path="); match {
  177. opts.ReportPath = value
  178. } else if match, value := opts.optString(arg, "--clone-path="); match {
  179. opts.ClonePath = value
  180. } else if match, value := opts.optInt(arg, "--log="); match {
  181. opts.LogLevel = value
  182. } else if match, value := opts.optInt(arg, "--b64Entropy="); match {
  183. opts.B64EntropyCutoff = value
  184. } else if match, value := opts.optInt(arg, "--hexEntropy="); match {
  185. opts.HexEntropyCutoff = value
  186. } else if i == len(args)-1 {
  187. fmt.Println(args[i])
  188. if opts.LocalMode {
  189. opts.RepoPath = filepath.Clean(args[i])
  190. } else {
  191. if isGithubTarget(args[i]) {
  192. opts.URL = args[i]
  193. } else {
  194. fmt.Printf("Unknown option %s\n\n", arg)
  195. help()
  196. os.Exit(EXIT_CLEAN)
  197. }
  198. }
  199. } else {
  200. fmt.Printf("Unknown option %s\n\n", arg)
  201. help()
  202. return fmt.Errorf("Unknown option %s\n\n", arg)
  203. }
  204. }
  205. }
  206. err := opts.guards()
  207. if !opts.RepoMode && !opts.UserMode && !opts.OrgMode && !opts.LocalMode {
  208. if opts.URL != "" {
  209. opts.RepoMode = true
  210. return nil
  211. }
  212. pwd, _ = os.Getwd()
  213. // check if pwd contains a .git, if it does, run local mode
  214. dotGitPath := filepath.Join(pwd, ".git")
  215. if _, err := os.Stat(dotGitPath); os.IsNotExist(err) {
  216. fmt.Printf("gitleaks has no target")
  217. os.Exit(EXIT_CLEAN)
  218. } else {
  219. opts.LocalMode = true
  220. opts.RepoPath = pwd
  221. opts.RepoMode = false
  222. }
  223. }
  224. return err
  225. }
  226. // failF prints a failure message out to stderr, displays help
  227. // and exits with a exit code 2
  228. func (opts *Options) failF(format string, args ...interface{}) {
  229. fmt.Fprintf(os.Stderr, format, args...)
  230. help()
  231. os.Exit(EXIT_FAILURE)
  232. }
  233. // guards will prevent gitleaks from continuing if any invalid options
  234. // are found.
  235. func (opts *Options) guards() error {
  236. if (opts.RepoMode || opts.OrgMode || opts.UserMode) && opts.LocalMode {
  237. return fmt.Errorf("Cannot run Gitleaks on repo/user/org mode and local mode\n")
  238. } else if (opts.RepoMode || opts.OrgMode || opts.UserMode) && !isGithubTarget(opts.URL) {
  239. return fmt.Errorf("Not valid github target %s\n", opts.URL)
  240. } else if (opts.RepoMode || opts.UserMode) && opts.OrgMode {
  241. return fmt.Errorf("Cannot run Gitleaks on more than one mode\n")
  242. } else if (opts.OrgMode || opts.UserMode) && opts.RepoMode {
  243. return fmt.Errorf("Cannot run Gitleaks on more than one mode\n")
  244. } else if (opts.OrgMode || opts.RepoMode) && opts.UserMode {
  245. return fmt.Errorf("Cannot run Gitleaks on more than one mode\n")
  246. } else if opts.LocalMode && opts.Tmp {
  247. return fmt.Errorf("Cannot run Gitleaks with temp settings and local mode\n")
  248. } else if opts.SinceCommit != "" && (opts.OrgMode || opts.UserMode) {
  249. return fmt.Errorf("Cannot run Gitleaks with since commit flag and a owner mode\n")
  250. }
  251. return nil
  252. }
  253. // isGithubTarget checks if url is a valid github target
  254. func isGithubTarget(url string) bool {
  255. re := regexp.MustCompile("github.com")
  256. return re.MatchString(url)
  257. }