manager.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. var b []byte
  101. if manager.Opts.PrettyPrint {
  102. b, _ = json.MarshalIndent(leak, "", " ")
  103. } else {
  104. b, _ = json.Marshal(leak)
  105. }
  106. fmt.Println(string(b))
  107. }
  108. manager.leakWG.Done()
  109. }
  110. }
  111. // GetMetadata returns the metadata. TODO this may not need to be private
  112. func (manager *Manager) GetMetadata() Metadata {
  113. return manager.metadata
  114. }
  115. // receiveMetadata is where the messages sent to the metadata channel get consumed. You can view metadata
  116. // by running gitleaks with the --debug option set. This is extremely useful when trying to optimize regular
  117. // expressions as that what gitleaks spends most of its cycles on.
  118. func (manager *Manager) receiveMetadata() {
  119. for t := range manager.metadata.timings {
  120. switch ti := t.(type) {
  121. case CloneTime:
  122. manager.metadata.cloneTime += int64(ti)
  123. case AuditTime:
  124. manager.metadata.AuditTime += int64(ti)
  125. case PatchTime:
  126. manager.metadata.patchTime += int64(ti)
  127. case RegexTime:
  128. manager.metadata.RegexTime[ti.Regex] = manager.metadata.RegexTime[ti.Regex] + ti.Time
  129. }
  130. }
  131. }
  132. // IncrementCommits increments total commits during an audit by i.
  133. func (manager *Manager) IncrementCommits(i int) {
  134. manager.metadata.mux.Lock()
  135. manager.metadata.Commits += i
  136. manager.metadata.mux.Unlock()
  137. }
  138. // RecordTime accepts an interface and sends it to the manager's time channel
  139. func (manager *Manager) RecordTime(t interface{}) {
  140. manager.metadata.timings <- t
  141. }
  142. // NewManager accepts options and returns a manager struct. The manager is a container for gitleaks configurations,
  143. // options and channel receivers.
  144. func NewManager(opts options.Options, cfg config.Config) (*Manager, error) {
  145. cloneOpts, err := opts.CloneOptions()
  146. if err != nil {
  147. return nil, err
  148. }
  149. m := &Manager{
  150. Opts: opts,
  151. Config: cfg,
  152. CloneOptions: cloneOpts,
  153. stopChan: make(chan os.Signal, 1),
  154. leakChan: make(chan Leak),
  155. leakWG: &sync.WaitGroup{},
  156. metadata: Metadata{
  157. RegexTime: make(map[string]int64),
  158. timings: make(chan interface{}),
  159. data: make(map[string]interface{}),
  160. },
  161. }
  162. signal.Notify(m.stopChan, os.Interrupt)
  163. // start receiving leaks and metadata
  164. go m.receiveLeaks()
  165. go m.receiveMetadata()
  166. go m.receiveInterrupt()
  167. return m, nil
  168. }
  169. // DebugOutput logs metadata and other messages that occurred during a gitleaks audit
  170. func (manager *Manager) DebugOutput() {
  171. log.Debugf("-------------------------\n")
  172. log.Debugf("| Times and Commit Counts|\n")
  173. log.Debugf("-------------------------\n")
  174. fmt.Println("totalAuditTime: ", durafmt.Parse(time.Duration(manager.metadata.AuditTime)*time.Nanosecond))
  175. fmt.Println("totalPatchTime: ", durafmt.Parse(time.Duration(manager.metadata.patchTime)*time.Nanosecond))
  176. fmt.Println("totalCloneTime: ", durafmt.Parse(time.Duration(manager.metadata.cloneTime)*time.Nanosecond))
  177. fmt.Println("totalCommits: ", manager.metadata.Commits)
  178. const padding = 6
  179. w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '.', 0)
  180. log.Debugf("--------------------------\n")
  181. log.Debugf("| Individual Regex Times |\n")
  182. log.Debugf("--------------------------\n")
  183. for k, v := range manager.metadata.RegexTime {
  184. fmt.Fprintf(w, "%s\t%s\n", k, durafmt.Parse(time.Duration(v)*time.Nanosecond))
  185. }
  186. w.Flush()
  187. }
  188. // Report saves gitleaks leaks to a json specified by --report={report.json}
  189. func (manager *Manager) Report() error {
  190. close(manager.leakChan)
  191. close(manager.metadata.timings)
  192. if log.IsLevelEnabled(log.DebugLevel) {
  193. manager.DebugOutput()
  194. }
  195. if manager.Opts.Report != "" {
  196. if len(manager.GetLeaks()) == 0 {
  197. log.Infof("no leaks found, skipping writing report")
  198. return nil
  199. }
  200. file, err := os.Create(manager.Opts.Report)
  201. if err != nil {
  202. return err
  203. }
  204. encoder := json.NewEncoder(file)
  205. encoder.SetIndent("", " ")
  206. err = encoder.Encode(manager.leaks)
  207. if err != nil {
  208. return err
  209. }
  210. err = file.Close()
  211. if err != nil {
  212. return err
  213. }
  214. log.Infof("report written to %s", manager.Opts.Report)
  215. }
  216. return nil
  217. }
  218. func (manager *Manager) receiveInterrupt() {
  219. <-manager.stopChan
  220. if manager.Opts.Report != "" {
  221. err := manager.Report()
  222. if err != nil {
  223. log.Error(err)
  224. }
  225. }
  226. log.Info("gitleaks received interrupt, stopping audit")
  227. os.Exit(options.ErrorEncountered)
  228. }