|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "regexp" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + prefixes = []string{ |
| 14 | + // API Key. |
| 15 | + "aks_[0-9a-f]{20,}", |
| 16 | + // Cluster credentials password. |
| 17 | + "ccp_[0-9a-f]{20,}", |
| 18 | + // Session key secret. |
| 19 | + "sks_[0-9a-f]{20,}", |
| 20 | + } |
| 21 | + |
| 22 | + allowedKeys = map[string]struct{}{} |
| 23 | +) |
| 24 | + |
| 25 | +func main() { |
| 26 | + filesFlag := flag.String("files", "", "Comma-separated list of files to scan") |
| 27 | + flag.Parse() |
| 28 | + |
| 29 | + if *filesFlag == "" { |
| 30 | + fmt.Println("Usage: scanner -files=<comma-separated-files>") |
| 31 | + os.Exit(1) |
| 32 | + } |
| 33 | + |
| 34 | + var ( |
| 35 | + files = strings.Split(*filesFlag, ",") |
| 36 | + prefixPattern = strings.Join(prefixes, "|") |
| 37 | + regex = regexp.MustCompile(prefixPattern) |
| 38 | + ) |
| 39 | + |
| 40 | + hasIssues := false |
| 41 | + for _, file := range files { |
| 42 | + if file == "" { |
| 43 | + continue |
| 44 | + } |
| 45 | + |
| 46 | + f, err := os.Open(file) |
| 47 | + if err != nil { |
| 48 | + fmt.Printf("Error opening file %s: %v\n", file, err) |
| 49 | + os.Exit(1) |
| 50 | + } |
| 51 | + |
| 52 | + scanner := bufio.NewScanner(f) |
| 53 | + lineNumber := 1 |
| 54 | + for scanner.Scan() { |
| 55 | + line := scanner.Text() |
| 56 | + matches := regex.FindAllString(line, -1) |
| 57 | + for _, match := range matches { |
| 58 | + if _, allowed := allowedKeys[match]; allowed { |
| 59 | + continue |
| 60 | + } |
| 61 | + |
| 62 | + fmt.Printf("Found illegal prefix (potential secret?) in %s at line %d: %s\n", file, lineNumber, line) |
| 63 | + hasIssues = true |
| 64 | + } |
| 65 | + lineNumber++ |
| 66 | + } |
| 67 | + |
| 68 | + if err := scanner.Err(); err != nil { |
| 69 | + fmt.Printf("Error reading file %s: %v\n", file, err) |
| 70 | + if closeErr := f.Close(); closeErr != nil { |
| 71 | + fmt.Printf("Error closing file %s: %v\n", file, closeErr) |
| 72 | + } |
| 73 | + os.Exit(1) |
| 74 | + } |
| 75 | + |
| 76 | + if err := f.Close(); err != nil { |
| 77 | + fmt.Printf("Error closing file %s: %v\n", file, err) |
| 78 | + os.Exit(1) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + if hasIssues { |
| 83 | + fmt.Println("Illegal prefixes (potential secret?) found.") |
| 84 | + os.Exit(1) |
| 85 | + } |
| 86 | +} |
0 commit comments