manager.go 8.7 KB

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