utils.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package detect
  2. import (
  3. // "encoding/json"
  4. "fmt"
  5. "math"
  6. "path/filepath"
  7. "strings"
  8. "github.com/zricethezav/gitleaks/v8/cmd/scm"
  9. "github.com/zricethezav/gitleaks/v8/logging"
  10. "github.com/zricethezav/gitleaks/v8/report"
  11. "github.com/zricethezav/gitleaks/v8/sources"
  12. "github.com/charmbracelet/lipgloss"
  13. )
  14. var linkCleaner = strings.NewReplacer(
  15. " ", "%20",
  16. "%", "%25",
  17. )
  18. func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
  19. if remote.Platform == scm.UnknownPlatform ||
  20. remote.Platform == scm.NoPlatform ||
  21. finding.Commit == "" {
  22. return ""
  23. }
  24. // Clean the path.
  25. filePath, _, hasInnerPath := strings.Cut(finding.File, sources.InnerPathSeparator)
  26. filePath = linkCleaner.Replace(filePath)
  27. switch remote.Platform {
  28. case scm.GitHubPlatform:
  29. link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
  30. if hasInnerPath {
  31. return link
  32. }
  33. ext := strings.ToLower(filepath.Ext(filePath))
  34. if ext == ".ipynb" || ext == ".md" {
  35. link += "?plain=1"
  36. }
  37. if finding.StartLine != 0 {
  38. link += fmt.Sprintf("#L%d", finding.StartLine)
  39. }
  40. if finding.EndLine != finding.StartLine {
  41. link += fmt.Sprintf("-L%d", finding.EndLine)
  42. }
  43. return link
  44. case scm.GitLabPlatform:
  45. link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
  46. if hasInnerPath {
  47. return link
  48. }
  49. if finding.StartLine != 0 {
  50. link += fmt.Sprintf("#L%d", finding.StartLine)
  51. }
  52. if finding.EndLine != finding.StartLine {
  53. link += fmt.Sprintf("-%d", finding.EndLine)
  54. }
  55. return link
  56. case scm.AzureDevOpsPlatform:
  57. link := fmt.Sprintf("%s/commit/%s?path=/%s", remote.Url, finding.Commit, filePath)
  58. // Add line information if applicable
  59. if hasInnerPath {
  60. return link
  61. }
  62. if finding.StartLine != 0 {
  63. link += fmt.Sprintf("&line=%d", finding.StartLine)
  64. }
  65. if finding.EndLine != finding.StartLine {
  66. link += fmt.Sprintf("&lineEnd=%d", finding.EndLine)
  67. }
  68. // This is a bit dirty, but Azure DevOps does not highlight the line when the lineStartColumn and lineEndColumn are not provided
  69. link += "&lineStartColumn=1&lineEndColumn=10000000&type=2&lineStyle=plain&_a=files"
  70. return link
  71. default:
  72. // This should never happen.
  73. return ""
  74. }
  75. }
  76. // shannonEntropy calculates the entropy of data using the formula defined here:
  77. // https://en.wiktionary.org/wiki/Shannon_entropy
  78. // Another way to think about what this is doing is calculating the number of bits
  79. // needed to on average encode the data. So, the higher the entropy, the more random the data, the
  80. // more bits needed to encode that data.
  81. func shannonEntropy(data string) (entropy float64) {
  82. if data == "" {
  83. return 0
  84. }
  85. charCounts := make(map[rune]int)
  86. for _, char := range data {
  87. charCounts[char]++
  88. }
  89. invLength := 1.0 / float64(len(data))
  90. for _, count := range charCounts {
  91. freq := float64(count) * invLength
  92. entropy -= freq * math.Log2(freq)
  93. }
  94. return entropy
  95. }
  96. // filter will dedupe and redact findings
  97. func filter(findings []report.Finding, redact uint) []report.Finding {
  98. var retFindings []report.Finding
  99. for _, f := range findings {
  100. include := true
  101. if strings.Contains(strings.ToLower(f.RuleID), "generic") {
  102. for _, fPrime := range findings {
  103. if f.StartLine == fPrime.StartLine &&
  104. f.Commit == fPrime.Commit &&
  105. f.RuleID != fPrime.RuleID &&
  106. strings.Contains(fPrime.Secret, f.Secret) &&
  107. !strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
  108. genericMatch := strings.ReplaceAll(f.Match, f.Secret, "REDACTED")
  109. betterMatch := strings.ReplaceAll(fPrime.Match, fPrime.Secret, "REDACTED")
  110. logging.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
  111. include = false
  112. break
  113. }
  114. }
  115. }
  116. if redact > 0 {
  117. f.Redact(redact)
  118. }
  119. if include {
  120. retFindings = append(retFindings, f)
  121. }
  122. }
  123. return retFindings
  124. }
  125. func printFinding(f report.Finding, noColor bool) {
  126. // trim all whitespace and tabs
  127. f.Line = strings.TrimSpace(f.Line)
  128. f.Secret = strings.TrimSpace(f.Secret)
  129. f.Match = strings.TrimSpace(f.Match)
  130. isFileMatch := strings.HasPrefix(f.Match, "file detected:")
  131. skipColor := noColor
  132. finding := ""
  133. var secret lipgloss.Style
  134. // Matches from filenames do not have a |line| or |secret|
  135. if !isFileMatch {
  136. matchInLineIDX := strings.Index(f.Line, f.Match)
  137. secretInMatchIdx := strings.Index(f.Match, f.Secret)
  138. skipColor = false
  139. if matchInLineIDX == -1 || noColor {
  140. skipColor = true
  141. matchInLineIDX = 0
  142. }
  143. start := f.Line[0:matchInLineIDX]
  144. startMatchIdx := 0
  145. if matchInLineIDX > 20 {
  146. startMatchIdx = matchInLineIDX - 20
  147. start = "..." + f.Line[startMatchIdx:matchInLineIDX]
  148. }
  149. matchBeginning := lipgloss.NewStyle().SetString(f.Match[0:secretInMatchIdx]).Foreground(lipgloss.Color("#f5d445"))
  150. secret = lipgloss.NewStyle().SetString(f.Secret).
  151. Bold(true).
  152. Italic(true).
  153. Foreground(lipgloss.Color("#f05c07"))
  154. matchEnd := lipgloss.NewStyle().SetString(f.Match[secretInMatchIdx+len(f.Secret):]).Foreground(lipgloss.Color("#f5d445"))
  155. lineEndIdx := matchInLineIDX + len(f.Match)
  156. if len(f.Line)-1 <= lineEndIdx {
  157. lineEndIdx = len(f.Line)
  158. }
  159. lineEnd := f.Line[lineEndIdx:]
  160. if len(f.Secret) > 100 {
  161. secret = lipgloss.NewStyle().SetString(f.Secret[0:100] + "...").
  162. Bold(true).
  163. Italic(true).
  164. Foreground(lipgloss.Color("#f05c07"))
  165. }
  166. if len(lineEnd) > 20 {
  167. lineEnd = lineEnd[0:20] + "..."
  168. }
  169. finding = fmt.Sprintf("%s%s%s%s%s\n", strings.TrimPrefix(strings.TrimLeft(start, " "), "\n"), matchBeginning, secret, matchEnd, lineEnd)
  170. }
  171. if skipColor || isFileMatch {
  172. fmt.Printf("%-12s %s\n", "Finding:", f.Match)
  173. fmt.Printf("%-12s %s\n", "Secret:", f.Secret)
  174. } else {
  175. fmt.Printf("%-12s %s", "Finding:", finding)
  176. fmt.Printf("%-12s %s\n", "Secret:", secret)
  177. }
  178. fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID)
  179. fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy)
  180. if f.File == "" {
  181. fmt.Println("")
  182. return
  183. }
  184. if len(f.Tags) > 0 {
  185. fmt.Printf("%-12s %s\n", "Tags:", f.Tags)
  186. }
  187. fmt.Printf("%-12s %s\n", "File:", f.File)
  188. fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
  189. if f.Commit == "" {
  190. fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
  191. fmt.Println("")
  192. return
  193. }
  194. fmt.Printf("%-12s %s\n", "Commit:", f.Commit)
  195. fmt.Printf("%-12s %s\n", "Author:", f.Author)
  196. fmt.Printf("%-12s %s\n", "Email:", f.Email)
  197. fmt.Printf("%-12s %s\n", "Date:", f.Date)
  198. fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
  199. if f.Link != "" {
  200. fmt.Printf("%-12s %s\n", "Link:", f.Link)
  201. }
  202. fmt.Println("")
  203. }