manager.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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/config"
  15. "github.com/zricethezav/gitleaks/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. // GetLeaks returns all available leaks
  89. func (manager *Manager) GetLeaks() []Leak {
  90. // need to wait for any straggling leaks
  91. manager.leakWG.Wait()
  92. return manager.leaks
  93. }
  94. // SendLeaks accepts a leak and is used by the audit pkg. This is the public function
  95. // that allows other packages to send leaks to the manager.
  96. func (manager *Manager) SendLeaks(l Leak) {
  97. if len(l.Line) > maxLineLen {
  98. l.Line = l.Line[0:maxLineLen-1] + "..."
  99. }
  100. if len(l.Offender) > maxLineLen {
  101. l.Offender = l.Offender[0:maxLineLen-1] + "..."
  102. }
  103. h := sha1.New()
  104. h.Write([]byte(l.Commit + l.Offender + l.File))
  105. l.lookupHash = hex.EncodeToString(h.Sum(nil))
  106. manager.leakWG.Add(1)
  107. manager.leakChan <- l
  108. }
  109. func (manager *Manager) alreadySeen(leak Leak) bool {
  110. if _, ok := manager.leakCache[leak.lookupHash]; ok {
  111. return true
  112. }
  113. manager.leakCache[leak.lookupHash] = true
  114. return false
  115. }
  116. // receiveLeaks listens to leakChan for incoming leaks. If any are received, they are appended to the
  117. // manager's leaks for future reporting. If the -v/--verbose option is set the leaks will marshaled into
  118. // json and printed out.
  119. func (manager *Manager) receiveLeaks() {
  120. for leak := range manager.leakChan {
  121. if manager.alreadySeen(leak) {
  122. manager.leakWG.Done()
  123. continue
  124. }
  125. manager.leaks = append(manager.leaks, leak)
  126. if manager.Opts.Verbose {
  127. var b []byte
  128. if manager.Opts.PrettyPrint {
  129. b, _ = json.MarshalIndent(leak, "", " ")
  130. } else {
  131. b, _ = json.Marshal(leak)
  132. }
  133. fmt.Println(string(b))
  134. }
  135. manager.leakWG.Done()
  136. }
  137. }
  138. // GetMetadata returns the metadata. TODO this may not need to be private
  139. func (manager *Manager) GetMetadata() Metadata {
  140. manager.metaWG.Wait()
  141. return manager.metadata
  142. }
  143. // receiveMetadata is where the messages sent to the metadata channel get consumed. You can view metadata
  144. // by running gitleaks with the --debug option set. This is extremely useful when trying to optimize regular
  145. // expressions as that what gitleaks spends most of its cycles on.
  146. func (manager *Manager) receiveMetadata() {
  147. for t := range manager.metadata.timings {
  148. switch ti := t.(type) {
  149. case CloneTime:
  150. manager.metadata.cloneTime += int64(ti)
  151. case AuditTime:
  152. manager.metadata.AuditTime += int64(ti)
  153. case PatchTime:
  154. manager.metadata.patchTime += int64(ti)
  155. case RegexTime:
  156. manager.metadata.RegexTime[ti.Regex] = manager.metadata.RegexTime[ti.Regex] + ti.Time
  157. }
  158. manager.metaWG.Done()
  159. }
  160. }
  161. // IncrementCommits increments total commits during an audit by i.
  162. func (manager *Manager) IncrementCommits(i int) {
  163. manager.metadata.mux.Lock()
  164. manager.metadata.Commits += i
  165. manager.metadata.mux.Unlock()
  166. }
  167. // RecordTime accepts an interface and sends it to the manager's time channel
  168. func (manager *Manager) RecordTime(t interface{}) {
  169. manager.metaWG.Add(1)
  170. manager.metadata.timings <- t
  171. }
  172. // NewManager accepts options and returns a manager struct. The manager is a container for gitleaks configurations,
  173. // options and channel receivers.
  174. func NewManager(opts options.Options, cfg config.Config) (*Manager, error) {
  175. cloneOpts, err := opts.CloneOptions()
  176. if err != nil {
  177. return nil, err
  178. }
  179. m := &Manager{
  180. Opts: opts,
  181. Config: cfg,
  182. CloneOptions: cloneOpts,
  183. stopChan: make(chan os.Signal, 1),
  184. leakChan: make(chan Leak),
  185. leakWG: &sync.WaitGroup{},
  186. leakCache: make(map[string]bool),
  187. metaWG: &sync.WaitGroup{},
  188. metadata: Metadata{
  189. RegexTime: make(map[string]int64),
  190. timings: make(chan interface{}),
  191. data: make(map[string]interface{}),
  192. },
  193. }
  194. signal.Notify(m.stopChan, os.Interrupt)
  195. // start receiving leaks and metadata
  196. go m.receiveLeaks()
  197. go m.receiveMetadata()
  198. go m.receiveInterrupt()
  199. return m, nil
  200. }
  201. // DebugOutput logs metadata and other messages that occurred during a gitleaks audit
  202. func (manager *Manager) DebugOutput() {
  203. log.Debugf("-------------------------\n")
  204. log.Debugf("| Times and Commit Counts|\n")
  205. log.Debugf("-------------------------\n")
  206. fmt.Println("totalAuditTime: ", durafmt.Parse(time.Duration(manager.metadata.AuditTime)*time.Nanosecond))
  207. fmt.Println("totalPatchTime: ", durafmt.Parse(time.Duration(manager.metadata.patchTime)*time.Nanosecond))
  208. fmt.Println("totalCloneTime: ", durafmt.Parse(time.Duration(manager.metadata.cloneTime)*time.Nanosecond))
  209. fmt.Println("totalCommits: ", manager.metadata.Commits)
  210. const padding = 6
  211. w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '.', 0)
  212. log.Debugf("--------------------------\n")
  213. log.Debugf("| Individual Regex Times |\n")
  214. log.Debugf("--------------------------\n")
  215. for k, v := range manager.metadata.RegexTime {
  216. fmt.Fprintf(w, "%s\t%s\n", k, durafmt.Parse(time.Duration(v)*time.Nanosecond))
  217. }
  218. w.Flush()
  219. }
  220. // Report saves gitleaks leaks to a json specified by --report={report.json}
  221. func (manager *Manager) Report() error {
  222. close(manager.leakChan)
  223. close(manager.metadata.timings)
  224. if log.IsLevelEnabled(log.DebugLevel) {
  225. manager.DebugOutput()
  226. }
  227. if manager.Opts.Report != "" {
  228. if len(manager.GetLeaks()) == 0 {
  229. log.Infof("no leaks found, skipping writing report")
  230. return nil
  231. }
  232. file, err := os.Create(manager.Opts.Report)
  233. if err != nil {
  234. return err
  235. }
  236. if manager.Opts.ReportFormat == "json" {
  237. encoder := json.NewEncoder(file)
  238. encoder.SetIndent("", " ")
  239. err = encoder.Encode(manager.leaks)
  240. if err != nil {
  241. return err
  242. }
  243. } else {
  244. w := csv.NewWriter(file)
  245. w.Write([]string{"repo", "line", "commit", "offender", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
  246. for _, leak := range manager.GetLeaks() {
  247. 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)})
  248. }
  249. w.Flush()
  250. }
  251. file.Close()
  252. log.Infof("report written to %s", manager.Opts.Report)
  253. }
  254. return nil
  255. }
  256. func (manager *Manager) receiveInterrupt() {
  257. <-manager.stopChan
  258. if manager.Opts.Report != "" {
  259. err := manager.Report()
  260. if err != nil {
  261. log.Error(err)
  262. }
  263. }
  264. log.Info("gitleaks received interrupt, stopping audit")
  265. os.Exit(options.ErrorEncountered)
  266. }