| 1 | package websource |
| 2 | |
| 3 | import ( |
| 4 | "net/url" |
| 5 | "regexp" |
| 6 | ) |
| 7 | |
| 8 | // secretPatterns are the credential shapes the runner's redaction knows |
| 9 | // (runnerproto.RedactText and RedactDetail: bearer and basic values, |
| 10 | // credential-named assignments, sk-, ghp_ and github_pat_ prefixes, JSON |
| 11 | // web tokens), plus other common key prefixes and private key headers. |
| 12 | var secretPatterns = []*regexp.Regexp{ |
| 13 | regexp.MustCompile(`(?i)\b(?:bearer|basic)(?:\s|%20|\+)+[A-Za-z0-9._~+/=-]{8,}`), |
| 14 | regexp.MustCompile(`(?i)(?:api[_-]?key|access[_-]?key|password|passwd|secret|token|auth)\s*[=:]\s*[^\s,"'<>&/]+`), |
| 15 | regexp.MustCompile(`\b(?:sk|rk|pk)-[A-Za-z0-9_-]{8,}`), |
| 16 | regexp.MustCompile(`\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}`), |
| 17 | regexp.MustCompile(`\bgh[pousr]_[A-Za-z0-9]{16,}`), |
| 18 | regexp.MustCompile(`\bgithub_pat_[A-Za-z0-9_]{16,}`), |
| 19 | regexp.MustCompile(`\bglpat-[A-Za-z0-9_-]{16,}`), |
| 20 | regexp.MustCompile(`\bxox[abposr]-[A-Za-z0-9-]{10,}`), |
| 21 | regexp.MustCompile(`\b(?:AKIA|ASIA)[0-9A-Z]{16}\b`), |
| 22 | regexp.MustCompile(`\bAIza[0-9A-Za-z_-]{30,}`), |
| 23 | regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*`), |
| 24 | regexp.MustCompile(`-----BEGIN|PRIVATE KEY`), |
| 25 | // RedactDetail's long opaque run. |
| 26 | regexp.MustCompile(`[A-Za-z0-9_+]{41,}`), |
| 27 | } |
| 28 | |
| 29 | // opaqueRun is a run that could hold an encoded secret: base64 or hex |
| 30 | // characters, broken by the punctuation that separates words in a path. |
| 31 | var opaqueRun = regexp.MustCompile(`[A-Za-z0-9+=]{24,}`) |
| 32 | |
| 33 | // LooksSecret reports text that matches a credential pattern, or holds a |
| 34 | // high-entropy token: 24 or more letters and digits in a run, with both |
| 35 | // letters and digits and at least 12 different characters. It checks s |
| 36 | // and, when s is percent-encoded, its decoded form too. |
| 37 | func LooksSecret(s string) bool { |
| 38 | if looksSecret(s) { |
| 39 | return true |
| 40 | } |
| 41 | if d, err := url.PathUnescape(s); err == nil && d != s { |
| 42 | return looksSecret(d) |
| 43 | } |
| 44 | return false |
| 45 | } |
| 46 | |
| 47 | func looksSecret(s string) bool { |
| 48 | for _, p := range secretPatterns { |
| 49 | if p.MatchString(s) { |
| 50 | return true |
| 51 | } |
| 52 | } |
| 53 | for _, run := range opaqueRun.FindAllString(s, -1) { |
| 54 | var letter, digit bool |
| 55 | seen := map[rune]bool{} |
| 56 | for _, c := range run { |
| 57 | seen[c] = true |
| 58 | letter = letter || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' |
| 59 | digit = digit || c >= '0' && c <= '9' |
| 60 | } |
| 61 | if letter && digit && len(seen) >= 12 { |
| 62 | return true |
| 63 | } |
| 64 | } |
| 65 | return false |
| 66 | } |
| 67 | |