manager.go 6.4 KB

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