manager.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package manager
  2. import (
  3. "crypto/sha1"
  4. "encoding/csv"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "os"
  9. "os/signal"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "text/tabwriter"
  14. "time"
  15. "github.com/zricethezav/gitleaks/v5/config"
  16. "github.com/zricethezav/gitleaks/v5/options"
  17. "github.com/go-git/go-git/v5"
  18. "github.com/hako/durafmt"
  19. "github.com/mattn/go-colorable"
  20. log "github.com/sirupsen/logrus"
  21. )
  22. const maxLineLen = 200
  23. // Manager is a struct containing options and configs as well CloneOptions and CloneDir.
  24. // This struct is passed into each NewRepo so we are not passing around the manager in func params.
  25. type Manager struct {
  26. Opts options.Options
  27. Config config.Config
  28. CloneOptions *git.CloneOptions
  29. CloneDir string
  30. leaks []Leak
  31. leakChan chan Leak
  32. leakWG *sync.WaitGroup
  33. leakCache map[string]bool
  34. stopChan chan os.Signal
  35. metadata Metadata
  36. metaWG *sync.WaitGroup
  37. }
  38. // Leak is a struct that contains information about some line of code that contains
  39. // sensitive information as determined by the rules set in a gitleaks config
  40. type Leak struct {
  41. Line string `json:"line"`
  42. LineNumber int `json:"lineNumber"`
  43. Offender string `json:"offender"`
  44. Commit string `json:"commit"`
  45. Repo string `json:"repo"`
  46. Rule string `json:"rule"`
  47. Message string `json:"commitMessage"`
  48. Author string `json:"author"`
  49. Email string `json:"email"`
  50. File string `json:"file"`
  51. Date time.Time `json:"date"`
  52. Tags string `json:"tags"`
  53. Operation string `json:"operation"`
  54. lookupHash string
  55. }
  56. // ScanTime is a type used to determine total scan time
  57. type ScanTime int64
  58. // PatchTime is a type used to determine total patch time during an scan
  59. type PatchTime int64
  60. // CloneTime is a type used to determine total clone time
  61. type CloneTime int64
  62. // RegexTime is a type used to determine the time each rules' regex takes. This is especially useful
  63. // if you notice that gitleaks is taking a long time. You can use --debug to see the output of the regexTime
  64. // so you can determine which regex is not performing well.
  65. type RegexTime struct {
  66. Time int64
  67. Regex string
  68. }
  69. // Metadata is a struct used to communicate metadata about an scan like timings and total commit counts.
  70. type Metadata struct {
  71. mux *sync.Mutex
  72. data map[string]interface{}
  73. timings chan interface{}
  74. RegexTime map[string]int64
  75. Commits int
  76. ScanTime int64
  77. patchTime int64
  78. cloneTime int64
  79. }
  80. func init() {
  81. log.SetOutput(os.Stdout)
  82. log.SetFormatter(&log.TextFormatter{
  83. ForceColors: true,
  84. FullTimestamp: true,
  85. })
  86. // Fix colors on Windows
  87. if runtime.GOOS == "windows" {
  88. log.SetOutput(colorable.NewColorableStdout())
  89. }
  90. }
  91. // NewManager accepts options and returns a manager struct. The manager is a container for gitleaks configurations,
  92. // options and channel receivers.
  93. func NewManager(opts options.Options, cfg config.Config) (*Manager, error) {
  94. cloneOpts, err := opts.CloneOptions()
  95. if err != nil {
  96. return nil, err
  97. }
  98. m := &Manager{
  99. Opts: opts,
  100. Config: cfg,
  101. CloneOptions: cloneOpts,
  102. stopChan: make(chan os.Signal, 1),
  103. leakChan: make(chan Leak),
  104. leakWG: &sync.WaitGroup{},
  105. leakCache: make(map[string]bool),
  106. metaWG: &sync.WaitGroup{},
  107. metadata: Metadata{
  108. RegexTime: make(map[string]int64),
  109. timings: make(chan interface{}),
  110. data: make(map[string]interface{}),
  111. mux: new(sync.Mutex),
  112. },
  113. }
  114. signal.Notify(m.stopChan, os.Interrupt)
  115. // start receiving leaks and metadata
  116. go m.receiveLeaks()
  117. go m.receiveMetadata()
  118. go m.receiveInterrupt()
  119. return m, nil
  120. }
  121. // GetLeaks returns all available leaks
  122. func (manager *Manager) GetLeaks() []Leak {
  123. // need to wait for any straggling leaks
  124. manager.leakWG.Wait()
  125. return manager.leaks
  126. }
  127. // SendLeaks accepts a leak and is used by the scan pkg. This is the public function
  128. // that allows other packages to send leaks to the manager.
  129. func (manager *Manager) SendLeaks(l Leak) {
  130. if len(l.Line) > maxLineLen {
  131. l.Line = l.Line[0:maxLineLen-1] + "..."
  132. }
  133. if len(l.Offender) > maxLineLen {
  134. l.Offender = l.Offender[0:maxLineLen-1] + "..."
  135. }
  136. h := sha1.New()
  137. h.Write([]byte(l.Commit + l.Offender + l.File + l.Line + string(l.LineNumber)))
  138. l.lookupHash = hex.EncodeToString(h.Sum(nil))
  139. if manager.Opts.Redact {
  140. l.Line = strings.ReplaceAll(l.Line, l.Offender, "REDACTED")
  141. l.Offender = "REDACTED"
  142. }
  143. manager.leakWG.Add(1)
  144. manager.leakChan <- l
  145. }
  146. func (manager *Manager) alreadySeen(leak Leak) bool {
  147. if _, ok := manager.leakCache[leak.lookupHash]; ok {
  148. return true
  149. }
  150. manager.leakCache[leak.lookupHash] = true
  151. return false
  152. }
  153. // receiveLeaks listens to leakChan for incoming leaks. If any are received, they are appended to the
  154. // manager's leaks for future reporting. If the -v/--verbose option is set the leaks will marshaled into
  155. // json and printed out.
  156. func (manager *Manager) receiveLeaks() {
  157. for leak := range manager.leakChan {
  158. if manager.alreadySeen(leak) {
  159. manager.leakWG.Done()
  160. continue
  161. }
  162. manager.leaks = append(manager.leaks, leak)
  163. if manager.Opts.Verbose {
  164. var b []byte
  165. if manager.Opts.PrettyPrint {
  166. b, _ = json.MarshalIndent(leak, "", " ")
  167. } else {
  168. b, _ = json.Marshal(leak)
  169. }
  170. fmt.Println(string(b))
  171. }
  172. manager.leakWG.Done()
  173. }
  174. }
  175. // GetMetadata returns the metadata. TODO this may not need to be private
  176. func (manager *Manager) GetMetadata() Metadata {
  177. manager.metaWG.Wait()
  178. return manager.metadata
  179. }
  180. // receiveMetadata is where the messages sent to the metadata channel get consumed. You can view metadata
  181. // by running gitleaks with the --debug option set. This is extremely useful when trying to optimize regular
  182. // expressions as that what gitleaks spends most of its cycles on.
  183. func (manager *Manager) receiveMetadata() {
  184. for t := range manager.metadata.timings {
  185. switch ti := t.(type) {
  186. case CloneTime:
  187. manager.metadata.cloneTime += int64(ti)
  188. case ScanTime:
  189. manager.metadata.ScanTime += int64(ti)
  190. case PatchTime:
  191. manager.metadata.patchTime += int64(ti)
  192. case RegexTime:
  193. manager.metadata.RegexTime[ti.Regex] = manager.metadata.RegexTime[ti.Regex] + ti.Time
  194. }
  195. manager.metaWG.Done()
  196. }
  197. }
  198. // IncrementCommits increments total commits during an scan by i.
  199. func (manager *Manager) IncrementCommits(i int) {
  200. manager.metadata.mux.Lock()
  201. manager.metadata.Commits += i
  202. manager.metadata.mux.Unlock()
  203. }
  204. // RecordTime accepts an interface and sends it to the manager's time channel
  205. func (manager *Manager) RecordTime(t interface{}) {
  206. manager.metaWG.Add(1)
  207. manager.metadata.timings <- t
  208. }
  209. // DebugOutput logs metadata and other messages that occurred during a gitleaks scan
  210. func (manager *Manager) DebugOutput() {
  211. log.Debugf("-------------------------\n")
  212. log.Debugf("| Times and Commit Counts|\n")
  213. log.Debugf("-------------------------\n")
  214. fmt.Println("totalScanTime: ", durafmt.Parse(time.Duration(manager.metadata.ScanTime)*time.Nanosecond))
  215. fmt.Println("totalPatchTime: ", durafmt.Parse(time.Duration(manager.metadata.patchTime)*time.Nanosecond))
  216. fmt.Println("totalCloneTime: ", durafmt.Parse(time.Duration(manager.metadata.cloneTime)*time.Nanosecond))
  217. fmt.Println("totalCommits: ", manager.metadata.Commits)
  218. const padding = 6
  219. w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '.', 0)
  220. log.Debugf("--------------------------\n")
  221. log.Debugf("| Individual Regex Times |\n")
  222. log.Debugf("--------------------------\n")
  223. for k, v := range manager.metadata.RegexTime {
  224. _, _ = fmt.Fprintf(w, "%s\t%s\n", k, durafmt.Parse(time.Duration(v)*time.Nanosecond))
  225. }
  226. _ = w.Flush()
  227. }
  228. // Report saves gitleaks leaks to a json specified by --report={report.json}
  229. func (manager *Manager) Report() error {
  230. close(manager.leakChan)
  231. close(manager.metadata.timings)
  232. if log.IsLevelEnabled(log.DebugLevel) {
  233. manager.DebugOutput()
  234. }
  235. if manager.Opts.Report != "" {
  236. if len(manager.GetLeaks()) == 0 {
  237. log.Infof("no leaks found, skipping writing report")
  238. return nil
  239. }
  240. file, err := os.Create(manager.Opts.Report)
  241. if err != nil {
  242. return err
  243. }
  244. if manager.Opts.ReportFormat == "json" {
  245. encoder := json.NewEncoder(file)
  246. encoder.SetIndent("", " ")
  247. err = encoder.Encode(manager.leaks)
  248. if err != nil {
  249. return err
  250. }
  251. } else {
  252. w := csv.NewWriter(file)
  253. _ = w.Write([]string{"repo", "line", "commit", "offender", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
  254. for _, leak := range manager.GetLeaks() {
  255. w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
  256. }
  257. w.Flush()
  258. }
  259. _ = file.Close()
  260. log.Infof("report written to %s", manager.Opts.Report)
  261. }
  262. return nil
  263. }
  264. func (manager *Manager) receiveInterrupt() {
  265. <-manager.stopChan
  266. if manager.Opts.Report != "" {
  267. err := manager.Report()
  268. if err != nil {
  269. log.Error(err)
  270. }
  271. }
  272. log.Info("gitleaks received interrupt, stopping scan")
  273. os.Exit(options.ErrorEncountered)
  274. }