manager.go 7.2 KB

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