manager.go 8.6 KB

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