manager.go 7.2 KB

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