Repository: UndeadSec/DockerSpy Branch: main Commit: 030b4224f428 Files: 8 Total size: 22.2 KB Directory structure: gitextract_iodmuqym/ ├── LICENSE ├── Makefile ├── README.md ├── go.mod ├── go.sum ├── main.go └── src/ └── configs/ ├── ignore_extensions.json └── regex_patterns.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 UndeadSec Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ SRC_DIR = src/ DEST_DIR = /etc/dockerspy BIN_DIR = /usr/local/bin GREEN = \033[0;32m YELLOW = \033[0;33m BLUE = \033[0;34m NC = \033[0m all: build cleanup build: copy-deps @echo "$(BLUE)[#] Building the dockerspy binary...$(NC)" sudo go build -o dockerspy @echo "$(BLUE)[#] Copying the dockerspy binary to $(BIN_DIR)...$(NC)" sudo cp dockerspy $(BIN_DIR) sudo chmod +x $(BIN_DIR)/dockerspy copy-deps: @echo "$(YELLOW)[#] Copying configuration files...$(NC)" sudo mkdir -p $(DEST_DIR) sudo cp -R $(SRC_DIR)* $(DEST_DIR) cleanup: @echo "$(BLUE)[#] Cleaning up...$(NC)" sudo rm -f dockerspy .PHONY: all build copy-deps cleanup all: build cleanup @echo "$(GREEN)[###] Build complete. You can now run dockerspy from the terminal.$(NC)" ================================================ FILE: README.md ================================================ # DockerSpy DockerSpy searches for images on Docker Hub and extracts sensitive information such as authentication secrets, private keys, and more.

### What is Docker? Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization technology. Containers allow developers to package an application and its dependencies into a single, portable unit that can run consistently across various computing environments. Docker simplifies the development and deployment process by ensuring that applications run the same way regardless of where they are deployed. ### About Docker Hub Docker Hub is a cloud-based repository where developers can store, share, and distribute container images. It serves as the largest library of container images, providing access to both official images created by Docker and community-contributed images. Docker Hub enables developers to easily find, download, and deploy pre-built images, facilitating rapid application development and deployment. ### Why OSINT on Docker Hub? Open Source Intelligence (OSINT) on Docker Hub involves using publicly available information to gather insights and data from container images and repositories hosted on Docker Hub. This is particularly important for identifying exposed secrets for several reasons: 1. **Security Audits**: By analyzing Docker images, organizations can uncover exposed secrets such as API keys, authentication tokens, and private keys that might have been inadvertently included. This helps in mitigating potential security risks. 2. **Incident Prevention**: Proactively searching for exposed secrets in Docker images can prevent security breaches before they happen, protecting sensitive information and maintaining the integrity of applications. 3. **Compliance**: Ensuring that container images do not expose secrets is crucial for meeting regulatory and organizational security standards. OSINT helps verify that no sensitive information is unintentionally disclosed. 4. **Vulnerability Assessment**: Identifying exposed secrets as part of regular security assessments allows organizations to address these vulnerabilities promptly, reducing the risk of exploitation by malicious actors. 5. **Enhanced Security Posture**: Continuously monitoring Docker Hub for exposed secrets strengthens an organization's overall security posture, making it more resilient against potential threats. Utilizing OSINT on Docker Hub to find exposed secrets enables organizations to enhance their security measures, prevent data breaches, and ensure the confidentiality of sensitive information within their containerized applications. - [Thousands of images on Docker Hub leak auth secrets, private keys](https://www.bleepingcomputer.com/news/security/thousands-of-images-on-docker-hub-leak-auth-secrets-private-keys/) - [Docker Hub images found to expose secrets and private keys](https://www.threatdown.com/blog/docker-hub-images-found-to-expose-secrets-and-private-keys/) ## How DockerSpy Works DockerSpy obtains information from Docker Hub and uses regular expressions to inspect the content for sensitive information, such as secrets. ## Getting Started To use DockerSpy, follow these steps: 1. **Installation:** Clone the DockerSpy repository and install the required dependencies. ```bash git clone https://github.com/UndeadSec/DockerSpy.git && cd DockerSpy && make ``` 2. **Usage:** Run DockerSpy from terminal. ```bash dockerspy ``` ## Custom Configurations To customize DockerSpy configurations, edit the following files: - [Regular Expressions](src/configs/regex_patterns.json) - [Ignored File Extensions](src/configs/ignore_extensions.json) ## Disclaimer DockerSpy is intended for educational and research purposes only. Users are responsible for ensuring that their use of this tool complies with applicable laws and regulations. ## Contribution Contributions to DockerSpy are welcome! Feel free to submit issues, feature requests, or pull requests to help improve this tool. ## About the Author DockerSpy is developed and maintained by *Alisson Moretto* (UndeadSec) I'm a passionate cyber threat intelligence pro who loves sharing insights and crafting cybersecurity tools. Consider following me: [![X](https://img.shields.io/badge/X-%23000000.svg?style=for-the-badge&logo=X&logoColor=white)](https://twitter.com/UndeadSec) [![LinkedIn](https://img.shields.io/badge/linkedin-%230077B5.svg?style=for-the-badge&logo=linkedin&logoColor=white)](https://linkedin.com/in/alissonmoretto) [![GitHub](https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white)](https://github.com/UndeadSec) ## TODO ### Regular Expressions Enhancement - [ ] Review and improve existing regular expressions. - [ ] Ensure that regular expressions adhere to best practices. - [ ] Check for any potential optimizations in the regex patterns. - [ ] Test regular expressions with various input scenarios for accuracy. - [ ] Document any complex or non-trivial regex patterns for better understanding. ## License DockerSpy is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. ### Thanks Special thanks to [@akaclandestine](https://x.com/akaclandestine) ================================================ FILE: go.mod ================================================ module dockerspy go 1.22 require github.com/fatih/color v1.17.0 require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect golang.org/x/sys v0.22.0 // indirect ) ================================================ FILE: go.sum ================================================ github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= ================================================ FILE: main.go ================================================ package main import ( "archive/tar" "bufio" "compress/gzip" "encoding/json" "fmt" "github.com/fatih/color" "io" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "strings" ) type IgnoreExtensions struct { Extensions []string `json:"extensions"` } type SearchResult struct { NumResults int `json:"count"` Next string `json:"next"` Results []struct { Name string `json:"repo_name"` Description string `json:"short_description"` PullCount int `json:"pull_count"` StarCount int `json:"star_count"` IsOfficial bool `json:"is_official"` } `json:"results"` } type TagsResult struct { Count int `json:"count"` Next string `json:"next"` Previous string `json:"previous"` Results []struct { Name string `json:"name"` } `json:"results"` } const ( dockerHubAPI = "https://registry-1.docker.io/v2/" ) type TokenResponse struct { Token string `json:"token"` } type Manifest struct { Config Descriptor `json:"config"` Layers []Descriptor `json:"layers"` MediaType string `json:"mediaType"` } type Descriptor struct { MediaType string `json:"mediaType"` Size int64 `json:"size"` Digest string `json:"digest"` } func getDockerHubToken(repo string) (string, error) { authURL := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s:pull", repo) resp, err := http.Get(authURL) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("failed to authenticate: %s", resp.Status) } var tokenResponse TokenResponse if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil { return "", err } return tokenResponse.Token, nil } func getManifest(repo, tag, token string) (*Manifest, error) { client := &http.Client{} url := fmt.Sprintf("%s%s/manifests/%s", dockerHubAPI, repo, tag) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json") resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("failed to get manifest: %s", resp.Status) } var manifest Manifest if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil { return nil, err } return &manifest, nil } func downloadLayer(repo, token, digest, outputPath string, size int64) error { client := &http.Client{} url := fmt.Sprintf("%s%s/blobs/%s", dockerHubAPI, repo, digest) req, err := http.NewRequest("GET", url, nil) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+token) resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("failed to download layer: %s", resp.Status) } file, err := os.Create(outputPath) if err != nil { return err } defer file.Close() progressWriter := &ProgressWriter{Writer: file, Total: size} _, err = io.Copy(progressWriter, resp.Body) return err } type ProgressWriter struct { Writer io.Writer Total int64 Downloaded int64 } func (pw *ProgressWriter) Write(p []byte) (int, error) { n, err := pw.Writer.Write(p) pw.Downloaded += int64(n) pw.printProgress() return n, err } func (pw *ProgressWriter) printProgress() { percent := float64(pw.Downloaded) / float64(pw.Total) * 100 fmt.Printf("\rDownloading... %.2f%% complete", percent) } func loadRegexPatterns(filename string) (map[string]*regexp.Regexp, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() var patterns map[string]string decoder := json.NewDecoder(file) if err := decoder.Decode(&patterns); err != nil { return nil, err } regexPatterns := make(map[string]*regexp.Regexp) for name, pattern := range patterns { re, err := regexp.Compile(pattern) if err != nil { return nil, fmt.Errorf("failed to compile regex %s: %v", name, err) } regexPatterns[name] = re } return regexPatterns, nil } func checkPatterns(content string, patterns map[string]*regexp.Regexp) map[string][]string { matches := make(map[string][]string) for name, re := range patterns { foundMatches := re.FindAllString(content, -1) if foundMatches != nil { matches[name] = foundMatches } } return matches } func extractTarGz(tarGzPath, outputDir string) error { file, err := os.Open(tarGzPath) if err != nil { return err } defer file.Close() gzr, err := gzip.NewReader(file) if err != nil { return err } defer gzr.Close() tarReader := tar.NewReader(gzr) for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { return err } target := filepath.Join(outputDir, header.Name) switch header.Typeflag { case tar.TypeDir: if err := os.MkdirAll(target, os.ModePerm); err != nil { return err } case tar.TypeReg: outFile, err := os.Create(target) if err != nil { return err } if _, err := io.Copy(outFile, tarReader); err != nil { outFile.Close() return err } outFile.Close() default: //fmt.Printf("Unable to untar type: %c in file %s", header.Typeflag, header.Name) } } return nil } func loadIgnoreExtensions(filename string) ([]string, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() var ignoreExtensions IgnoreExtensions decoder := json.NewDecoder(file) if err := decoder.Decode(&ignoreExtensions); err != nil { return nil, err } return ignoreExtensions.Extensions, nil } func shouldSkipFile(filename string, ignoreExtensions []string) bool { for _, ext := range ignoreExtensions { if strings.HasSuffix(strings.ToLower(filename), ext) { return true } } return false } func removeDir(dir string) error { if _, err := os.Stat(dir); os.IsNotExist(err) { return nil } return os.RemoveAll(dir) } func printBanner() { banner := ` ╭━━━━━━━━╮┏━╮╭━┓ ┃┈┈┈┈┈┈┈┈┃╰╮╰╯╭╯ v1.1 ┃╰╯┈┈┈┈┈┈╰╮╰╮╭╯┈ DOCKERSPY by Alisson Moretto (UndeadSec) ┣━━╯┈┈┈┈┈┈╰━╯┃┈┈ AUTOMATED OSINT ON DOCKER HUB ╰━━━━━━━━━━━━╯┈┈` fmt.Println(color.New(color.FgGreen).Sprint(banner)) } func fetchPaginatedResults(url string) ([]struct { Name string `json:"repo_name"` Description string `json:"short_description"` PullCount int `json:"pull_count"` StarCount int `json:"star_count"` IsOfficial bool `json:"is_official"` }, error) { var allResults []struct { Name string `json:"repo_name"` Description string `json:"short_description"` PullCount int `json:"pull_count"` StarCount int `json:"star_count"` IsOfficial bool `json:"is_official"` } count := 0 for { if count >= 100 { break } resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("API response error: %s", resp.Status) } var searchResult SearchResult if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { return nil, err } allResults = append(allResults, searchResult.Results...) count += len(searchResult.Results) if searchResult.Next == "" { break } url = searchResult.Next } if len(allResults) > 100 { allResults = allResults[:100] } return allResults, nil } func main() { printBanner() err := removeDir("docker_image") if err != nil { fmt.Println("\nError removing docker_image directory:", err) return } regexPatterns, err := loadRegexPatterns("/etc/dockerspy/configs/regex_patterns.json") if err != nil { fmt.Println("\nError loading regex patterns:", err) return } ignoreExtensions, err := loadIgnoreExtensions("/etc/dockerspy/configs/ignore_extensions.json") if err != nil { fmt.Println("\nError loading ignore extensions:", err) return } scanner := bufio.NewScanner(os.Stdin) info := color.New(color.FgCyan).SprintFunc() warning := color.New(color.FgYellow).SprintFunc() errorColor := color.New(color.FgRed).SprintFunc() success := color.New(color.FgGreen).SprintFunc() highlight := color.New(color.FgHiMagenta, color.Bold).SprintFunc() for { fmt.Print(info("\nEnter search term (or 'exit' to quit): ")) scanner.Scan() searchTerm := scanner.Text() if strings.ToLower(searchTerm) == "exit" { break } dockerHubURL := "https://hub.docker.com/v2/search/repositories" params := url.Values{} params.Add("query", searchTerm) searchURL := fmt.Sprintf("%s?%s", dockerHubURL, params.Encode()) results, err := fetchPaginatedResults(searchURL) if err != nil { fmt.Println(errorColor("\nError fetching search results:"), err) continue } fmt.Printf(info("\nFound %d results for '%s':"), len(results), searchTerm) for i, result := range results { fmt.Printf("\n%s - Name: %s\nDescription: %s\nStars: %d\nOfficial: %t", highlight(i+1), result.Name, result.Description, result.StarCount, result.IsOfficial) } fmt.Print(info("\nChoose a number or enter the full name to view repository tags (or 'cancel' to search again): ")) scanner.Scan() choice := scanner.Text() if strings.ToLower(choice) == "cancel" { continue } var selectedRepo string choiceNum, err := strconv.Atoi(choice) if err == nil && choiceNum >= 1 && choiceNum <= len(results) { selectedRepo = results[choiceNum-1].Name } else { selectedRepo = choice } tagsURL := fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/tags", selectedRepo) resp, err := http.Get(tagsURL) if err != nil { fmt.Println(errorColor("\nError fetching tags:"), err) continue } defer resp.Body.Close() var tagsResult TagsResult if err := json.NewDecoder(resp.Body).Decode(&tagsResult); err != nil { fmt.Println(errorColor("\nError decoding JSON response:"), err) continue } fmt.Printf(info("Available tags for repository '%s':"), selectedRepo) for i, tag := range tagsResult.Results { fmt.Printf("\n%s - %s", highlight(i+1), tag.Name) } fmt.Print(info("\nChoose a number to download the tag (or 'cancel' to search again): ")) scanner.Scan() tagChoice := scanner.Text() if strings.ToLower(tagChoice) == "cancel" { continue } tagChoiceNum, err := strconv.Atoi(tagChoice) if err != nil || tagChoiceNum < 1 || tagChoiceNum > len(tagsResult.Results) { fmt.Println(warning("\nInvalid choice. Please try again.")) continue } tag := tagsResult.Results[tagChoiceNum-1].Name repo := selectedRepo outputDir := "./docker_image" token, err := getDockerHubToken(repo) if err != nil { fmt.Println("\nError getting token:", err) return } manifest, err := getManifest(repo, tag, token) if err != nil { fmt.Println("\nError getting manifest:", err) return } os.MkdirAll(outputDir, os.ModePerm) var envContent string matchesResult := make(map[string]map[string][]string) for _, layer := range manifest.Layers { digestParts := strings.Split(layer.Digest, ":") if len(digestParts) != 2 { fmt.Println("\nInvalid digest format:", layer.Digest) continue } outputPath := filepath.Join(outputDir, digestParts[1]+".tar.gz") fmt.Println("\nDownloading layer:", layer.Digest) if err := downloadLayer(repo, token, layer.Digest, outputPath, layer.Size); err != nil { fmt.Println("\nError downloading layer:", err) return } extractedDir := filepath.Join(outputDir, digestParts[1]) fmt.Println("\nExtracting layer:", outputPath) if err := extractTarGz(outputPath, extractedDir); err != nil { fmt.Println("\nError extracting layer:", err) continue } filepath.Walk(extractedDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && !shouldSkipFile(path, ignoreExtensions) { content, err := os.ReadFile(path) if err != nil { fmt.Println("\nError reading file:", err) return nil } if filepath.Base(path) == ".env" { fmt.Println(success("\nFound .env file:")) envContent = string(content) fmt.Println(envContent) } matches := checkPatterns(string(content), regexPatterns) if len(matches) > 0 { fmt.Println(success("\nMatches found in file:"), path) matchesResult[path] = matches for pattern, matchedStrings := range matches { fmt.Printf(" Pattern: %s\n", pattern) for _, match := range matchedStrings { fmt.Printf(" %s\n", match) } } } } return nil }) } fmt.Println(success("\nImage downloaded and extracted successfully\n")) resultData := map[string]interface{}{ "selectedRepo": selectedRepo, "selectedTag": tag, "envContent": envContent, "matches": matchesResult, } jsonFile, err := os.Create("results.json") if err != nil { fmt.Println(errorColor("\nError creating JSON file:"), err) return } defer jsonFile.Close() encoder := json.NewEncoder(jsonFile) if err := encoder.Encode(resultData); err != nil { fmt.Println(errorColor("\nError encoding JSON:"), err) return } fmt.Println(success("Results saved to results.json")) } } ================================================ FILE: src/configs/ignore_extensions.json ================================================ { "extensions": [".md",".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif", ".mp4", ".mp3", ".avi", ".mkv", ".mov", ".exe", ".dll", ".so", ".bin", ".dmg", ".iso", ".jar", ".bat", ".sh", ".msi"] } ================================================ FILE: src/configs/regex_patterns.json ================================================ { "amazon_mws_auth_token": "amzn\\\\.mws\\\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "amazon_aws_url": "s3\\.amazonaws.com[/]+|[a-zA-Z0-9_-]*\\.s3\\.amazonaws.com", "authorization_bearer": "bearer [a-zA-Z0-9_\\-\\.=:_\\+/]{5,100}", "github_access_token": "[a-zA-Z0-9_-]*:[a-zA-Z0-9_\\-]+@github\\.com*", "rsa_private_key": "-----BEGIN RSA PRIVATE KEY-----", "ssh_dsa_private_key": "-----BEGIN DSA PRIVATE KEY-----", "ssh_dc_private_key": "-----BEGIN EC PRIVATE KEY-----", "pgp_private_block": "-----BEGIN PGP PRIVATE KEY BLOCK-----", "slack_token": "\\\"api_token\\\":\\\"(xox[a-zA-Z]-[a-zA-Z0-9-]+)\\\"", "SSH_privKey": "([-]+BEGIN [^\\s]+ PRIVATE KEY[-]+[\\s]*[^-]*[-]+END [^\\s]+ PRIVATE KEY[-]+)" }